Decompiled source of GWCServerModpack v1.0.0

BepInEx/core/0Harmony.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using HarmonyLib.Internal.Patching;
using HarmonyLib.Internal.RuntimeFixes;
using HarmonyLib.Internal.Util;
using HarmonyLib.Public.Patching;
using HarmonyLib.Tools;
using JetBrains.Annotations;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.Utils;
using MonoMod.Utils.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("HarmonyTests")]
[assembly: InternalsVisibleTo("MonoMod.Utils.Cil.ILGeneratorProxy")]
[assembly: Guid("69aee16a-b6e7-4642-8081-3928b32455df")]
[assembly: AssemblyCompany("BepInEx")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © BepInEx 2022")]
[assembly: AssemblyDescription("A library for patching, replacing and decorating .NET and Mono methods during runtime powered by MonoMod.")]
[assembly: AssemblyFileVersion("2.9.0.0")]
[assembly: AssemblyInformationalVersion("2.9.0")]
[assembly: AssemblyProduct("HarmonyX")]
[assembly: AssemblyTitle("0Harmony")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.9.0.0")]
[module: UnverifiableCode]
namespace System
{
	internal struct ValueTuple<T1, T2>
	{
		public T1 Item1;

		public T2 Item2;

		public ValueTuple(T1 first, T2 second)
		{
			Item1 = first;
			Item2 = second;
		}
	}
	internal struct ValueTuple<T1, T2, T3>
	{
		public T1 Item1;

		public T2 Item2;

		public T3 Item3;

		public ValueTuple(T1 first, T2 second, T3 third)
		{
			Item1 = first;
			Item2 = second;
			Item3 = third;
		}
	}
}
namespace JetBrains.Annotations
{
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class UsedImplicitlyAttribute : Attribute
	{
		public ImplicitUseKindFlags UseKindFlags { get; }

		public ImplicitUseTargetFlags TargetFlags { get; }

		public UsedImplicitlyAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)]
	internal sealed class MeansImplicitUseAttribute : Attribute
	{
		[UsedImplicitly]
		public ImplicitUseKindFlags UseKindFlags { get; }

		[UsedImplicitly]
		public ImplicitUseTargetFlags TargetFlags { get; }

		public MeansImplicitUseAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[Flags]
	internal enum ImplicitUseKindFlags
	{
		Default = 7,
		Access = 1,
		Assign = 2,
		InstantiatedWithFixedConstructorSignature = 4,
		InstantiatedNoFixedConstructorSignature = 8
	}
	[Flags]
	internal enum ImplicitUseTargetFlags
	{
		Default = 1,
		Itself = 1,
		Members = 2,
		WithInheritors = 4,
		WithMembers = 3
	}
}
namespace HarmonyLib
{
	public class DelegateTypeFactory
	{
		private class DelegateEntry
		{
			public CallingConvention? callingConvention;

			public Type delegateType;
		}

		private static int counter;

		private static readonly Dictionary<MethodInfo, List<DelegateEntry>> TypeCache = new Dictionary<MethodInfo, List<DelegateEntry>>();

		private static readonly MethodBase CallingConvAttr = AccessTools.Constructor(typeof(UnmanagedFunctionPointerAttribute), new Type[1] { typeof(CallingConvention) });

		public static readonly DelegateTypeFactory instance = new DelegateTypeFactory();

		public Type CreateDelegateType(Type returnType, Type[] argTypes)
		{
			return CreateDelegateType(returnType, argTypes, null);
		}

		public Type CreateDelegateType(Type returnType, Type[] argTypes, CallingConvention? convention)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Expected O, but got Unknown
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			counter++;
			AssemblyDefinition val = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition($"HarmonyDTFAssembly{counter}", new Version(1, 0)), $"HarmonyDTFModule{counter}", (ModuleKind)0);
			ModuleDefinition module = val.MainModule;
			TypeDefinition val2 = new TypeDefinition("", $"HarmonyDTFType{counter}", (TypeAttributes)257)
			{
				BaseType = module.ImportReference(typeof(MulticastDelegate))
			};
			module.Types.Add(val2);
			if (convention.HasValue)
			{
				CustomAttribute val3 = new CustomAttribute(module.ImportReference(CallingConvAttr));
				val3.ConstructorArguments.Add(new CustomAttributeArgument(module.ImportReference(typeof(CallingConvention)), (object)convention.Value));
				val2.CustomAttributes.Add(val3);
			}
			MethodDefinition val4 = new MethodDefinition(".ctor", (MethodAttributes)4230, module.ImportReference(typeof(void)))
			{
				ImplAttributes = (MethodImplAttributes)3
			};
			Extensions.AddRange<ParameterDefinition>(((MethodReference)val4).Parameters, (IEnumerable<ParameterDefinition>)(object)new ParameterDefinition[2]
			{
				new ParameterDefinition(module.ImportReference(typeof(object))),
				new ParameterDefinition(module.ImportReference(typeof(IntPtr)))
			});
			val2.Methods.Add(val4);
			MethodDefinition val5 = new MethodDefinition("Invoke", (MethodAttributes)198, module.ImportReference(returnType))
			{
				ImplAttributes = (MethodImplAttributes)3
			};
			Extensions.AddRange<ParameterDefinition>(((MethodReference)val5).Parameters, ((IEnumerable<Type>)argTypes).Select((Func<Type, ParameterDefinition>)((Type t) => new ParameterDefinition(module.ImportReference(t)))));
			val2.Methods.Add(val5);
			return ReflectionHelper.Load(val.MainModule).GetType($"HarmonyDTFType{counter}");
		}

		public Type CreateDelegateType(MethodInfo method)
		{
			return CreateDelegateType(method, null);
		}

		public Type CreateDelegateType(MethodInfo method, CallingConvention? convention)
		{
			DelegateEntry delegateEntry;
			if (TypeCache.TryGetValue(method, out var value) && (delegateEntry = value.FirstOrDefault((DelegateEntry e) => e.callingConvention == convention)) != null)
			{
				return delegateEntry.delegateType;
			}
			if (value == null)
			{
				value = (TypeCache[method] = new List<DelegateEntry>());
			}
			delegateEntry = new DelegateEntry
			{
				delegateType = CreateDelegateType(method.ReturnType, method.GetParameters().Types().ToArray(), convention),
				callingConvention = convention
			};
			value.Add(delegateEntry);
			return delegateEntry.delegateType;
		}
	}
	[Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Func<T, S>> for property getters")]
	public delegate S GetterHandler<in T, out S>(T source);
	[Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Action<T, S>> for property setters")]
	public delegate void SetterHandler<in T, in S>(T source, S value);
	public delegate T InstantiationHandler<out T>();
	public static class FastAccess
	{
		public static InstantiationHandler<T> CreateInstantiationHandler<T>()
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			ConstructorInfo constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
			if ((object)constructor == null)
			{
				throw new ApplicationException($"The type {typeof(T)} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).");
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition("InstantiateObject_" + typeof(T).Name, typeof(T), (Type[])null);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Newobj, constructor);
			iLGenerator.Emit(OpCodes.Ret);
			return (InstantiationHandler<T>)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(InstantiationHandler<T>));
		}

		[Obsolete("Use AccessTools.MethodDelegate<Func<T, S>>(PropertyInfo.GetGetMethod(true))")]
		public static GetterHandler<T, S> CreateGetterHandler<T, S>(PropertyInfo propertyInfo)
		{
			MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true);
			DynamicMethodDefinition obj = CreateGetDynamicMethod<T, S>(propertyInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Call, getMethod);
			iLGenerator.Emit(OpCodes.Ret);
			return (GetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(GetterHandler<T, S>));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
		public static GetterHandler<T, S> CreateGetterHandler<T, S>(FieldInfo fieldInfo)
		{
			DynamicMethodDefinition obj = CreateGetDynamicMethod<T, S>(fieldInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldfld, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return (GetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(GetterHandler<T, S>));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(name) for fields and AccessTools.MethodDelegate<Func<T, S>>(AccessTools.PropertyGetter(typeof(T), name)) for properties")]
		public static GetterHandler<T, S> CreateFieldGetter<T, S>(params string[] names)
		{
			foreach (string name in names)
			{
				FieldInfo field = typeof(T).GetField(name, AccessTools.all);
				if ((object)field != null)
				{
					return CreateGetterHandler<T, S>(field);
				}
				PropertyInfo property = typeof(T).GetProperty(name, AccessTools.all);
				if ((object)property != null)
				{
					return CreateGetterHandler<T, S>(property);
				}
			}
			return null;
		}

		[Obsolete("Use AccessTools.MethodDelegate<Action<T, S>>(PropertyInfo.GetSetMethod(true))")]
		public static SetterHandler<T, S> CreateSetterHandler<T, S>(PropertyInfo propertyInfo)
		{
			MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
			DynamicMethodDefinition obj = CreateSetDynamicMethod<T, S>(propertyInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Call, setMethod);
			iLGenerator.Emit(OpCodes.Ret);
			return (SetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(SetterHandler<T, S>));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
		public static SetterHandler<T, S> CreateSetterHandler<T, S>(FieldInfo fieldInfo)
		{
			DynamicMethodDefinition obj = CreateSetDynamicMethod<T, S>(fieldInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Stfld, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return (SetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(SetterHandler<T, S>));
		}

		private static DynamicMethodDefinition CreateGetDynamicMethod<T, S>(Type type)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			return new DynamicMethodDefinition("DynamicGet_" + type.Name, typeof(S), new Type[1] { typeof(T) });
		}

		private static DynamicMethodDefinition CreateSetDynamicMethod<T, S>(Type type)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			return new DynamicMethodDefinition("DynamicSet_" + type.Name, typeof(void), new Type[2]
			{
				typeof(T),
				typeof(S)
			});
		}
	}
	public delegate object FastInvokeHandler(object target, params object[] parameters);
	public static class MethodInvoker
	{
		public static FastInvokeHandler GetHandler(MethodInfo methodInfo, bool directBoxValueAccess = false)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			DynamicMethodDefinition val = new DynamicMethodDefinition("FastInvoke_" + methodInfo.Name + "_" + (directBoxValueAccess ? "direct" : "indirect"), typeof(object), new Type[2]
			{
				typeof(object),
				typeof(object[])
			});
			ILGenerator iLGenerator = val.GetILGenerator();
			if (!methodInfo.IsStatic)
			{
				Emit(iLGenerator, OpCodes.Ldarg_0);
				EmitUnboxIfNeeded(iLGenerator, methodInfo.DeclaringType);
			}
			bool flag = true;
			ParameterInfo[] parameters = methodInfo.GetParameters();
			for (int i = 0; i < parameters.Length; i++)
			{
				Type type = parameters[i].ParameterType;
				bool isByRef = type.IsByRef;
				if (isByRef)
				{
					type = type.GetElementType();
				}
				bool isValueType = type.IsValueType;
				if (isByRef && isValueType && !directBoxValueAccess)
				{
					Emit(iLGenerator, OpCodes.Ldarg_1);
					EmitFastInt(iLGenerator, i);
				}
				Emit(iLGenerator, OpCodes.Ldarg_1);
				EmitFastInt(iLGenerator, i);
				if (isByRef && !isValueType)
				{
					Emit(iLGenerator, OpCodes.Ldelema, typeof(object));
					continue;
				}
				Emit(iLGenerator, OpCodes.Ldelem_Ref);
				if (!isValueType)
				{
					continue;
				}
				if (!isByRef || !directBoxValueAccess)
				{
					Emit(iLGenerator, OpCodes.Unbox_Any, type);
					if (isByRef)
					{
						Emit(iLGenerator, OpCodes.Box, type);
						Emit(iLGenerator, OpCodes.Dup);
						if (flag)
						{
							flag = false;
							iLGenerator.DeclareLocal(typeof(object), pinned: false);
						}
						Emit(iLGenerator, OpCodes.Stloc_0);
						Emit(iLGenerator, OpCodes.Stelem_Ref);
						Emit(iLGenerator, OpCodes.Ldloc_0);
						Emit(iLGenerator, OpCodes.Unbox, type);
					}
				}
				else
				{
					Emit(iLGenerator, OpCodes.Unbox, type);
				}
			}
			if (methodInfo.IsStatic)
			{
				EmitCall(iLGenerator, OpCodes.Call, methodInfo);
			}
			else
			{
				EmitCall(iLGenerator, OpCodes.Callvirt, methodInfo);
			}
			if ((object)methodInfo.ReturnType == typeof(void))
			{
				Emit(iLGenerator, OpCodes.Ldnull);
			}
			else
			{
				EmitBoxIfNeeded(iLGenerator, methodInfo.ReturnType);
			}
			Emit(iLGenerator, OpCodes.Ret);
			return (FastInvokeHandler)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(FastInvokeHandler));
		}

		internal static void Emit(ILGenerator il, OpCode opcode)
		{
			il.Emit(opcode);
		}

		internal static void Emit(ILGenerator il, OpCode opcode, Type type)
		{
			il.Emit(opcode, type);
		}

		internal static void EmitCall(ILGenerator il, OpCode opcode, MethodInfo methodInfo)
		{
			il.EmitCall(opcode, methodInfo, null);
		}

		private static void EmitUnboxIfNeeded(ILGenerator il, Type type)
		{
			if (type.IsValueType)
			{
				Emit(il, OpCodes.Unbox_Any, type);
			}
		}

		private static void EmitBoxIfNeeded(ILGenerator il, Type type)
		{
			if (type.IsValueType)
			{
				Emit(il, OpCodes.Box, type);
			}
		}

		internal static void EmitFastInt(ILGenerator il, int value)
		{
			switch (value)
			{
			case -1:
				il.Emit(OpCodes.Ldc_I4_M1);
				return;
			case 0:
				il.Emit(OpCodes.Ldc_I4_0);
				return;
			case 1:
				il.Emit(OpCodes.Ldc_I4_1);
				return;
			case 2:
				il.Emit(OpCodes.Ldc_I4_2);
				return;
			case 3:
				il.Emit(OpCodes.Ldc_I4_3);
				return;
			case 4:
				il.Emit(OpCodes.Ldc_I4_4);
				return;
			case 5:
				il.Emit(OpCodes.Ldc_I4_5);
				return;
			case 6:
				il.Emit(OpCodes.Ldc_I4_6);
				return;
			case 7:
				il.Emit(OpCodes.Ldc_I4_7);
				return;
			case 8:
				il.Emit(OpCodes.Ldc_I4_8);
				return;
			}
			if (value > -129 && value < 128)
			{
				il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
			}
			else
			{
				il.Emit(OpCodes.Ldc_I4, value);
			}
		}
	}
	internal class AccessCache
	{
		internal enum MemberType
		{
			Any,
			Static,
			Instance
		}

		private const BindingFlags BasicFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty;

		private static readonly Dictionary<MemberType, BindingFlags> declaredOnlyBindingFlags = new Dictionary<MemberType, BindingFlags>
		{
			{
				MemberType.Any,
				BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty
			},
			{
				MemberType.Instance,
				BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty
			},
			{
				MemberType.Static,
				BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty
			}
		};

		private readonly Dictionary<Type, Dictionary<string, FieldInfo>> declaredFields = new Dictionary<Type, Dictionary<string, FieldInfo>>();

		private readonly Dictionary<Type, Dictionary<string, PropertyInfo>> declaredProperties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();

		private readonly Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>> declaredMethods = new Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>>();

		private readonly Dictionary<Type, Dictionary<string, FieldInfo>> inheritedFields = new Dictionary<Type, Dictionary<string, FieldInfo>>();

		private readonly Dictionary<Type, Dictionary<string, PropertyInfo>> inheritedProperties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();

		private readonly Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>> inheritedMethods = new Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>>();

		private static T Get<T>(Dictionary<Type, Dictionary<string, T>> dict, Type type, string name, Func<T> fetcher)
		{
			lock (dict)
			{
				if (!dict.TryGetValue(type, out var value))
				{
					value = (dict[type] = new Dictionary<string, T>());
				}
				if (!value.TryGetValue(name, out var value2))
				{
					value2 = (value[name] = fetcher());
				}
				return value2;
			}
		}

		private static T Get<T>(Dictionary<Type, Dictionary<string, Dictionary<int, T>>> dict, Type type, string name, Type[] arguments, Func<T> fetcher)
		{
			lock (dict)
			{
				if (!dict.TryGetValue(type, out var value))
				{
					value = (dict[type] = new Dictionary<string, Dictionary<int, T>>());
				}
				if (!value.TryGetValue(name, out var value2))
				{
					value2 = (value[name] = new Dictionary<int, T>());
				}
				int key = AccessTools.CombinedHashCode(arguments);
				if (!value2.TryGetValue(key, out var value3))
				{
					value3 = (value2[key] = fetcher());
				}
				return value3;
			}
		}

		internal FieldInfo GetFieldInfo(Type type, string name, MemberType memberType = MemberType.Any, bool declaredOnly = false)
		{
			FieldInfo fieldInfo = Get(declaredFields, type, name, () => type.GetField(name, declaredOnlyBindingFlags[memberType]));
			if ((object)fieldInfo == null && !declaredOnly)
			{
				fieldInfo = Get(inheritedFields, type, name, () => AccessTools.FindIncludingBaseTypes(type, (Type t) => t.GetField(name, AccessTools.all)));
			}
			return fieldInfo;
		}

		internal PropertyInfo GetPropertyInfo(Type type, string name, MemberType memberType = MemberType.Any, bool declaredOnly = false)
		{
			PropertyInfo propertyInfo = Get(declaredProperties, type, name, () => type.GetProperty(name, declaredOnlyBindingFlags[memberType]));
			if ((object)propertyInfo == null && !declaredOnly)
			{
				propertyInfo = Get(inheritedProperties, type, name, () => AccessTools.FindIncludingBaseTypes(type, (Type t) => t.GetProperty(name, AccessTools.all)));
			}
			return propertyInfo;
		}

		internal MethodBase GetMethodInfo(Type type, string name, Type[] arguments, MemberType memberType = MemberType.Any, bool declaredOnly = false)
		{
			MethodBase methodBase = Get(declaredMethods, type, name, arguments, () => type.GetMethod(name, declaredOnlyBindingFlags[memberType], null, arguments, null));
			if ((object)methodBase == null && !declaredOnly)
			{
				methodBase = Get(inheritedMethods, type, name, arguments, () => AccessTools.Method(type, name, arguments));
			}
			return methodBase;
		}
	}
	internal static class PatchArgumentExtensions
	{
		private static HarmonyArgument[] AllHarmonyArguments(object[] attributes)
		{
			return (from attr in attributes
				select (attr.GetType().Name != "HarmonyArgument") ? null : AccessTools.MakeDeepCopy<HarmonyArgument>(attr) into harg
				where harg != null
				select harg).ToArray();
		}

		private static HarmonyArgument GetArgumentAttribute(this ParameterInfo parameter)
		{
			return AllHarmonyArguments(parameter.GetCustomAttributes(inherit: false)).FirstOrDefault();
		}

		private static HarmonyArgument[] GetArgumentAttributes(this MethodInfo method)
		{
			if ((object)method == null || method is DynamicMethod)
			{
				return null;
			}
			return AllHarmonyArguments(method.GetCustomAttributes(inherit: false));
		}

		private static HarmonyArgument[] GetArgumentAttributes(this Type type)
		{
			return AllHarmonyArguments(type.GetCustomAttributes(inherit: false));
		}

		private static string GetOriginalArgumentName(this ParameterInfo parameter, string[] originalParameterNames)
		{
			HarmonyArgument argumentAttribute = parameter.GetArgumentAttribute();
			if (argumentAttribute == null)
			{
				return null;
			}
			if (!string.IsNullOrEmpty(argumentAttribute.OriginalName))
			{
				return argumentAttribute.OriginalName;
			}
			if (argumentAttribute.Index >= 0 && argumentAttribute.Index < originalParameterNames.Length)
			{
				return originalParameterNames[argumentAttribute.Index];
			}
			return null;
		}

		private static string GetOriginalArgumentName(HarmonyArgument[] attributes, string name, string[] originalParameterNames)
		{
			if (((attributes != null && attributes.Length != 0) ? 1 : 0) <= (false ? 1 : 0))
			{
				return null;
			}
			HarmonyArgument harmonyArgument = attributes.SingleOrDefault((HarmonyArgument p) => p.NewName == name);
			if (harmonyArgument == null)
			{
				return null;
			}
			if (!string.IsNullOrEmpty(harmonyArgument.OriginalName))
			{
				return harmonyArgument.OriginalName;
			}
			if (originalParameterNames != null && harmonyArgument.Index >= 0 && harmonyArgument.Index < originalParameterNames.Length)
			{
				return originalParameterNames[harmonyArgument.Index];
			}
			return null;
		}

		private static string GetOriginalArgumentName(this MethodInfo method, string[] originalParameterNames, string name)
		{
			string originalArgumentName = GetOriginalArgumentName(((object)method != null) ? method.GetArgumentAttributes() : null, name, originalParameterNames);
			if (originalArgumentName != null)
			{
				return originalArgumentName;
			}
			object attributes;
			if ((object)method == null)
			{
				attributes = null;
			}
			else
			{
				Type? declaringType = method.DeclaringType;
				attributes = (((object)declaringType != null) ? declaringType.GetArgumentAttributes() : null);
			}
			originalArgumentName = GetOriginalArgumentName((HarmonyArgument[])attributes, name, originalParameterNames);
			if (originalArgumentName != null)
			{
				return originalArgumentName;
			}
			return name;
		}

		internal static int GetArgumentIndex(this MethodInfo patch, string[] originalParameterNames, ParameterInfo patchParam)
		{
			if (patch is DynamicMethod)
			{
				return Array.IndexOf<string>(originalParameterNames, patchParam.Name);
			}
			string originalArgumentName = patchParam.GetOriginalArgumentName(originalParameterNames);
			if (originalArgumentName != null)
			{
				return Array.IndexOf(originalParameterNames, originalArgumentName);
			}
			originalArgumentName = patch.GetOriginalArgumentName(originalParameterNames, patchParam.Name);
			if (originalArgumentName != null)
			{
				return Array.IndexOf(originalParameterNames, originalArgumentName);
			}
			return -1;
		}
	}
	internal static class PatchFunctions
	{
		internal static List<MethodInfo> GetSortedPatchMethods(MethodBase original, Patch[] patches, bool debug)
		{
			return new PatchSorter(patches, debug).Sort(original);
		}

		internal static Patch[] GetSortedPatchMethodsAsPatches(MethodBase original, Patch[] patches, bool debug)
		{
			return new PatchSorter(patches, debug).SortAsPatches(original);
		}

		internal static MethodInfo UpdateWrapper(MethodBase original, PatchInfo patchInfo)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			MethodPatcher methodPatcher = original.GetMethodPatcher();
			DynamicMethodDefinition val = methodPatcher.PrepareOriginal();
			if (val != null)
			{
				ILContext ctx = new ILContext(val.Definition);
				HarmonyManipulator.Manipulate(original, patchInfo, ctx);
			}
			try
			{
				return methodPatcher.DetourTo((val != null) ? val.Generate() : null) as MethodInfo;
			}
			catch (Exception ex)
			{
				object body;
				if (val == null)
				{
					body = null;
				}
				else
				{
					MethodDefinition definition = val.Definition;
					body = ((definition != null) ? definition.Body : null);
				}
				throw HarmonyException.Create(ex, (MethodBody)body);
			}
		}

		internal static MethodInfo ReversePatch(HarmonyMethod standin, MethodBase original, MethodInfo postTranspiler, MethodInfo postManipulator)
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			if (standin == null)
			{
				throw new ArgumentNullException("standin");
			}
			if ((object)standin.method == null)
			{
				throw new ArgumentNullException("standin", "standin.method is NULL");
			}
			bool debug = standin.debug.GetValueOrDefault();
			List<MethodInfo> transpilers = new List<MethodInfo>();
			List<MethodInfo> ilmanipulators = new List<MethodInfo>();
			if (standin.reversePatchType == HarmonyReversePatchType.Snapshot)
			{
				Patches patchInfo = Harmony.GetPatchInfo(original);
				transpilers.AddRange(GetSortedPatchMethods(original, patchInfo.Transpilers.ToArray(), debug));
				ilmanipulators.AddRange(GetSortedPatchMethods(original, patchInfo.ILManipulators.ToArray(), debug));
			}
			if ((object)postTranspiler != null)
			{
				transpilers.Add(postTranspiler);
			}
			if ((object)postManipulator != null)
			{
				ilmanipulators.Add(postManipulator);
			}
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("Reverse patching " + standin.method.FullDescription() + " with " + original.FullDescription());
				PrintInfo(stringBuilder, transpilers, "Transpiler");
				PrintInfo(stringBuilder, ilmanipulators, "Manipulators");
				return stringBuilder.ToString();
			}, debug);
			MethodBody patchBody = null;
			ILHook val = new ILHook((MethodBase)standin.method, (Manipulator)delegate(ILContext ctx)
			{
				//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fb: Expected O, but got Unknown
				//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
				if (original is MethodInfo methodInfo2)
				{
					patchBody = ctx.Body;
					MethodPatcher methodPatcher = methodInfo2.GetMethodPatcher();
					DynamicMethodDefinition val2 = methodPatcher.CopyOriginal();
					if (val2 == null)
					{
						throw new NullReferenceException("Cannot reverse patch " + methodInfo2.FullDescription() + ": method patcher (" + methodPatcher.GetType().FullDescription() + ") can't copy original method body");
					}
					ILManipulator iLManipulator = new ILManipulator(val2.Definition.Body, debug);
					ctx.Body.Variables.Clear();
					Enumerator<VariableDefinition> enumerator2 = iLManipulator.Body.Variables.GetEnumerator();
					try
					{
						while (enumerator2.MoveNext())
						{
							VariableDefinition current2 = enumerator2.Current;
							ctx.Body.Variables.Add(new VariableDefinition(ctx.Module.ImportReference(((VariableReference)current2).VariableType)));
						}
					}
					finally
					{
						((IDisposable)enumerator2).Dispose();
					}
					foreach (MethodInfo item in transpilers)
					{
						iLManipulator.AddTranspiler(item);
					}
					iLManipulator.WriteTo(ctx.Body, standin.method);
					HarmonyManipulator.ApplyManipulators(ctx, original, ilmanipulators, null);
					Instruction val3 = null;
					foreach (Instruction item2 in ((IEnumerable<Instruction>)ctx.Instrs).Where((Instruction i) => i.OpCode == OpCodes.Ret))
					{
						if (val3 == null)
						{
							val3 = ctx.IL.Create(OpCodes.Ret);
						}
						item2.OpCode = OpCodes.Br;
						item2.Operand = val3;
					}
					if (val3 != null)
					{
						ctx.IL.Append(val3);
					}
					Logger.Log(Logger.LogChannel.IL, () => "Generated reverse patcher (" + ((MemberReference)ctx.Method).FullName + "):\n" + ctx.Body.ToILDasmString(), debug);
				}
			}, new ILHookConfig
			{
				ManualApply = true
			});
			try
			{
				val.Apply();
			}
			catch (Exception ex)
			{
				throw HarmonyException.Create(ex, patchBody);
			}
			MethodInfo methodInfo = val.GetCurrentTarget() as MethodInfo;
			PatchTools.RememberObject(standin.method, methodInfo);
			return methodInfo;
			static void PrintInfo(StringBuilder sb, ICollection<MethodInfo> methods, string name)
			{
				if (methods.Count <= 0)
				{
					return;
				}
				sb.AppendLine(name + ":");
				foreach (MethodInfo method in methods)
				{
					sb.AppendLine("  * " + method.FullDescription());
				}
			}
		}

		internal static IEnumerable<CodeInstruction> ApplyTranspilers(MethodBase methodBase, ILGenerator generator, int maxTranspilers = 0)
		{
			MethodPatcher methodPatcher = methodBase.GetMethodPatcher();
			DynamicMethodDefinition val = methodPatcher.CopyOriginal();
			if (val == null)
			{
				throw new NullReferenceException("Cannot reverse patch " + methodBase.FullDescription() + ": method patcher (" + methodPatcher.GetType().FullDescription() + ") can't copy original method body");
			}
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body, debug: false);
			PatchInfo patchInfo = methodBase.GetPatchInfo();
			if (patchInfo != null)
			{
				List<MethodInfo> sortedPatchMethods = GetSortedPatchMethods(methodBase, patchInfo.transpilers, debug: false);
				for (int i = 0; i < maxTranspilers && i < sortedPatchMethods.Count; i++)
				{
					iLManipulator.AddTranspiler(sortedPatchMethods[i]);
				}
			}
			return iLManipulator.GetInstructions(generator, methodBase);
		}

		internal static void UnpatchConditional(Func<Patch, bool> executionCondition)
		{
			foreach (MethodBase item in PatchProcessor.GetAllPatchedMethods().ToList())
			{
				bool num = item.HasMethodBody();
				Patches patchInfo2 = PatchProcessor.GetPatchInfo(item);
				PatchProcessor patchProcessor = new PatchProcessor(null, item);
				if (num)
				{
					patchInfo2.Postfixes.DoIf(executionCondition, delegate(Patch patchInfo)
					{
						patchProcessor.Unpatch(patchInfo.PatchMethod);
					});
					patchInfo2.Prefixes.DoIf(executionCondition, delegate(Patch patchInfo)
					{
						patchProcessor.Unpatch(patchInfo.PatchMethod);
					});
				}
				patchInfo2.ILManipulators.DoIf(executionCondition, delegate(Patch patchInfo)
				{
					patchProcessor.Unpatch(patchInfo.PatchMethod);
				});
				patchInfo2.Transpilers.DoIf(executionCondition, delegate(Patch patchInfo)
				{
					patchProcessor.Unpatch(patchInfo.PatchMethod);
				});
				if (num)
				{
					patchInfo2.Finalizers.DoIf(executionCondition, delegate(Patch patchInfo)
					{
						patchProcessor.Unpatch(patchInfo.PatchMethod);
					});
				}
			}
		}
	}
	internal class PatchJobs<T>
	{
		internal class Job
		{
			internal MethodBase original;

			internal T replacement;

			internal List<HarmonyMethod> prefixes = new List<HarmonyMethod>();

			internal List<HarmonyMethod> postfixes = new List<HarmonyMethod>();

			internal List<HarmonyMethod> transpilers = new List<HarmonyMethod>();

			internal List<HarmonyMethod> finalizers = new List<HarmonyMethod>();

			internal List<HarmonyMethod> ilmanipulators = new List<HarmonyMethod>();

			internal void AddPatch(AttributePatch patch)
			{
				HarmonyPatchType? type = patch.type;
				if (type.HasValue)
				{
					switch (type.GetValueOrDefault())
					{
					case HarmonyPatchType.Prefix:
						prefixes.Add(patch.info);
						break;
					case HarmonyPatchType.Postfix:
						postfixes.Add(patch.info);
						break;
					case HarmonyPatchType.Transpiler:
						transpilers.Add(patch.info);
						break;
					case HarmonyPatchType.Finalizer:
						finalizers.Add(patch.info);
						break;
					case HarmonyPatchType.ILManipulator:
						ilmanipulators.Add(patch.info);
						break;
					case HarmonyPatchType.ReversePatch:
						break;
					}
				}
			}
		}

		internal Dictionary<MethodBase, Job> state = new Dictionary<MethodBase, Job>();

		internal Job GetJob(MethodBase method)
		{
			if ((object)method == null)
			{
				return null;
			}
			if (!state.TryGetValue(method, out var value))
			{
				value = new Job
				{
					original = method
				};
				state[method] = value;
			}
			return value;
		}

		internal List<Job> GetJobs()
		{
			return state.Values.Where((Job job) => job.prefixes.Count + job.postfixes.Count + job.transpilers.Count + job.finalizers.Count + job.ilmanipulators.Count > 0).ToList();
		}

		internal List<T> GetReplacements()
		{
			return state.Values.Select((Job job) => job.replacement).ToList();
		}
	}
	internal class AttributePatch
	{
		private static readonly HarmonyPatchType[] allPatchTypes = new HarmonyPatchType[6]
		{
			HarmonyPatchType.Prefix,
			HarmonyPatchType.Postfix,
			HarmonyPatchType.Transpiler,
			HarmonyPatchType.Finalizer,
			HarmonyPatchType.ReversePatch,
			HarmonyPatchType.ILManipulator
		};

		internal HarmonyMethod info;

		internal HarmonyPatchType? type;

		private static readonly string harmonyAttributeName = typeof(HarmonyAttribute).FullName;

		internal static IEnumerable<AttributePatch> Create(MethodInfo patch, bool collectIncomplete = false)
		{
			if ((object)patch == null)
			{
				throw new NullReferenceException("Patch method cannot be null");
			}
			object[] customAttributes = patch.GetCustomAttributes(inherit: true);
			string name = patch.Name;
			HarmonyPatchType? type = GetPatchType(name, customAttributes);
			if (!type.HasValue)
			{
				return Enumerable.Empty<AttributePatch>();
			}
			if (type != HarmonyPatchType.ReversePatch && !patch.IsStatic)
			{
				throw new ArgumentException("Patch method " + patch.FullDescription() + " must be static");
			}
			List<HarmonyMethod> list = (from attr in customAttributes
				where attr.GetType().BaseType.FullName == harmonyAttributeName
				select AccessTools.Field(attr.GetType(), "info").GetValue(attr) into harmonyInfo
				select AccessTools.MakeDeepCopy<HarmonyMethod>(harmonyInfo)).ToList();
			List<HarmonyMethod> list2 = new List<HarmonyMethod>();
			ILookup<bool, HarmonyMethod> lookup = list.ToLookup((HarmonyMethod m) => IsComplete(m, collectIncomplete));
			List<HarmonyMethod> incomplete = lookup[false].ToList();
			HarmonyMethod info = HarmonyMethod.Merge(incomplete);
			List<HarmonyMethod> list3 = lookup[true].Where((HarmonyMethod m) => !Same(m, info)).ToList();
			if (list3.Count > 1)
			{
				list2.AddRange(list3.Select((HarmonyMethod m) => HarmonyMethod.Merge(incomplete.AddItem(m))));
			}
			else
			{
				list2.Add(HarmonyMethod.Merge(list));
			}
			foreach (HarmonyMethod item in list2)
			{
				item.method = patch;
			}
			return list2.Select((HarmonyMethod i) => new AttributePatch
			{
				info = i,
				type = type
			}).ToList();
			static bool IsComplete(HarmonyMethod m, bool collectIncomplete)
			{
				if (collectIncomplete || (object)m.GetDeclaringType() != null)
				{
					return m.methodName != null;
				}
				return false;
			}
			static bool Same(HarmonyMethod m1, HarmonyMethod m2)
			{
				if ((object)m1.GetDeclaringType() == m2.GetDeclaringType() && m1.methodName == m2.methodName)
				{
					return m1.GetArgumentList().SequenceEqual(m2.GetArgumentList());
				}
				return false;
			}
		}

		private static HarmonyPatchType? GetPatchType(string methodName, object[] allAttributes)
		{
			HashSet<string> hashSet = new HashSet<string>(from attr in allAttributes
				select attr.GetType().FullName into name
				where name.StartsWith("Harmony")
				select name);
			HarmonyPatchType? result = null;
			HarmonyPatchType[] array = allPatchTypes;
			for (int i = 0; i < array.Length; i++)
			{
				HarmonyPatchType value = array[i];
				string text = value.ToString();
				if (text == methodName || hashSet.Contains("HarmonyLib.Harmony" + text))
				{
					result = value;
					break;
				}
			}
			return result;
		}
	}
	internal class PatchSorter
	{
		private class PatchSortingWrapper : IComparable
		{
			internal readonly HashSet<PatchSortingWrapper> after;

			internal readonly HashSet<PatchSortingWrapper> before;

			internal readonly Patch innerPatch;

			internal PatchSortingWrapper(Patch patch)
			{
				innerPatch = patch;
				before = new HashSet<PatchSortingWrapper>();
				after = new HashSet<PatchSortingWrapper>();
			}

			public int CompareTo(object obj)
			{
				return PatchInfoSerialization.PriorityComparer((obj as PatchSortingWrapper)?.innerPatch, innerPatch.index, innerPatch.priority);
			}

			public override bool Equals(object obj)
			{
				if (obj is PatchSortingWrapper patchSortingWrapper)
				{
					return (object)innerPatch.PatchMethod == patchSortingWrapper.innerPatch.PatchMethod;
				}
				return false;
			}

			public override int GetHashCode()
			{
				return innerPatch.PatchMethod.GetHashCode();
			}

			internal void AddBeforeDependency(IEnumerable<PatchSortingWrapper> dependencies)
			{
				foreach (PatchSortingWrapper dependency in dependencies)
				{
					before.Add(dependency);
					dependency.after.Add(this);
				}
			}

			internal void AddAfterDependency(IEnumerable<PatchSortingWrapper> dependencies)
			{
				foreach (PatchSortingWrapper dependency in dependencies)
				{
					after.Add(dependency);
					dependency.before.Add(this);
				}
			}

			internal void RemoveAfterDependency(PatchSortingWrapper afterNode)
			{
				after.Remove(afterNode);
				afterNode.before.Remove(this);
			}

			internal void RemoveBeforeDependency(PatchSortingWrapper beforeNode)
			{
				before.Remove(beforeNode);
				beforeNode.after.Remove(this);
			}
		}

		internal class PatchDetailedComparer : IEqualityComparer<Patch>
		{
			public bool Equals(Patch x, Patch y)
			{
				if (y != null && x != null && x.owner == y.owner && (object)x.PatchMethod == y.PatchMethod && x.index == y.index && x.priority == y.priority && x.before.Length == y.before.Length && x.after.Length == y.after.Length && x.before.All(((IEnumerable<string>)y.before).Contains<string>))
				{
					return x.after.All(((IEnumerable<string>)y.after).Contains<string>);
				}
				return false;
			}

			public int GetHashCode(Patch obj)
			{
				return obj.GetHashCode();
			}
		}

		private List<PatchSortingWrapper> patches;

		private HashSet<PatchSortingWrapper> handledPatches;

		private List<PatchSortingWrapper> result;

		private List<PatchSortingWrapper> waitingList;

		internal Patch[] sortedPatchArray;

		private readonly bool debug;

		internal PatchSorter(Patch[] patches, bool debug = false)
		{
			this.patches = patches.Select((Patch x) => new PatchSortingWrapper(x)).ToList();
			this.debug = debug;
			foreach (PatchSortingWrapper node in this.patches)
			{
				node.AddBeforeDependency(this.patches.Where((PatchSortingWrapper x) => node.innerPatch.before.Contains(x.innerPatch.owner)));
				node.AddAfterDependency(this.patches.Where((PatchSortingWrapper x) => node.innerPatch.after.Contains(x.innerPatch.owner)));
			}
			this.patches.Sort();
		}

		internal List<MethodInfo> Sort(MethodBase original)
		{
			return (from x in SortAsPatches(original)
				select x.GetMethod(original)).ToList();
		}

		internal Patch[] SortAsPatches(MethodBase original)
		{
			if (sortedPatchArray != null)
			{
				return sortedPatchArray;
			}
			handledPatches = new HashSet<PatchSortingWrapper>();
			waitingList = new List<PatchSortingWrapper>();
			result = new List<PatchSortingWrapper>(patches.Count);
			Queue<PatchSortingWrapper> queue = new Queue<PatchSortingWrapper>(patches);
			while (queue.Count != 0)
			{
				foreach (PatchSortingWrapper item in queue)
				{
					if (item.after.All((PatchSortingWrapper x) => handledPatches.Contains(x)))
					{
						AddNodeToResult(item);
						if (item.before.Count != 0)
						{
							ProcessWaitingList();
						}
					}
					else
					{
						waitingList.Add(item);
					}
				}
				CullDependency();
				queue = new Queue<PatchSortingWrapper>(waitingList);
				waitingList.Clear();
			}
			sortedPatchArray = result.Select((PatchSortingWrapper x) => x.innerPatch).ToArray();
			handledPatches = null;
			waitingList = null;
			patches = null;
			return sortedPatchArray;
		}

		internal bool ComparePatchLists(Patch[] patches)
		{
			if (sortedPatchArray == null)
			{
				Sort(null);
			}
			if (patches != null && sortedPatchArray.Length == patches.Length)
			{
				return sortedPatchArray.All((Patch x) => patches.Contains(x, new PatchDetailedComparer()));
			}
			return false;
		}

		private void CullDependency()
		{
			for (int i = waitingList.Count - 1; i >= 0; i--)
			{
				foreach (PatchSortingWrapper afterNode in waitingList[i].after)
				{
					if (!handledPatches.Contains(afterNode))
					{
						waitingList[i].RemoveAfterDependency(afterNode);
						Logger.Log(Logger.LogChannel.Debug, delegate
						{
							string text = afterNode.innerPatch.PatchMethod.FullDescription();
							string text2 = waitingList[i].innerPatch.PatchMethod.FullDescription();
							return "Breaking dependence between " + text + " and " + text2;
						}, debug);
						return;
					}
				}
			}
		}

		private void ProcessWaitingList()
		{
			int num = waitingList.Count;
			int num2 = 0;
			while (num2 < num)
			{
				PatchSortingWrapper patchSortingWrapper = waitingList[num2];
				if (patchSortingWrapper.after.All(handledPatches.Contains))
				{
					waitingList.Remove(patchSortingWrapper);
					AddNodeToResult(patchSortingWrapper);
					num--;
					num2 = 0;
				}
				else
				{
					num2++;
				}
			}
		}

		private void AddNodeToResult(PatchSortingWrapper node)
		{
			result.Add(node);
			handledPatches.Add(node);
		}
	}
	internal static class PatchTools
	{
		[ThreadStatic]
		private static Dictionary<object, object> objectReferences;

		internal static void RememberObject(object key, object value)
		{
			if (objectReferences == null)
			{
				objectReferences = new Dictionary<object, object>();
			}
			objectReferences[key] = value;
		}

		internal static MethodInfo GetPatchMethod(Type patchType, string attributeName)
		{
			MethodInfo methodInfo = patchType.GetMethods(AccessTools.all).FirstOrDefault((MethodInfo m) => m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == attributeName));
			if ((object)methodInfo == null)
			{
				string name = attributeName.Replace("HarmonyLib.Harmony", "");
				methodInfo = patchType.GetMethod(name, AccessTools.all);
			}
			return methodInfo;
		}

		internal static AssemblyBuilder DefineDynamicAssembly(string name)
		{
			AssemblyName assemblyName = new AssemblyName(name);
			return AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
		}

		internal static List<AttributePatch> GetPatchMethods(Type type, bool collectIncomplete = false)
		{
			return (from attributePatch in AccessTools.GetDeclaredMethods(type).SelectMany((MethodInfo m) => AttributePatch.Create(m, collectIncomplete))
				where attributePatch != null
				select attributePatch).ToList();
		}

		internal static MethodBase GetOriginalMethod(this HarmonyMethod attr)
		{
			try
			{
				MethodType? methodType = attr.methodType;
				if (methodType.HasValue)
				{
					switch (methodType.GetValueOrDefault())
					{
					case MethodType.Normal:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.DeclaredMethod(attr.GetDeclaringType(), attr.methodName, attr.argumentTypes);
					case MethodType.Getter:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.DeclaredProperty(attr.GetDeclaringType(), attr.methodName).GetGetMethod(nonPublic: true);
					case MethodType.Setter:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.DeclaredProperty(attr.GetDeclaringType(), attr.methodName).GetSetMethod(nonPublic: true);
					case MethodType.Constructor:
						return AccessTools.DeclaredConstructor(attr.GetDeclaringType(), attr.argumentTypes);
					case MethodType.StaticConstructor:
						return AccessTools.GetDeclaredConstructors(attr.GetDeclaringType()).FirstOrDefault((ConstructorInfo c) => c.IsStatic);
					case MethodType.Enumerator:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.EnumeratorMoveNext(AccessTools.DeclaredMethod(attr.GetDeclaringType(), attr.methodName, attr.argumentTypes));
					}
				}
			}
			catch (AmbiguousMatchException ex)
			{
				throw new HarmonyException("Ambiguous match for HarmonyMethod[" + attr.Description() + "]", ex.InnerException ?? ex);
			}
			return null;
		}
	}
	public enum MethodType
	{
		Normal,
		Getter,
		Setter,
		Constructor,
		StaticConstructor,
		Enumerator
	}
	public enum ArgumentType
	{
		Normal,
		Ref,
		Out,
		Pointer
	}
	public enum HarmonyPatchType
	{
		All,
		Prefix,
		Postfix,
		Transpiler,
		Finalizer,
		ReversePatch,
		ILManipulator
	}
	public enum HarmonyReversePatchType
	{
		Original,
		Snapshot
	}
	public enum MethodDispatchType
	{
		VirtualCall,
		Call
	}
	[MeansImplicitUse]
	public class HarmonyAttribute : Attribute
	{
		public HarmonyMethod info = new HarmonyMethod();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Delegate, AllowMultiple = true)]
	public class HarmonyPatch : HarmonyAttribute
	{
		public HarmonyPatch()
		{
		}

		public HarmonyPatch(Type declaringType)
		{
			info.declaringType = declaringType;
		}

		public HarmonyPatch(Type declaringType, Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
		}

		public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(string assemblyQualifiedDeclaringType, string methodName)
		{
			info.assemblyQualifiedDeclaringTypeName = assemblyQualifiedDeclaringType;
			info.methodName = methodName;
		}

		public HarmonyPatch(string assemblyQualifiedDeclaringType, string methodName, MethodType methodType, Type[] argumentTypes = null, ArgumentType[] argumentVariations = null)
		{
			info.assemblyQualifiedDeclaringTypeName = assemblyQualifiedDeclaringType;
			info.methodName = methodName;
			info.methodType = methodType;
			if (argumentTypes != null)
			{
				ParseSpecialArguments(argumentTypes, argumentVariations);
			}
		}

		public HarmonyPatch(Type declaringType, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type declaringType, string methodName, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(string methodName)
		{
			info.methodName = methodName;
		}

		public HarmonyPatch(string methodName, params Type[] argumentTypes)
		{
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(string methodName, MethodType methodType)
		{
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType)
		{
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
		{
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type[] argumentTypes)
		{
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		private void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			if (argumentVariations == null || argumentVariations.Length == 0)
			{
				info.argumentTypes = argumentTypes;
				return;
			}
			if (argumentTypes.Length < argumentVariations.Length)
			{
				throw new ArgumentException("argumentVariations contains more elements than argumentTypes", "argumentVariations");
			}
			List<Type> list = new List<Type>();
			for (int i = 0; i < argumentTypes.Length; i++)
			{
				Type type = argumentTypes[i];
				switch (argumentVariations[i])
				{
				case ArgumentType.Ref:
				case ArgumentType.Out:
					type = type.MakeByRefType();
					break;
				case ArgumentType.Pointer:
					type = type.MakePointerType();
					break;
				}
				list.Add(type);
			}
			info.argumentTypes = list.ToArray();
		}
	}
	[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = true)]
	public class HarmonyDelegate : HarmonyPatch
	{
		public HarmonyDelegate(Type declaringType)
			: base(declaringType)
		{
		}

		public HarmonyDelegate(Type declaringType, Type[] argumentTypes)
			: base(declaringType, argumentTypes)
		{
		}

		public HarmonyDelegate(Type declaringType, string methodName)
			: base(declaringType, methodName)
		{
		}

		public HarmonyDelegate(Type declaringType, string methodName, params Type[] argumentTypes)
			: base(declaringType, methodName, argumentTypes)
		{
		}

		public HarmonyDelegate(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(declaringType, methodName, argumentTypes, argumentVariations)
		{
		}

		public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType)
			: base(declaringType, MethodType.Normal)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, params Type[] argumentTypes)
			: base(declaringType, MethodType.Normal, argumentTypes)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(declaringType, MethodType.Normal, argumentTypes, argumentVariations)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type declaringType, string methodName, MethodDispatchType methodDispatchType)
			: base(declaringType, methodName, MethodType.Normal)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(string methodName)
			: base(methodName)
		{
		}

		public HarmonyDelegate(string methodName, params Type[] argumentTypes)
			: base(methodName, argumentTypes)
		{
		}

		public HarmonyDelegate(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(methodName, argumentTypes, argumentVariations)
		{
		}

		public HarmonyDelegate(string methodName, MethodDispatchType methodDispatchType)
			: base(methodName, MethodType.Normal)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(MethodDispatchType methodDispatchType)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(MethodDispatchType methodDispatchType, params Type[] argumentTypes)
			: base(MethodType.Normal, argumentTypes)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(MethodType.Normal, argumentTypes, argumentVariations)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type[] argumentTypes)
			: base(argumentTypes)
		{
		}

		public HarmonyDelegate(Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(argumentTypes, argumentVariations)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
	public class HarmonyReversePatch : HarmonyAttribute
	{
		public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
		{
			info.reversePatchType = type;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class HarmonyPatchAll : HarmonyAttribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyPriority : HarmonyAttribute
	{
		public HarmonyPriority(int priority)
		{
			info.priority = priority;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyBefore : HarmonyAttribute
	{
		public HarmonyBefore(params string[] before)
		{
			info.before = before;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyAfter : HarmonyAttribute
	{
		public HarmonyAfter(params string[] after)
		{
			info.after = after;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyDebug : HarmonyAttribute
	{
		public HarmonyDebug()
		{
			info.debug = true;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyEmitIL : HarmonyAttribute
	{
		public HarmonyEmitIL()
		{
			info.debugEmitPath = "./";
		}

		public HarmonyEmitIL(string dir)
		{
			info.debugEmitPath = dir;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyWrapSafe : HarmonyAttribute
	{
		public HarmonyWrapSafe()
		{
			info.wrapTryCatch = true;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrepare : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyCleanup : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethod : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethods : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrefix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPostfix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTranspiler : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyILManipulator : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyFinalizer : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)]
	public class HarmonyArgument : Attribute
	{
		public string OriginalName { get; private set; }

		public int Index { get; private set; }

		public string NewName { get; private set; }

		public HarmonyArgument(string originalName)
			: this(originalName, null)
		{
		}

		public HarmonyArgument(int index)
			: this(index, null)
		{
		}

		public HarmonyArgument(string originalName, string newName)
		{
			OriginalName = originalName;
			Index = -1;
			NewName = newName;
		}

		public HarmonyArgument(int index, string name)
		{
			OriginalName = null;
			Index = index;
			NewName = name;
		}
	}
	public class CodeInstruction
	{
		public OpCode opcode;

		public object operand;

		public List<Label> labels = new List<Label>();

		public List<ExceptionBlock> blocks = new List<ExceptionBlock>();

		internal CodeInstruction()
		{
		}

		public CodeInstruction(OpCode opcode, object operand = null)
		{
			this.opcode = opcode;
			this.operand = operand;
		}

		public CodeInstruction(CodeInstruction instruction)
		{
			opcode = instruction.opcode;
			operand = instruction.operand;
			labels = instruction.labels.ToList();
			blocks = instruction.blocks.ToList();
		}

		public CodeInstruction Clone()
		{
			return new CodeInstruction(this)
			{
				labels = new List<Label>(),
				blocks = new List<ExceptionBlock>()
			};
		}

		public CodeInstruction Clone(OpCode opcode)
		{
			CodeInstruction codeInstruction = Clone();
			codeInstruction.opcode = opcode;
			return codeInstruction;
		}

		public CodeInstruction Clone(object operand)
		{
			CodeInstruction codeInstruction = Clone();
			codeInstruction.operand = operand;
			return codeInstruction;
		}

		public static CodeInstruction Call(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, parameters, generics);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException($"No method found for type={type}, name={name}, parameters={parameters.Description()}, generics={generics.Description()}");
			}
			return new CodeInstruction(OpCodes.Call, methodInfo);
		}

		public static CodeInstruction Call(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
		{
			MethodInfo methodInfo = AccessTools.Method(typeColonMethodname, parameters, generics);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException("No method found for " + typeColonMethodname + ", parameters=" + parameters.Description() + ", generics=" + generics.Description());
			}
			return new CodeInstruction(OpCodes.Call, methodInfo);
		}

		public static CodeInstruction Call(Expression<Action> expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction Call<T>(Expression<Action<T>> expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction Call<T, TResult>(Expression<Func<T, TResult>> expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction Call(LambdaExpression expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction CallClosure<T>(T closure) where T : Delegate
		{
			return Transpilers.EmitDelegate(closure);
		}

		public static CodeInstruction LoadField(Type type, string name, bool useAddress = false)
		{
			FieldInfo fieldInfo = AccessTools.Field(type, name);
			if ((object)fieldInfo == null)
			{
				throw new ArgumentException($"No field found for {type} and {name}");
			}
			return new CodeInstruction((!useAddress) ? (fieldInfo.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld) : (fieldInfo.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda), fieldInfo);
		}

		public static CodeInstruction StoreField(Type type, string name)
		{
			FieldInfo fieldInfo = AccessTools.Field(type, name);
			if ((object)fieldInfo == null)
			{
				throw new ArgumentException($"No field found for {type} and {name}");
			}
			return new CodeInstruction(fieldInfo.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fieldInfo);
		}

		public override string ToString()
		{
			List<string> list = new List<string>();
			foreach (Label label in labels)
			{
				list.Add($"Label{label.GetHashCode()}");
			}
			foreach (ExceptionBlock block in blocks)
			{
				list.Add("EX_" + block.blockType.ToString().Replace("Block", ""));
			}
			string text = ((list.Count > 0) ? (" [" + string.Join(", ", list.ToArray()) + "]") : "");
			string text2 = FormatArgument(operand);
			if (text2.Length > 0)
			{
				text2 = " " + text2;
			}
			OpCode opCode = opcode;
			return opCode.ToString() + text2 + text;
		}

		internal static string FormatArgument(object argument, string extra = null)
		{
			if (argument == null)
			{
				return "NULL";
			}
			Type type = argument.GetType();
			if (argument is MethodBase member)
			{
				return member.FullDescription() + ((extra != null) ? (" " + extra) : "");
			}
			if (argument is FieldInfo fieldInfo)
			{
				return fieldInfo.FieldType.FullDescription() + " " + fieldInfo.DeclaringType.FullDescription() + "::" + fieldInfo.Name;
			}
			if ((object)type == typeof(Label))
			{
				return $"Label{((Label)argument).GetHashCode()}";
			}
			if ((object)type == typeof(Label[]))
			{
				return "Labels" + string.Join(",", ((Label[])argument).Select((Label l) => l.GetHashCode().ToString()).ToArray());
			}
			if ((object)type == typeof(LocalBuilder))
			{
				return $"{((LocalBuilder)argument).LocalIndex} ({((LocalBuilder)argument).LocalType})";
			}
			if ((object)type == typeof(string))
			{
				return argument.ToString().ToLiteral();
			}
			return argument.ToString().Trim();
		}
	}
	public enum ExceptionBlockType
	{
		BeginExceptionBlock,
		BeginCatchBlock,
		BeginExceptFilterBlock,
		BeginFaultBlock,
		BeginFinallyBlock,
		EndExceptionBlock
	}
	public class ExceptionBlock
	{
		public ExceptionBlockType blockType;

		public Type catchType;

		public ExceptionBlock(ExceptionBlockType blockType, Type catchType = null)
		{
			this.blockType = blockType;
			this.catchType = catchType ?? typeof(object);
		}
	}
	public class InvalidHarmonyPatchArgumentException : Exception
	{
		public MethodBase Original { get; }

		public MethodInfo Patch { get; }

		public override string Message => "(" + Patch.FullDescription() + "): " + base.Message;

		public InvalidHarmonyPatchArgumentException(string message, MethodBase original, MethodInfo patch)
			: base(message)
		{
			Original = original;
			Patch = patch;
		}
	}
	public class MemberNotFoundException : Exception
	{
		public MemberNotFoundException(string message)
			: base(message)
		{
		}
	}
	public class Harmony : IDisposable
	{
		[Obsolete("Use HarmonyFileLog.Enabled instead")]
		public static bool DEBUG;

		public string Id { get; }

		static Harmony()
		{
			StackTraceFixes.Install();
		}

		public Harmony(string id)
		{
			if (string.IsNullOrEmpty(id))
			{
				throw new ArgumentException("id cannot be null or empty");
			}
			try
			{
				string environmentVariable = Environment.GetEnvironmentVariable("HARMONY_DEBUG");
				if (environmentVariable != null && environmentVariable.Length > 0)
				{
					environmentVariable = environmentVariable.Trim();
					DEBUG = environmentVariable == "1" || bool.Parse(environmentVariable);
				}
			}
			catch
			{
			}
			if (DEBUG)
			{
				HarmonyFileLog.Enabled = true;
			}
			MethodBase callingMethod = (Logger.IsEnabledFor(Logger.LogChannel.Info) ? AccessTools.GetOutsideCaller() : null);
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
				StringBuilder stringBuilder = new StringBuilder();
				Assembly assembly = typeof(Harmony).Assembly;
				Version version = assembly.GetName().Version;
				string text = assembly.Location;
				string text2 = Environment.Version.ToString();
				string text3 = Environment.OSVersion.Platform.ToString();
				if (string.IsNullOrEmpty(text))
				{
					text = new Uri(assembly.CodeBase).LocalPath;
				}
				int size = IntPtr.Size;
				Platform current = PlatformHelper.Current;
				stringBuilder.AppendLine($"### Harmony id={id}, version={version}, location={text}, env/clr={text2}, platform={text3}, ptrsize:runtime/env={size}/{current}");
				if ((object)callingMethod?.DeclaringType != null)
				{
					Assembly assembly2 = callingMethod.DeclaringType.Assembly;
					text = assembly2.Location;
					if (string.IsNullOrEmpty(text))
					{
						text = new Uri(assembly2.CodeBase).LocalPath;
					}
					stringBuilder.AppendLine("### Started from " + callingMethod.FullDescription() + ", location " + text);
					stringBuilder.Append($"### At {DateTime.Now:yyyy-MM-dd hh.mm.ss}");
				}
				return stringBuilder.ToString();
			});
			Id = id;
		}

		public void PatchAll()
		{
			Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly;
			PatchAll(assembly);
		}

		public PatchProcessor CreateProcessor(MethodBase original)
		{
			return new PatchProcessor(this, original);
		}

		public PatchClassProcessor CreateClassProcessor(Type type)
		{
			return new PatchClassProcessor(this, type);
		}

		public PatchClassProcessor CreateClassProcessor(Type type, bool allowUnannotatedType)
		{
			return new PatchClassProcessor(this, type, allowUnannotatedType);
		}

		public ReversePatcher CreateReversePatcher(MethodBase original, HarmonyMethod standin)
		{
			return new ReversePatcher(this, original, standin);
		}

		public void PatchAll(Assembly assembly)
		{
			AccessTools.GetTypesFromAssembly(assembly).Do(delegate(Type type)
			{
				CreateClassProcessor(type).Patch();
			});
		}

		public void PatchAll(Type type)
		{
			CreateClassProcessor(type, allowUnannotatedType: true).Patch();
		}

		public MethodInfo Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null, HarmonyMethod ilmanipulator = null)
		{
			PatchProcessor patchProcessor = CreateProcessor(original);
			patchProcessor.AddPrefix(prefix);
			patchProcessor.AddPostfix(postfix);
			patchProcessor.AddTranspiler(transpiler);
			patchProcessor.AddFinalizer(finalizer);
			patchProcessor.AddILManipulator(ilmanipulator);
			return patchProcessor.Patch();
		}

		[Obsolete("Use newer Patch() instead", true)]
		public MethodInfo Patch(MethodBase original, HarmonyMethod prefix, HarmonyMethod postfix, HarmonyMethod transpiler, HarmonyMethod finalizer)
		{
			return Patch(original, prefix, postfix, transpiler, finalizer, null);
		}

		public static MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler = null, MethodInfo ilmanipulator = null)
		{
			return PatchFunctions.ReversePatch(standin, original, transpiler, ilmanipulator);
		}

		[Obsolete("Use newer ReversePatch() instead", true)]
		public static MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler)
		{
			return PatchFunctions.ReversePatch(standin, original, transpiler, null);
		}

		public static void UnpatchID(string harmonyID)
		{
			if (string.IsNullOrEmpty(harmonyID))
			{
				throw new ArgumentNullException("harmonyID", "UnpatchID was called with a null or empty harmonyID.");
			}
			PatchFunctions.UnpatchConditional((Patch patchInfo) => patchInfo.owner == harmonyID);
		}

		void IDisposable.Dispose()
		{
			UnpatchSelf();
		}

		public void UnpatchSelf()
		{
			UnpatchID(Id);
		}

		public static void UnpatchAll()
		{
			Logger.Log(Logger.LogChannel.Warn, () => "UnpatchAll has been called - This will remove ALL HARMONY PATCHES.");
			PatchFunctions.UnpatchConditional((Patch _) => true);
		}

		[Obsolete("Use UnpatchSelf() to unpatch the current instance. The functionality to unpatch either other ids or EVERYTHING has been moved the static methods UnpatchID() and UnpatchAll() respectively", true)]
		public void UnpatchAll(string harmonyID = null)
		{
			if (harmonyID == null)
			{
				if (HarmonyGlobalSettings.DisallowLegacyGlobalUnpatchAll)
				{
					Logger.Log(Logger.LogChannel.Warn, () => "Legacy UnpatchAll has been called AND DisallowLegacyGlobalUnpatchAll=true. Skipping execution of UnpatchAll");
				}
				else
				{
					UnpatchAll();
				}
			}
			else if (harmonyID.Length == 0)
			{
				Logger.Log(Logger.LogChannel.Warn, () => "Legacy UnpatchAll was called with harmonyID=\"\" which is an invalid id. Skipping execution of UnpatchAll");
			}
			else
			{
				UnpatchID(harmonyID);
			}
		}

		public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null)
		{
			CreateProcessor(original).Unpatch(type, harmonyID);
		}

		public void Unpatch(MethodBase original, MethodInfo patch)
		{
			CreateProcessor(original).Unpatch(patch);
		}

		public static bool HasAnyPatches(string harmonyID)
		{
			return (from original in GetAllPatchedMethods()
				select GetPatchInfo(original)).Any((Patches info) => info.Owners.Contains(harmonyID));
		}

		public static Patches GetPatchInfo(MethodBase method)
		{
			return PatchProcessor.GetPatchInfo(method);
		}

		public IEnumerable<MethodBase> GetPatchedMethods()
		{
			return from original in GetAllPatchedMethods()
				where GetPatchInfo(original).Owners.Contains(Id)
				select original;
		}

		public static IEnumerable<MethodBase> GetAllPatchedMethods()
		{
			return PatchProcessor.GetAllPatchedMethods();
		}

		public static MethodBase GetOriginalMethod(MethodInfo replacement)
		{
			if ((object)replacement == null)
			{
				throw new ArgumentNullException("replacement");
			}
			return PatchManager.GetOriginal(replacement);
		}

		public static MethodBase GetMethodFromStackframe(StackFrame frame)
		{
			if (frame == null)
			{
				throw new ArgumentNullException("frame");
			}
			return PatchManager.FindReplacement(frame) ?? frame.GetMethod();
		}

		public static Dictionary<string, Version> VersionInfo(out Version currentVersion)
		{
			return PatchProcessor.VersionInfo(out currentVersion);
		}

		public static Harmony CreateAndPatchAll(Type type, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(type);
			return harmony;
		}

		public static Harmony CreateAndPatchAll(Assembly assembly, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(assembly);
			return harmony;
		}
	}
	[Serializable]
	public class HarmonyException : Exception
	{
		private Dictionary<int, CodeInstruction> instructions;

		private int errorOffset;

		internal HarmonyException()
		{
		}

		internal HarmonyException(string message)
			: base(message)
		{
		}

		internal HarmonyException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected HarmonyException(SerializationInfo serializationInfo, StreamingContext streamingContext)
		{
			throw new NotImplementedException();
		}

		internal HarmonyException(Exception innerException, Dictionary<int, CodeInstruction> instructions, int errorOffset)
			: base("IL Compile Error", innerException)
		{
			this.instructions = instructions;
			this.errorOffset = errorOffset;
		}

		internal static Exception Create(Exception ex, MethodBody body)
		{
			Match match = Regex.Match(ex.Message.TrimEnd(new char[0]), "Reason: Invalid IL code in.+: IL_(\\d{4}): (.+)$");
			if (!match.Success)
			{
				return new HarmonyException("IL Compile Error (unknown location)", ex);
			}
			Dictionary<int, CodeInstruction> dictionary = ILManipulator.GetInstructions(body) ?? new Dictionary<int, CodeInstruction>();
			int num = int.Parse(match.Groups[1].Value, NumberStyles.HexNumber);
			Regex.Replace(match.Groups[2].Value, " {2,}", " ");
			if (ex is HarmonyException ex2)
			{
				if (dictionary.Count != 0)
				{
					ex2.instructions = dictionary;
					ex2.errorOffset = num;
				}
				return ex2;
			}
			return new HarmonyException(ex, dictionary, num);
		}

		public List<KeyValuePair<int, CodeInstruction>> GetInstructionsWithOffsets()
		{
			return instructions.OrderBy((KeyValuePair<int, CodeInstruction> ins) => ins.Key).ToList();
		}

		public List<CodeInstruction> GetInstructions()
		{
			return (from ins in instructions
				orderby ins.Key
				select ins.Value).ToList();
		}

		public int GetErrorOffset()
		{
			return errorOffset;
		}

		public int GetErrorIndex()
		{
			if (instructions.TryGetValue(errorOffset, out var value))
			{
				return GetInstructions().IndexOf(value);
			}
			return -1;
		}
	}
	public static class HarmonyGlobalSettings
	{
		public static bool DisallowLegacyGlobalUnpatchAll { get; set; }
	}
	public class HarmonyMethod
	{
		public MethodInfo method;

		public Type declaringType;

		public string methodName;

		public MethodType? methodType;

		public Type[] argumentTypes;

		public int priority = -1;

		public string[] before;

		public string[] after;

		public HarmonyReversePatchType? reversePatchType;

		public bool? debug;

		public string debugEmitPath;

		public bool nonVirtualDelegate;

		public bool? wrapTryCatch;

		internal string assemblyQualifiedDeclaringTypeName;

		public HarmonyMethod()
		{
		}

		private void ImportMethod(MethodInfo theMethod)
		{
			method = theMethod;
			if ((object)method != null)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(method);
				if (fromMethod != null)
				{
					Merge(fromMethod).CopyTo(this);
				}
			}
		}

		public HarmonyMethod(MethodInfo method)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			ImportMethod(method);
		}

		public HarmonyMethod(MethodInfo method, int priority = -1, string[] before = null, string[] after = null, bool? debug = null)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			ImportMethod(method);
			this.priority = priority;
			this.before = before;
			this.after = after;
			this.debug = debug;
		}

		public HarmonyMethod(Type methodType, string methodName, Type[] argumentTypes = null)
		{
			MethodInfo methodInfo = AccessTools.Method(methodType, methodName, argumentTypes);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException($"Cannot not find method for type {methodType} and name {methodName} and parameters {argumentTypes?.Description()}");
			}
			ImportMethod(methodInfo);
		}

		public static List<string> HarmonyFields()
		{
			return (from s in AccessTools.GetFieldNames(typeof(HarmonyMethod))
				where s != "method"
				select s).ToList();
		}

		public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
		{
			return Merge((IEnumerable<HarmonyMethod>)attributes);
		}

		internal static HarmonyMethod Merge(IEnumerable<HarmonyMethod> attributes)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			if (attributes == null)
			{
				return harmonyMethod;
			}
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			attributes.Do(delegate(HarmonyMethod attribute)
			{
				Traverse trv = Traverse.Create(attribute);
				HarmonyFields().ForEach(delegate(string f)
				{
					object value = trv.Field(f).GetValue();
					if (value != null && (f != "priority" || (int)value != -1))
					{
						HarmonyMethodExtensions.SetValue(resultTrv, f, value);
					}
				});
			});
			return harmonyMethod;
		}

		public override string ToString()
		{
			string result = "";
			Traverse trv = Traverse.Create(this);
			HarmonyFields().ForEach(delegate(string f)
			{
				if (result.Length > 0)
				{
					result += ", ";
				}
				result += $"{f}={trv.Field(f).GetValue()}";
			});
			return "HarmonyMethod[" + result + "]";
		}

		internal string Description()
		{
			string text = (((object)declaringType != null) ? declaringType.FullName : ((assemblyQualifiedDeclaringTypeName != null) ? assemblyQualifiedDeclaringTypeName : "undefined"));
			string text2 = methodName ?? "undefined";
			string text3 = (methodType.HasValue ? methodType.Value.ToString() : "undefined");
			string text4 = ((argumentTypes != null) ? argumentTypes.Description() : "undefined");
			return "(class=" + text + ", methodname=" + text2 + ", type=" + text3 + ", args=" + text4 + ")";
		}

		internal Type GetDeclaringType()
		{
			if ((object)declaringType == null && assemblyQualifiedDeclaringTypeName != null)
			{
				declaringType = Type.GetType(assemblyQualifiedDeclaringTypeName, throwOnError: true);
			}
			return declaringType;
		}

		internal Type[] GetArgumentList()
		{
			return argumentTypes ?? EmptyType.NoArgs;
		}
	}
	internal static class EmptyType
	{
		internal static readonly Type[] NoArgs = new Type[0];
	}
	public static class HarmonyMethodExtensions
	{
		internal static void SetValue(Traverse trv, string name, object val)
		{
			if (val != null)
			{
				Traverse traverse = trv.Field(name);
				if (name == "methodType" || name == "reversePatchType")
				{
					val = Enum.ToObject(Nullable.GetUnderlyingType(traverse.GetValueType()), (int)val);
				}
				traverse.SetValue(val);
			}
		}

		public static void CopyTo(this HarmonyMethod from, HarmonyMethod to)
		{
			if (to == null)
			{
				return;
			}
			Traverse fromTrv = Traverse.Create(from);
			Traverse toTrv = Traverse.Create(to);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = fromTrv.Field(f).GetValue();
				if (value != null)
				{
					SetValue(toTrv, f, value);
				}
			});
		}

		public static HarmonyMethod Clone(this HarmonyMethod original)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			original.CopyTo(harmonyMethod);
			return harmonyMethod;
		}

		public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail)
		{
			if (detail == null)
			{
				return master;
			}
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			Traverse masterTrv = Traverse.Create(master);
			Traverse detailTrv = Traverse.Create(detail);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = masterTrv.Field(f).GetValue();
				object value2 = detailTrv.Field(f).GetValue();
				if (f != "priority" || (int)value2 != -1)
				{
					SetValue(resultTrv, f, value2 ?? value);
				}
			});
			return harmonyMethod;
		}

		private static HarmonyMethod GetHarmonyMethodInfo(object attribute)
		{
			FieldInfo field = attribute.GetType().GetField("info", AccessTools.all);
			if ((object)field == null)
			{
				return null;
			}
			if (field.FieldType.FullName != typeof(HarmonyMethod).FullName)
			{
				return null;
			}
			return AccessTools.MakeDeepCopy<HarmonyMethod>(field.GetValue(attribute));
		}

		public static List<HarmonyMethod> GetFromType(Type type)
		{
			return (from attr in type.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}

		public static HarmonyMethod GetMergedFromType(Type type)
		{
			return HarmonyMethod.Merge(GetFromType(type));
		}

		public static List<HarmonyMethod> GetFromMethod(MethodBase method)
		{
			return (from attr in method.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}

		public static HarmonyMethod GetMergedFromMethod(MethodBase method)
		{
			return HarmonyMethod.Merge(GetFromMethod(method));
		}
	}
	public class InlineSignature : ICallSiteGenerator
	{
		public class ModifierType
		{
			public bool IsOptional;

			public Type Modifier;

			public object Type;

			public override string ToString()
			{
				return ((Type is Type type) ? type.FullDescription() : Type?.ToString()) + " mod" + (IsOptional ? "opt" : "req") + "(" + Modifier?.FullDescription() + ")";
			}

			internal TypeReference ToTypeReference(ModuleDefinition module)
			{
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Expected O, but got Unknown
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Expected O, but got Unknown
				if (!IsOptional)
				{
					return (TypeReference)new RequiredModifierType(module.ImportReference(Modifier), GetTypeReference(module, Type));
				}
				return (TypeReference)new OptionalModifierType(module.ImportReference(Modifier), GetTypeReference(module, Type));
			}
		}

		public bool HasThis { get; set; }

		public bool ExplicitThis { get; set; }

		public CallingConvention CallingConvention { get; set; } = CallingConvention.Winapi;


		public List<object> Parameters { get; set; } = new List<object>();


		public object ReturnType { get; set; } = typeof(void);


		public override string ToString()
		{
			return ((ReturnType is Type type) ? type.FullDescription() : ReturnType?.ToString()) + " (" + Parameters.Join((object p) => (!(p is Type type2)) ? p?.ToString() : type2.FullDescription()) + ")";
		}

		internal static TypeReference GetTypeReference(ModuleDefinition module, object param)
		{
			if (!(param is Type type))
			{
				if (!(param is InlineSignature inlineSignature))
				{
					if (param is ModifierType modifierType)
					{
						return modifierType.ToTypeReference(module);
					}
					throw new NotSupportedException($"Unsupported inline signature parameter type: {param} ({param?.GetType().FullDescription()})");
				}
				return (TypeReference)(object)inlineSignature.ToFunctionPointer(module);
			}
			return module.ImportReference(type);
		}

		CallSite ICallSiteGenerator.ToCallSite(ModuleDefinition module)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_003a: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			CallSite val = new CallSite(GetTypeReference(module, ReturnType))
			{
				HasThis = HasThis,
				ExplicitThis = ExplicitThis,
				CallingConvention = (MethodCallingConvention)(byte)((byte)CallingConvention - 1)
			};
			foreach (object parameter in Parameters)
			{
				val.Parameters.Add(new ParameterDefinition(GetTypeReference(module, parameter)));
			}
			return val;
		}

		private FunctionPointerType ToFunctionPointer(ModuleDefinition module)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			FunctionPointerType val = new FunctionPointerType
			{
				ReturnType = GetTypeReference(module, ReturnType),
				HasThis = HasThis,
				ExplicitThis = ExplicitThis,
				CallingConvention = (MethodCallingConvention)(byte)((byte)CallingConvention - 1)
			};
			foreach (object parameter in Parameters)
			{
				val.Parameters.Add(new ParameterDefinition(GetTypeReference(module, parameter)));
			}
			return val;
		}
	}
	internal static class PatchInfoSerialization
	{
		private class Binder : SerializationBinder
		{
			public override Type BindToType(string assemblyName, string typeName)
			{
				Type[] array = new Type[3]
				{
					typeof(PatchInfo),
					typeof(Patch[]),
					typeof(Patch)
				};
				foreach (Type type in array)
				{
					if (typeName == type.FullName)
					{
						return type;
					}
				}
				return Type.GetType($"{typeName}, {assemblyName}");
			}
		}

		internal static byte[] Serialize(this PatchInfo patchInfo)
		{
			using MemoryStream memoryStream = new MemoryStream();
			new BinaryFormatter().Serialize(memoryStream, patchInfo);
			return memoryStream.GetBuffer();
		}

		internal static PatchInfo Deserialize(byte[] bytes)
		{
			BinaryFormatter obj = new BinaryFormatter
			{
				Binder = new Binder()
			};
			MemoryStream serializationStream = new MemoryStream(bytes);
			return (PatchInfo)obj.Deserialize(serializationStream);
		}

		internal static int PriorityComparer(object obj, int index, int priority)
		{
			Traverse traverse = Traverse.Create(obj);
			int value = traverse.Field("priority").GetValue<int>();
			int value2 = traverse.Field("index").GetValue<int>();
			if (priority != value)
			{
				return -priority.CompareTo(value);
			}
			return index.CompareTo(value2);
		}
	}
	[Serializable]
	public class PatchInfo
	{
		public Patch[] prefixes = new Patch[0];

		public Patch[] postfixes = new Patch[0];

		public Patch[] transpilers = new Patch[0];

		public Patch[] finalizers = new Patch[0];

		public Patch[] ilmanipulators = new Patch[0];

		public bool Debugging
		{
			get
			{
				if (!prefixes.Any((Patch p) => p.debug) && !postfixes.Any((Patch p) => p.debug) && !transpilers.Any((Patch p) => p.debug) && !finalizers.Any((Patch p) => p.debug))
				{
					return ilmanipulators.Any((Patch p) => p.debug);
				}
				return true;
			}
		}

		public string[] DebugEmitPaths => (from p in prefixes.Concat(postfixes).Concat(transpilers).Concat(finalizers)
				.Concat(ilmanipulators)
			select p.debugEmitPath into p
			where p != null
			select p).ToArray();

		internal void AddPrefixes(string owner, params HarmonyMethod[] methods)
		{
			prefixes = Add(owner, methods, prefixes);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddPrefix(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddPrefixes(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemovePrefix(string owner)
		{
			prefixes = Remove(owner, prefixes);
		}

		internal void AddPostfixes(string owner, params HarmonyMethod[] methods)
		{
			postfixes = Add(owner, methods, postfixes);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddPostfix(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddPostfixes(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemovePostfix(string owner)
		{
			postfixes = Remove(owner, postfixes);
		}

		internal void AddTranspilers(string owner, params HarmonyMethod[] methods)
		{
			transpilers = Add(owner, methods, transpilers);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddTranspiler(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddTranspilers(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemoveTranspiler(string owner)
		{
			transpilers = Remove(owner, transpilers);
		}

		internal void AddFinalizers(string owner, params HarmonyMethod[] methods)
		{
			finalizers = Add(owner, methods, finalizers);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddFinalizer(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddFinalizers(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemoveFinalizer(string owner)
		{
			finalizers = Remove(owner, finalizers);
		}

		internal void AddILManipulators(string owner, params HarmonyMethod[] methods)
		{
			ilmanipulators = Add(owner, methods, ilmanipulators);
		}

		public void RemoveILManipulator(string owner)
		{
			ilmanipulators = Remove(owner, ilmanipulators);
		}

		public void RemovePatch(MethodInfo patch)
		{
			prefixes = prefixes.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			postfixes = postfixes.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			transpilers = transpilers.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			finalizers = finalizers.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			ilmanipulators = ilmanipulators.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
		}

		private static Patch[] Add(string owner, HarmonyMethod[] add, Patch[] current)
		{
			if (add.Length == 0)
			{
				return current;
			}
			int initialIndex = current.Length;
			return current.Concat(add.Where((HarmonyMethod method) => method != null).Select((HarmonyMethod method, int i) => new Patch(method, i + initialIndex, owner))).ToArray();
		}

		private static Patch[] Remove(string owner, Patch[] current)
		{
			if (!(owner == "*"))
			{
				return current.Where((Patch patch) => patch.owner != owner).ToArray();
			}
			return new Patch[0];
		}
	}
	[Serializable]
	public class Patch : IComparable
	{
		public readonly int index;

		public readonly string owner;

		public readonly int priority;

		public readonly string[] before;

		public readonly string[] after;

		public readonly bool debug;

		public readonly string debugEmitPath;

		public readonly bool wrapTryCatch;

		[NonSerialized]
		private MethodInfo patchMethod;

		private int methodToken;

		private string moduleGUID;

		public MethodInfo PatchMethod
		{
			get
			{
				if ((object)patchMethod == null)
				{
					Module module = (from a in AppDomain.CurrentDomain.GetAssemblies()
						where !a.FullName.StartsWith("Microsoft.VisualStudio")
						select a).SelectMany((Assembly a) => a.GetLoadedModules()).First((Module m) => m.ModuleVersionId.ToString() == moduleGUID);
					patchMethod = (MethodInfo)module.ResolveMethod(methodToken);
				}
				return patchMethod;
			}
			set
			{
				patchMethod = value;
				methodToken = patchMethod.MetadataToken;
				moduleGUID = patchMethod.Module.ModuleVersionId.ToString();
			}
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug)
		{
			if (patch is DynamicMethod)
			{
				throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method.");
			}
			this.index = index;
			this.owner = owner;
			this.priority = ((priority == -1) ? 400 : priority);
			this.before = before ?? new string[0];
			this.after = after ?? new string[0];
			this.debug = debug;
			PatchMethod = patch;
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug, bool wrapTryCatch)
		{
			if (patch is DynamicMethod)
			{
				throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method.");
			}
			this.index = index;
			this.owner = owner;
			this.priority = ((priority == -1) ? 400 : priority);
			this.before = before ?? new string[0];
			this.after = after ?? new string[0];
			this.debug = debug;
			this.wrapTryCatch = wrapTryCatch;
			PatchMethod = patch;
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug, bool wrapTryCatch, string debugEmitPath)
		{
			if (patch is DynamicMethod)
			{
				throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method.");
			}
			this.index = index;
			this.owner = owner;
			this.priority = ((priority == -1) ? 400 : priority);
			this.before = before ?? new string[0];
			this.after = after ?? new string[0];
			this.debug = debug;
			this.debugEmitPath = debugEmitPath;
			this.wrapTryCatch = wrapTryCatch;
			PatchMethod = patch;
		}

		public Patch(HarmonyMethod method, int index, string owner)
			: this(method.method, index, owner, method.priority, method.before, method.after, method.debug.GetValueOrDefault(), method.wrapTryCatch.GetValueOrDefault(), method.debugEmitPath)
		{
		}

		public MethodInfo GetMethod(MethodBase original)
		{
			MethodInfo methodInfo = PatchMethod;
			if ((object)methodInfo.ReturnType != typeof(DynamicMethod) && (object)methodInfo.ReturnType != typeof(MethodInfo))
			{
				return methodInfo;
			}
			if (!methodInfo.IsStatic)
			{
				return methodInfo;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length != 1)
			{
				return methodInfo;
			}
			if ((object)parameters[0].ParameterType != typeof(MethodBase))
			{
				return methodInfo;
			}
			return methodInfo.Invoke(null, new object[1] { original }) as MethodInfo;
		}

		public override bool Equals(object obj)
		{
			if (obj != null && obj is Patch)
			{
				return (object)PatchMethod == ((Patch)obj).PatchMethod;
			}
			return false;
		}

		public int CompareTo(object obj)
		{
			return PatchInfoSerialization.PriorityComparer(obj, index, priority);
		}

		public override int GetHashCode()
		{
			return PatchMethod.GetHashCode();
		}
	}
	public class PatchClassProcessor
	{
		private readonly Harmony instance;

		private readonly Type containerType;

		private readonly HarmonyMethod containerAttributes;

		private readonly Dictionary<Type, MethodInfo> auxilaryMethods;

		private readonly List<AttributePatch> patchMethods;

		private static readonly List<Type> auxilaryTypes = new List<Type>
		{
			typeof(HarmonyPrepare),
			typeof(HarmonyCleanup),
			typeof(HarmonyTargetMethod),
			typeof(HarmonyTargetMethods)
		};

		public PatchClassProcessor(Harmony instance, Type type)
			: this(instance, type, allowUnannotatedType: false)
		{
		}

		public PatchClassProcessor(Harmony instance, Type type, bool allowUnannotatedType)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			this.instance = instance;
			containerType = type;
			List<HarmonyMethod> fromType = HarmonyMethodExtensions.GetFromType(type);
			if (!allowUnannotatedType && (fromType == null || fromType.Count == 0))
			{
				return;
			}
			containerAttributes = HarmonyMethod.Merge(fromType);
			MethodType? methodType = containerAttributes.methodType;
			if (!methodType.HasValue)
			{
				containerAttributes.methodType = MethodType.Normal;
			}
			auxilaryMethods = new Dictionary<Type, MethodInfo>();
			foreach (Type auxilaryType in auxilaryTypes)
			{
				MethodInfo patchMethod = PatchTools.GetPatchMethod(containerType, auxilaryType.FullName);
				if ((object)patchMethod != null)
				{
					auxilaryMethods[auxilaryType] = patchMethod;
				}
			}
			patchMethods = PatchTools.GetPatchMethods(containerType, (object)containerAttributes.GetDeclaringType() != null);
			foreach (AttributePatch patchMethod2 in patchMethods)
			{
				MethodInfo method = patchMethod2.info.method;
				patchMethod2.info = containerAttributes.Merge(patchMethod2.info);
				patchMethod2.info.method = method;
			}
		}

		public List<MethodInfo> Patch()
		{
			if (containerAttributes == null)
			{
				return null;
			}
			Exception exception = null;
			if (!RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, defaultIfFailing: false, null, new object[0]))
			{
				RunMethod<HarmonyCleanup>(ref exception, new object[0]);
				ReportException(exception, null);
				return new List<MethodInfo>();
			}
			List<MethodInfo> result = new List<MethodInfo>();
			MethodBase lastOriginal = null;
			try
			{
				List<MethodBase> bulkMethods = GetBulkMethods();
				if (bulkMethods.Count == 1)
				{
					lastOriginal = bulkMethods[0];
				}
				ReversePatch(ref lastOriginal);
				result = ((bulkMethods.Count > 0) ? BulkPatch(bulkMethods, ref lastOriginal) : PatchWithAttributes(ref lastOriginal));
			}
			catch (Exception ex)
			{
				exception = ex;
			}
			RunMethod<HarmonyCleanup>(ref exception, new object[1] { exception });
			ReportException(exception, lastOriginal);
			return result;
		}

		private void ReversePatch(ref MethodBase lastOriginal)
		{
			for (int i = 0; i < patchMethods.Count; i++)
			{
				AttributePatch attributePatch = patchMethods[i];
				if (attributePatch.type == HarmonyPatchType.ReversePatch)
				{
					MethodBase originalMethod = attributePatch.info.GetOriginalMethod();
					if ((object)originalMethod != null)
					{
						lastOriginal = originalMethod;
					}
					ReversePatcher reversePatcher = instance.CreateReversePatcher(lastOriginal, attributePatch.info);
					lock (PatchProcessor.locker)
					{
						reversePatcher.Patch();
					}
				}
			}
		}

		private List<MethodInfo> BulkPatch(List<MethodBase> originals, ref MethodBase lastOriginal)
		{
			PatchJobs<MethodInfo> patchJobs = new PatchJobs<MethodInfo>();
			for (int i = 0; i < originals.Count; i++)
			{
				lastOriginal = originals[i];
				PatchJobs<MethodInfo>.Job job = patchJobs.GetJob(lastOriginal);
				foreach (AttributePatch patchMethod in patchMethods)
				{
					string text = "You cannot combine TargetMethod, TargetMethods or [HarmonyPatchAll] with individual annotations";
					HarmonyMethod info = patchMethod.info;
					if (info.methodName != null)
					{
						throw new ArgumentException(text + " [" + info.methodName + "]");
					}
					if (info.methodType.HasValue && info.methodType.Value != 0)
					{
						throw new ArgumentException($"{text} [{info.methodType}]");
					}
					if (info.argumentTypes != null)
					{
						throw new ArgumentException(text + " [" + info.argumentTypes.Description() + "]");
					}
					job.AddPatch(patchMethod);
				}
			}
			foreach (PatchJobs<MethodInfo>.Job job2 in patchJobs.GetJobs())
			{
				lastOriginal = job2.original;
				ProcessPatchJob(job2);
			}
			return patchJobs.GetReplacements();
		}

		private List<MethodInfo> PatchWithAttributes(ref MethodBase lastOriginal)
		{
			PatchJobs<MethodInfo> patchJobs = new PatchJobs<MethodInfo>();
			foreach (AttributePatch patchMethod in patchMethods)
			{
				lastOriginal = patchMethod.info.GetOriginalMethod();
				if ((object)lastOriginal == null)
				{
					throw new ArgumentException("Undefined target method for patch method " + patchMethod.info.method.FullDescription());
				}
				patchJobs.GetJob(lastOriginal).AddPatch(patchMethod);
			}
			foreach (PatchJob

BepInEx/core/0Harmony20.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using HarmonyLib.Internal;
using HarmonyLib.Internal.Patching;
using HarmonyLib.Internal.Util;
using HarmonyLib.Tools;
using HarmonyXInterop;
using JetBrains.Annotations;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.Utils;
using MonoMod.Utils.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("HarmonyX2Interop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HarmonyX2Interop")]
[assembly: AssemblyCopyright("Copyright ©  2020")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("69F6541D-A0F5-419D-B0EE-F5017F1D34F3")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.0.0")]
[module: UnverifiableCode]
namespace JetBrains.Annotations
{
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class UsedImplicitlyAttribute : Attribute
	{
		public ImplicitUseKindFlags UseKindFlags { get; }

		public ImplicitUseTargetFlags TargetFlags { get; }

		public UsedImplicitlyAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)]
	internal sealed class MeansImplicitUseAttribute : Attribute
	{
		[UsedImplicitly]
		public ImplicitUseKindFlags UseKindFlags { get; }

		[UsedImplicitly]
		public ImplicitUseTargetFlags TargetFlags { get; }

		public MeansImplicitUseAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[Flags]
	internal enum ImplicitUseKindFlags
	{
		Default = 7,
		Access = 1,
		Assign = 2,
		InstantiatedWithFixedConstructorSignature = 4,
		InstantiatedNoFixedConstructorSignature = 8
	}
	[Flags]
	internal enum ImplicitUseTargetFlags
	{
		Default = 1,
		Itself = 1,
		Members = 2,
		WithInheritors = 4,
		WithMembers = 3
	}
}
namespace HarmonyLib
{
	public static class Priority
	{
		public const int Last = 0;

		public const int VeryLow = 100;

		public const int Low = 200;

		public const int LowerThanNormal = 300;

		public const int Normal = 400;

		public const int HigherThanNormal = 500;

		public const int High = 600;

		public const int VeryHigh = 700;

		public const int First = 800;
	}
	public enum MethodType
	{
		Normal,
		Getter,
		Setter,
		Constructor,
		StaticConstructor
	}
	public enum ArgumentType
	{
		Normal,
		Ref,
		Out,
		Pointer
	}
	public enum HarmonyPatchType
	{
		All,
		Prefix,
		Postfix,
		Transpiler,
		Finalizer,
		ReversePatch
	}
	public enum HarmonyReversePatchType
	{
		Original,
		Snapshot
	}
	[MeansImplicitUse]
	public class HarmonyAttribute : Attribute
	{
		public HarmonyMethod info = new HarmonyMethod();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
	public class HarmonyPatch : HarmonyAttribute
	{
		public HarmonyPatch()
		{
		}

		public HarmonyPatch(Type declaringType)
		{
			info.declaringType = declaringType;
		}

		public HarmonyPatch(Type declaringType, Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
		}

		public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type declaringType, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type declaringType, string methodName, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(string methodName)
		{
			info.methodName = methodName;
		}

		public HarmonyPatch(string methodName, params Type[] argumentTypes)
		{
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(string methodName, MethodType methodType)
		{
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType)
		{
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
		{
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type[] argumentTypes)
		{
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		private void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			if (argumentVariations == null || argumentVariations.Length == 0)
			{
				info.argumentTypes = argumentTypes;
				return;
			}
			if (argumentTypes.Length < argumentVariations.Length)
			{
				throw new ArgumentException("argumentVariations contains more elements than argumentTypes", "argumentVariations");
			}
			List<Type> list = new List<Type>();
			for (int i = 0; i < argumentTypes.Length; i++)
			{
				Type type = argumentTypes[i];
				switch (argumentVariations[i])
				{
				case ArgumentType.Ref:
				case ArgumentType.Out:
					type = type.MakeByRefType();
					break;
				case ArgumentType.Pointer:
					type = type.MakePointerType();
					break;
				}
				list.Add(type);
			}
			info.argumentTypes = list.ToArray();
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
	public class HarmonyReversePatch : HarmonyAttribute
	{
		public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
		{
			info.reversePatchType = type;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class HarmonyPatchAll : HarmonyAttribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyPriority : HarmonyAttribute
	{
		public HarmonyPriority(int priority)
		{
			info.priority = priority;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyBefore : HarmonyAttribute
	{
		public HarmonyBefore(params string[] before)
		{
			info.before = before;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyAfter : HarmonyAttribute
	{
		public HarmonyAfter(params string[] after)
		{
			info.after = after;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrepare : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyCleanup : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethod : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethods : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrefix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPostfix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTranspiler : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyFinalizer : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)]
	public class HarmonyArgument : Attribute
	{
		public string OriginalName { get; private set; }

		public int Index { get; private set; }

		public string NewName { get; private set; }

		public HarmonyArgument(string originalName)
			: this(originalName, null)
		{
		}

		public HarmonyArgument(int index)
			: this(index, null)
		{
		}

		public HarmonyArgument(string originalName, string newName)
		{
			OriginalName = originalName;
			Index = -1;
			NewName = newName;
		}

		public HarmonyArgument(int index, string name)
		{
			OriginalName = null;
			Index = index;
			NewName = name;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class ParameterByRefAttribute : Attribute
	{
		public int[] ParameterIndices { get; }

		public ParameterByRefAttribute(params int[] parameterIndices)
		{
			ParameterIndices = parameterIndices;
		}
	}
	public class InvalidHarmonyPatchArgumentException : Exception
	{
		public MethodBase Original { get; }

		public MethodInfo Patch { get; }

		public override string Message => "(" + Extensions.GetID((MethodBase)Patch, (string)null, (string)null, true, false, false) + "): " + base.Message;

		public InvalidHarmonyPatchArgumentException(string message, MethodBase original, MethodInfo patch)
			: base(message)
		{
			Original = original;
			Patch = patch;
		}
	}
	public class MemberNotFoundException : Exception
	{
		public MemberNotFoundException(string message)
			: base(message)
		{
		}
	}
	public class Harmony
	{
		[Obsolete("No longer used, subscribe to Logger.LogChannel.Info")]
		public static bool DEBUG;

		[Obsolete("Not supported by HarmonyX", true)]
		public static bool SELF_PATCHING;

		public string Id { get; private set; }

		public Harmony(string id)
		{
			if (string.IsNullOrEmpty(id))
			{
				throw new ArgumentException("id cannot be null or empty");
			}
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				Assembly assembly = typeof(Harmony).Assembly;
				Version version = assembly.GetName().Version;
				string text = assembly.Location;
				if (string.IsNullOrEmpty(text))
				{
					text = new Uri(assembly.CodeBase).LocalPath;
				}
				MethodBase outsideCaller = AccessTools.GetOutsideCaller();
				Assembly assembly2 = outsideCaller.DeclaringType?.Assembly;
				string text2 = assembly2?.Location;
				if (string.IsNullOrEmpty(text2))
				{
					text2 = (((object)assembly2 != null) ? new Uri(assembly2.CodeBase).LocalPath : string.Empty);
				}
				return $"Created Harmony instance id={id}, version={version}, location={text} - Started from {Extensions.GetID(outsideCaller, (string)null, (string)null, true, false, false)} location={text2}";
			});
			Id = id;
		}

		public void PatchAll()
		{
			Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly;
			PatchAll(assembly);
		}

		public PatchProcessor ProcessorForAnnotatedClass(Type type)
		{
			List<HarmonyMethod> fromType = HarmonyMethodExtensions.GetFromType(type);
			if (fromType != null && fromType.Any())
			{
				HarmonyMethod attributes = HarmonyMethod.Merge(fromType);
				return new PatchProcessor(this, type, attributes);
			}
			return null;
		}

		public void PatchAll(Assembly assembly)
		{
			if ((object)assembly == null)
			{
				throw new ArgumentNullException("assembly");
			}
			List<PatchProcessor> list = (from x in assembly.GetTypes().Select(ProcessorForAnnotatedClass)
				where x != null
				select x).ToList();
			foreach (PatchProcessor item in list)
			{
				item.Patch();
			}
			if (list.Count == 0)
			{
				Logger.Log(Logger.LogChannel.Warn, () => "Could not find any valid Harmony patches inside of assembly " + assembly.FullName);
			}
		}

		public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null)
		{
			PatchProcessor patchProcessor = new PatchProcessor(this, original);
			patchProcessor.AddPrefix(prefix);
			patchProcessor.AddPostfix(postfix);
			patchProcessor.AddTranspiler(transpiler);
			patchProcessor.AddFinalizer(finalizer);
			return patchProcessor.Patch().FirstOrDefault();
		}

		public MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler = null)
		{
			return null;
		}

		public ReversePatcher CreateReversePatcher(MethodBase original, MethodInfo standin)
		{
			return new ReversePatcher(this, original, standin);
		}

		public void UnpatchAll(string harmonyID = null)
		{
			foreach (MethodBase item in GetAllPatchedMethods().ToList())
			{
				Patches patchInfo = GetPatchInfo(item);
				UnpatchAllId(item, patchInfo.Prefixes);
				UnpatchAllId(item, patchInfo.Postfixes);
				UnpatchAllId(item, patchInfo.Transpilers);
				UnpatchAllId(item, patchInfo.Finalizers);
			}
			void UnpatchAllId(MethodBase original, IEnumerable<Patch> patches)
			{
				foreach (Patch patch in patches)
				{
					if (harmonyID == null || patch.owner == harmonyID)
					{
						Unpatch(original, patch.patch);
					}
				}
			}
		}

		public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null)
		{
			new PatchProcessor(this, original).Unpatch(type, harmonyID);
		}

		public void Unpatch(MethodBase original, MethodInfo patch)
		{
			new PatchProcessor(this, original).Unpatch(patch);
		}

		public static bool HasAnyPatches(string harmonyID)
		{
			return GetAllPatchedMethods().Select(GetPatchInfo).Any((Patches info) => info.Owners.Contains(harmonyID));
		}

		public static Patches GetPatchInfo(MethodBase method)
		{
			return PatchProcessor.GetPatchInfo(method);
		}

		public IEnumerable<MethodBase> GetPatchedMethods()
		{
			return from original in GetAllPatchedMethods()
				where GetPatchInfo(original).Owners.Contains(Id)
				select original;
		}

		public static IEnumerable<MethodBase> GetAllPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		public static Dictionary<string, Version> VersionInfo(out Version currentVersion)
		{
			return PatchProcessor.VersionInfo(out currentVersion);
		}

		public void PatchAll(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(methodInfo);
				if (fromMethod != null && fromMethod.Any())
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(inherit: true);
					HarmonyMethod combinedInfo = HarmonyMethod.Merge(fromMethod);
					List<HarmonyMethod> list = fromMethod.Where(IsMethodComplete).ToList();
					if (fromMethod.All((HarmonyMethod x) => (object)x.declaringType != combinedInfo.declaringType && x.methodName != combinedInfo.methodName))
					{
						list.Add(combinedInfo);
					}
					List<MethodBase> list2 = new List<MethodBase>();
					foreach (HarmonyMethod item in list)
					{
						foreach (int item2 in customAttributes.OfType<ParameterByRefAttribute>().SelectMany((ParameterByRefAttribute x) => x.ParameterIndices))
						{
							if (!item.argumentTypes[item2].IsByRef)
							{
								item.argumentTypes[item2] = item.argumentTypes[item2].MakeByRefType();
							}
						}
						if (!item.methodType.HasValue)
						{
							item.methodType = MethodType.Normal;
						}
						if ((object)item.method == null)
						{
							item.method = methodInfo;
						}
						MethodBase originalMethod = PatchProcessor.GetOriginalMethod(item);
						if ((object)originalMethod != null)
						{
							list2.Add(originalMethod);
						}
					}
					PatchProcessor patchProcessor = new PatchProcessor(this);
					foreach (MethodBase item3 in list2)
					{
						patchProcessor.AddOriginal(item3);
					}
					if (customAttributes.Any((object x) => x is HarmonyPrefix))
					{
						patchProcessor.AddPrefix(new HarmonyMethod(methodInfo));
					}
					if (customAttributes.Any((object x) => x is HarmonyTranspiler))
					{
						patchProcessor.AddTranspiler(new HarmonyMethod(methodInfo));
					}
					if (customAttributes.Any((object x) => x is HarmonyPostfix))
					{
						patchProcessor.AddPostfix(new HarmonyMethod(methodInfo));
					}
					if (customAttributes.Any((object x) => x is HarmonyFinalizer))
					{
						patchProcessor.AddFinalizer(new HarmonyMethod(methodInfo));
					}
					patchProcessor.Patch();
				}
				else if ((Logger.ChannelFilter & Logger.LogChannel.Warn) != 0 && methodInfo.GetCustomAttributes(typeof(HarmonyAttribute), inherit: true).Any())
				{
					Logger.LogText(Logger.LogChannel.Warn, "Method " + methodInfo.FullDescription() + " has an invalid combination of Harmony attributes and will be ignored");
				}
			}
			static bool IsMethodComplete(HarmonyMethod m)
			{
				if ((object)m.declaringType != null)
				{
					if (m.methodName == null && m.methodType != MethodType.Constructor)
					{
						return m.methodType == MethodType.StaticConstructor;
					}
					return true;
				}
				return false;
			}
		}

		public static Harmony CreateAndPatchAll(Type type, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(type);
			return harmony;
		}

		public static Harmony CreateAndPatchAll(Assembly assembly, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(assembly);
			return harmony;
		}
	}
	public class HarmonyMethod
	{
		public MethodInfo method;

		public Type declaringType;

		public string methodName;

		public MethodType? methodType;

		public Type[] argumentTypes;

		public int priority = -1;

		public string[] before;

		public string[] after;

		public HarmonyReversePatchType? reversePatchType;

		public HarmonyMethod()
		{
		}

		private void ImportMethod(MethodInfo theMethod)
		{
			method = theMethod;
			if ((object)method != null)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(method);
				if (fromMethod != null)
				{
					Merge(fromMethod).CopyTo(this);
				}
			}
		}

		public HarmonyMethod(MethodInfo method)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			ImportMethod(method);
		}

		public HarmonyMethod(Type type, string name, Type[] parameters = null)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, parameters);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException($"Cannot not find method for type {type} and name {name} and parameters {parameters?.Description()}");
			}
			ImportMethod(methodInfo);
		}

		public static List<string> HarmonyFields()
		{
			return (from s in AccessTools.GetFieldNames(typeof(HarmonyMethod))
				where s != "method"
				select s).ToList();
		}

		public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			if (attributes == null)
			{
				return harmonyMethod;
			}
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			attributes.ForEach(delegate(HarmonyMethod attribute)
			{
				Traverse trv = Traverse.Create(attribute);
				HarmonyFields().ForEach(delegate(string f)
				{
					object value = trv.Field(f).GetValue();
					if (value != null)
					{
						HarmonyMethodExtensions.SetValue(resultTrv, f, value);
					}
				});
			});
			return harmonyMethod;
		}

		public override string ToString()
		{
			string result = "HarmonyMethod[";
			Traverse trv = Traverse.Create(this);
			HarmonyFields().ForEach(delegate(string f)
			{
				result += $"{f}{'='}{trv.Field(f).GetValue()}";
			});
			return result + "]";
		}
	}
	public static class HarmonyMethodExtensions
	{
		internal static void SetValue(Traverse trv, string name, object val)
		{
			if (val != null)
			{
				Traverse traverse = trv.Field(name);
				if (name == "methodType" || name == "reversePatchType")
				{
					val = Enum.ToObject(Nullable.GetUnderlyingType(traverse.GetValueType()), (int)val);
				}
				traverse.SetValue(val);
			}
		}

		public static void CopyTo(this HarmonyMethod from, HarmonyMethod to)
		{
			if (to == null)
			{
				return;
			}
			Traverse fromTrv = Traverse.Create(from);
			Traverse toTrv = Traverse.Create(to);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = fromTrv.Field(f).GetValue();
				if (value != null)
				{
					SetValue(toTrv, f, value);
				}
			});
		}

		public static HarmonyMethod Clone(this HarmonyMethod original)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			original.CopyTo(harmonyMethod);
			return harmonyMethod;
		}

		public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail)
		{
			if (detail == null)
			{
				return master;
			}
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			Traverse masterTrv = Traverse.Create(master);
			Traverse detailTrv = Traverse.Create(detail);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = masterTrv.Field(f).GetValue();
				object value2 = detailTrv.Field(f).GetValue();
				SetValue(resultTrv, f, value2 ?? value);
			});
			return harmonyMethod;
		}

		private static HarmonyMethod GetHarmonyMethodInfo(object attribute)
		{
			FieldInfo field = attribute.GetType().GetField("info", AccessTools.all);
			if ((object)field == null)
			{
				return null;
			}
			if (field.FieldType.Name != "HarmonyMethod")
			{
				return null;
			}
			return AccessTools.MakeDeepCopy<HarmonyMethod>(field.GetValue(attribute));
		}

		public static List<HarmonyMethod> GetFromType(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from attr in type.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}

		public static HarmonyMethod GetMergedFromType(Type type)
		{
			return HarmonyMethod.Merge(GetFromType(type));
		}

		public static HarmonyMethod GetMergedFromMethod(MethodBase method)
		{
			return HarmonyMethod.Merge(GetFromMethod(method));
		}

		public static List<HarmonyMethod> GetFromMethod(MethodBase method)
		{
			return (from attr in method.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}
	}
	[Obsolete("Exists for legacy support", true)]
	internal static class HarmonySharedState
	{
		[Obsolete("Exists for legacy support", true)]
		public static PatchInfo GetPatchInfo(MethodBase method)
		{
			return method.ToPatchInfo();
		}

		[Obsolete("Exists for legacy support", true)]
		public static IEnumerable<MethodBase> GetPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		[Obsolete("Exists for legacy support", true)]
		public static void UpdatePatchInfo(MethodBase methodBase, PatchInfo patchInfo)
		{
		}
	}
	[Obsolete("Exists for legacy support", true)]
	internal static class PatchFunctions
	{
		[Obsolete("Exists for legacy support", true)]
		public static DynamicMethod UpdateWrapper(MethodBase original, PatchInfo info, string id)
		{
			original.GetMethodPatcher().Apply();
			return null;
		}
	}
	public class PatchInfo
	{
		public Patch[] prefixes;

		public Patch[] postfixes;

		public Patch[] transpilers;

		public Patch[] finalizers;

		public PatchInfo()
		{
			prefixes = new Patch[0];
			postfixes = new Patch[0];
			transpilers = new Patch[0];
			finalizers = new Patch[0];
		}

		private void AddPatch(ref Patch[] list, string owner, HarmonyMethod info)
		{
			if ((object)info?.method != null)
			{
				int priority = ((info.priority == -1) ? 400 : info.priority);
				string[] before = info.before ?? new string[0];
				string[] after = info.after ?? new string[0];
				AddPatch(ref list, info.method, owner, priority, before, after);
			}
		}

		private void AddPatch(ref Patch[] list, MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			List<Patch> list2 = list.ToList();
			list2.Add(new Patch(patch, prefixes.Count() + 1, owner, priority, before, after));
			list = list2.ToArray();
		}

		private void RemovePatch(ref Patch[] list, string owner)
		{
			if (owner == "*")
			{
				list = new Patch[0];
				return;
			}
			list = list.Where((Patch patch) => patch.owner != owner).ToArray();
		}

		public void AddPrefix(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref prefixes, patch, owner, priority, before, after);
		}

		public void AddPrefix(string owner, HarmonyMethod info)
		{
			AddPatch(ref prefixes, owner, info);
		}

		public void RemovePrefix(string owner)
		{
			RemovePatch(ref prefixes, owner);
		}

		public void AddPostfix(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref postfixes, patch, owner, priority, before, after);
		}

		public void AddPostfix(string owner, HarmonyMethod info)
		{
			AddPatch(ref postfixes, owner, info);
		}

		public void RemovePostfix(string owner)
		{
			RemovePatch(ref postfixes, owner);
		}

		public void AddTranspiler(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref transpilers, patch, owner, priority, before, after);
		}

		public void AddTranspiler(string owner, HarmonyMethod info)
		{
			AddPatch(ref transpilers, owner, info);
		}

		public void RemoveTranspiler(string owner)
		{
			RemovePatch(ref transpilers, owner);
		}

		public void AddFinalizer(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref finalizers, patch, owner, priority, before, after);
		}

		public void AddFinalizer(string owner, HarmonyMethod info)
		{
			AddPatch(ref finalizers, owner, info);
		}

		public void RemoveFinalizer(string owner)
		{
			RemovePatch(ref finalizers, owner);
		}

		public void RemovePatch(MethodInfo patch)
		{
			lock (this)
			{
				prefixes = prefixes.Where((Patch p) => (object)p.patch != patch).ToArray();
				postfixes = postfixes.Where((Patch p) => (object)p.patch != patch).ToArray();
				transpilers = transpilers.Where((Patch p) => (object)p.patch != patch).ToArray();
				finalizers = finalizers.Where((Patch p) => (object)p.patch != patch).ToArray();
			}
		}
	}
	public class Patch : IComparable
	{
		public readonly int index;

		public readonly string owner;

		public readonly int priority;

		public readonly string[] before;

		public readonly string[] after;

		public MethodInfo patch;

		public MethodInfo PatchMethod
		{
			get
			{
				return patch;
			}
			set
			{
				patch = value;
			}
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after)
		{
			if (patch is DynamicMethod)
			{
				throw new ArgumentException("Cannot directly reference dynamic method \"" + Extensions.GetID((MethodBase)patch, (string)null, (string)null, true, false, false) + "\" in Harmony. Use a factory method instead that will return the dynamic method.", "patch");
			}
			this.index = index;
			this.owner = owner;
			this.priority = priority;
			this.before = before;
			this.after = after;
			this.patch = patch;
		}

		public MethodInfo GetMethod(MethodBase original)
		{
			if ((object)patch.ReturnType != typeof(DynamicMethod) && (object)patch.ReturnType != typeof(MethodInfo))
			{
				return patch;
			}
			if (!patch.IsStatic)
			{
				return patch;
			}
			ParameterInfo[] parameters = patch.GetParameters();
			if (parameters.Count() != 1)
			{
				return patch;
			}
			if ((object)parameters[0].ParameterType != typeof(MethodBase))
			{
				return patch;
			}
			return patch.Invoke(null, new object[1] { original }) as MethodInfo;
		}

		public override bool Equals(object obj)
		{
			if (obj is Patch patch)
			{
				return (object)this.patch == patch.patch;
			}
			return false;
		}

		public int CompareTo(object obj)
		{
			if (!(obj is Patch patch))
			{
				return 0;
			}
			int num;
			if (patch.priority != priority)
			{
				num = priority;
				return -num.CompareTo(patch.priority);
			}
			num = index;
			return num.CompareTo(patch.index);
		}

		public override int GetHashCode()
		{
			return patch.GetHashCode();
		}
	}
	public class Patches
	{
		public readonly ReadOnlyCollection<Patch> Prefixes;

		public readonly ReadOnlyCollection<Patch> Postfixes;

		public readonly ReadOnlyCollection<Patch> Transpilers;

		public readonly ReadOnlyCollection<Patch> Finalizers;

		public ReadOnlyCollection<string> Owners
		{
			get
			{
				HashSet<string> hashSet = new HashSet<string>();
				hashSet.UnionWith(Prefixes.Select((Patch p) => p.owner));
				hashSet.UnionWith(Postfixes.Select((Patch p) => p.owner));
				hashSet.UnionWith(Transpilers.Select((Patch p) => p.owner));
				hashSet.UnionWith(Finalizers.Select((Patch p) => p.owner));
				return hashSet.ToList().AsReadOnly();
			}
		}

		public Patches(Patch[] prefixes, Patch[] postfixes, Patch[] transpilers, Patch[] finalizers)
		{
			if (prefixes == null)
			{
				prefixes = new Patch[0];
			}
			if (postfixes == null)
			{
				postfixes = new Patch[0];
			}
			if (transpilers == null)
			{
				transpilers = new Patch[0];
			}
			if (finalizers == null)
			{
				finalizers = new Patch[0];
			}
			Prefixes = prefixes.ToList().AsReadOnly();
			Postfixes = postfixes.ToList().AsReadOnly();
			Transpilers = transpilers.ToList().AsReadOnly();
			Finalizers = finalizers.ToList().AsReadOnly();
		}
	}
	public class PatchProcessor
	{
		private readonly Harmony instance;

		private readonly Type container;

		private readonly HarmonyMethod containerAttributes;

		private readonly List<MethodBase> originals = new List<MethodBase>();

		private HarmonyMethod prefix;

		private HarmonyMethod postfix;

		private HarmonyMethod transpiler;

		private HarmonyMethod finalizer;

		public PatchProcessor(Harmony instance, MethodBase original = null)
		{
			this.instance = instance;
			if ((object)original != null)
			{
				originals.Add(original);
			}
		}

		public PatchProcessor(Harmony instance, Type type, HarmonyMethod attributes)
		{
			this.instance = instance;
			container = type;
			containerAttributes = attributes ?? new HarmonyMethod();
			prefix = containerAttributes.Clone();
			postfix = containerAttributes.Clone();
			transpiler = containerAttributes.Clone();
			finalizer = containerAttributes.Clone();
			PrepareType();
		}

		[Obsolete("Use other constructors and Add* methods")]
		public PatchProcessor(Harmony instance, List<MethodBase> originals, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null)
		{
			this.instance = instance;
			this.originals = originals;
			this.prefix = prefix;
			this.postfix = postfix;
			this.transpiler = transpiler;
			this.finalizer = finalizer;
		}

		public PatchProcessor AddOriginal(MethodBase original)
		{
			if (!originals.Contains(original))
			{
				originals.Add(original);
			}
			return this;
		}

		public PatchProcessor SetOriginals(List<MethodBase> originals)
		{
			this.originals.Clear();
			this.originals.AddRange(originals);
			return this;
		}

		public PatchProcessor AddPrefix(HarmonyMethod prefix)
		{
			this.prefix = prefix;
			return this;
		}

		public PatchProcessor AddPrefix(MethodInfo fixMethod)
		{
			prefix = new HarmonyMethod(fixMethod);
			return this;
		}

		public PatchProcessor AddPostfix(HarmonyMethod postfix)
		{
			this.postfix = postfix;
			return this;
		}

		public PatchProcessor AddPostfix(MethodInfo fixMethod)
		{
			postfix = new HarmonyMethod(fixMethod);
			return this;
		}

		public PatchProcessor AddTranspiler(HarmonyMethod transpiler)
		{
			this.transpiler = transpiler;
			return this;
		}

		public PatchProcessor AddTranspiler(MethodInfo fixMethod)
		{
			transpiler = new HarmonyMethod(fixMethod);
			return this;
		}

		public PatchProcessor AddFinalizer(HarmonyMethod finalizer)
		{
			this.finalizer = finalizer;
			return this;
		}

		public PatchProcessor AddFinalizer(MethodInfo fixMethod)
		{
			finalizer = new HarmonyMethod(fixMethod);
			return this;
		}

		public static Patches GetPatchInfo(MethodBase method)
		{
			PatchInfo patchInfo = method.GetPatchInfo();
			if (patchInfo == null)
			{
				return null;
			}
			lock (patchInfo)
			{
				return new Patches(patchInfo.prefixes, patchInfo.postfixes, patchInfo.transpilers, patchInfo.finalizers);
			}
		}

		public static Dictionary<string, Version> VersionInfo(out Version currentVersion)
		{
			currentVersion = typeof(Harmony).Assembly.GetName().Version;
			Dictionary<string, Assembly> assemblies = new Dictionary<string, Assembly>();
			foreach (MethodBase allPatchedMethod in GetAllPatchedMethods())
			{
				Patches patchInfo = GetPatchInfo(allPatchedMethod);
				AddAssemblies(patchInfo.Prefixes);
				AddAssemblies(patchInfo.Postfixes);
				AddAssemblies(patchInfo.Transpilers);
				AddAssemblies(patchInfo.Finalizers);
			}
			Dictionary<string, Version> dictionary = new Dictionary<string, Version>();
			foreach (KeyValuePair<string, Assembly> item in assemblies)
			{
				AssemblyName assemblyName = item.Value.GetReferencedAssemblies().FirstOrDefault((AssemblyName a) => a.FullName.StartsWith("0Harmony, Version", StringComparison.Ordinal));
				if (assemblyName != null)
				{
					dictionary[item.Key] = assemblyName.Version;
				}
			}
			return dictionary;
			void AddAssemblies(IEnumerable<Patch> patches)
			{
				foreach (Patch patch in patches)
				{
					assemblies[patch.owner] = patch.patch.DeclaringType?.Assembly;
				}
			}
		}

		public static List<CodeInstruction> GetOriginalInstructions(MethodBase original, ILGenerator generator = null)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			DynamicMethodDefinition val = new DynamicMethodDefinition(original);
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body);
			ILGenerator il = generator ?? ((ILGeneratorShim)new CecilILGenerator(val.GetILProcessor())).GetProxy();
			return iLManipulator.GetInstructions(il);
		}

		public static List<CodeInstruction> GetOriginalInstructions(MethodBase original, out ILGenerator generator)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			DynamicMethodDefinition val = new DynamicMethodDefinition(original);
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body);
			generator = ((ILGeneratorShim)new CecilILGenerator(val.GetILProcessor())).GetProxy();
			return iLManipulator.GetInstructions(generator);
		}

		[Obsolete("Use GetAllPatchedMethods instead")]
		public static IEnumerable<MethodBase> AllPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		public static IEnumerable<MethodBase> GetAllPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		public List<DynamicMethod> Patch()
		{
			Stopwatch sw = null;
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				sw = Stopwatch.StartNew();
				return "Patching " + instance.Id + "...";
			});
			List<DynamicMethod> result = new List<DynamicMethod>();
			foreach (MethodBase original in originals)
			{
				if ((object)original == null)
				{
					throw new NullReferenceException("Null method for " + instance.Id);
				}
				Logger.Log(Logger.LogChannel.Info, () => "Patching " + Extensions.GetID(original, (string)null, (string)null, true, false, false));
				bool individualPrepareResult = RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, new object[1] { original });
				Logger.Log(Logger.LogChannel.Info, () => $"HarmonyPrepare result: {individualPrepareResult}");
				if (individualPrepareResult)
				{
					PatchInfo patchInfo = original.ToPatchInfo();
					lock (patchInfo)
					{
						patchInfo.AddPrefix(instance.Id, prefix);
						patchInfo.AddPostfix(instance.Id, postfix);
						patchInfo.AddTranspiler(instance.Id, transpiler);
						patchInfo.AddFinalizer(instance.Id, finalizer);
					}
					original.GetMethodPatcher().Apply();
					RunMethod<HarmonyCleanup>(new object[1] { original });
				}
			}
			Logger.Log(Logger.LogChannel.Info, () => $"Patching {instance.Id} took {sw.ElapsedMilliseconds}ms");
			return result;
		}

		public PatchProcessor Unpatch(HarmonyPatchType type, string harmonyID)
		{
			foreach (MethodBase original in originals)
			{
				PatchInfo patchInfo = original.ToPatchInfo();
				lock (patchInfo)
				{
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Prefix)
					{
						patchInfo.RemovePrefix(harmonyID);
					}
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Postfix)
					{
						patchInfo.RemovePostfix(harmonyID);
					}
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Transpiler)
					{
						patchInfo.RemoveTranspiler(harmonyID);
					}
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Finalizer)
					{
						patchInfo.RemoveFinalizer(harmonyID);
					}
				}
				original.GetMethodPatcher().Apply();
			}
			return this;
		}

		public PatchProcessor Unpatch(MethodInfo patch)
		{
			foreach (MethodBase original in originals)
			{
				original.ToPatchInfo().RemovePatch(patch);
				original.GetMethodPatcher().Apply();
			}
			return this;
		}

		private void PrepareType()
		{
			if (!RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, new object[0]))
			{
				return;
			}
			MethodType? methodType = containerAttributes.methodType;
			if (!containerAttributes.methodType.HasValue)
			{
				containerAttributes.methodType = MethodType.Normal;
			}
			string reversePatchAttr = typeof(HarmonyReversePatch).FullName;
			foreach (MethodInfo item in (from m in container.GetMethods(AccessTools.all)
				where m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == reversePatchAttr)
				select m).ToList())
			{
				MethodBase originalMethod = GetOriginalMethod(containerAttributes.Merge(new HarmonyMethod(item)));
				instance.CreateReversePatcher(originalMethod, item).Patch();
			}
			IEnumerable<MethodBase> enumerable = RunMethod<HarmonyTargetMethods, IEnumerable<MethodBase>>(null, new object[0]);
			if (enumerable != null)
			{
				originals.Clear();
				originals.AddRange(enumerable);
			}
			else if (container.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == typeof(HarmonyPatchAll).FullName))
			{
				Type declaringType = containerAttributes.declaringType;
				originals.AddRange(AccessTools.GetDeclaredConstructors(declaringType).Cast<MethodBase>());
				originals.AddRange(AccessTools.GetDeclaredMethods(declaringType).Cast<MethodBase>());
				List<PropertyInfo> declaredProperties = AccessTools.GetDeclaredProperties(declaringType);
				originals.AddRange((from prop in declaredProperties
					select prop.GetGetMethod(nonPublic: true) into method
					where (object)method != null
					select method).Cast<MethodBase>());
				originals.AddRange((from prop in declaredProperties
					select prop.GetSetMethod(nonPublic: true) into method
					where (object)method != null
					select method).Cast<MethodBase>());
			}
			else
			{
				MethodBase methodBase = RunMethod<HarmonyTargetMethod, MethodBase>(null, new object[0]) ?? GetOriginalMethod(containerAttributes);
				if ((object)methodBase == null)
				{
					string text = "(";
					text += $"declaringType={containerAttributes.declaringType}, ";
					text = text + "methodName =" + containerAttributes.methodName + ", ";
					text += $"methodType={methodType}, ";
					text = text + "argumentTypes=" + containerAttributes.argumentTypes.Description();
					text += ")";
					throw new ArgumentException("No target method specified for class " + container.FullName + " " + text);
				}
				originals.Add(methodBase);
			}
			GetPatches(container, out var methodInfo, out var methodInfo2, out var methodInfo3, out var methodInfo4);
			if (prefix != null)
			{
				prefix.method = methodInfo;
			}
			if (postfix != null)
			{
				postfix.method = methodInfo2;
			}
			if (transpiler != null)
			{
				transpiler.method = methodInfo3;
			}
			if (finalizer != null)
			{
				finalizer.method = methodInfo4;
			}
			if ((object)methodInfo != null)
			{
				if (!methodInfo.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(methodInfo);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod)).CopyTo(prefix);
			}
			if ((object)methodInfo2 != null)
			{
				if (!methodInfo2.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo2, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod2 = HarmonyMethodExtensions.GetFromMethod(methodInfo2);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod2)).CopyTo(postfix);
			}
			if ((object)methodInfo3 != null)
			{
				if (!methodInfo3.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo3, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod3 = HarmonyMethodExtensions.GetFromMethod(methodInfo3);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod3)).CopyTo(transpiler);
			}
			if ((object)methodInfo4 != null)
			{
				if (!methodInfo4.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo4, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod4 = HarmonyMethodExtensions.GetFromMethod(methodInfo4);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod4)).CopyTo(finalizer);
			}
		}

		internal static MethodBase GetOriginalMethod(HarmonyMethod attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			if ((object)attribute.declaringType == null)
			{
				return MakeFailure("declaringType cannot be null");
			}
			switch (attribute.methodType)
			{
			case MethodType.Normal:
			{
				if (string.IsNullOrEmpty(attribute.methodName))
				{
					return MakeFailure("methodName can't be empty");
				}
				if (attribute.methodName == ".ctor")
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Constructor should be used instead of setting methodName to .ctor");
					goto case MethodType.Constructor;
				}
				if (attribute.methodName == ".cctor")
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.StaticConstructor should be used instead of setting methodName to .cctor");
					goto case MethodType.StaticConstructor;
				}
				if (attribute.methodName.StartsWith("get_") || attribute.methodName.StartsWith("set_"))
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Getter and MethodType.Setter should be used instead adding get_ and set_ to property names");
				}
				MethodInfo methodInfo = AccessTools.DeclaredMethod(attribute.declaringType, attribute.methodName, attribute.argumentTypes);
				if ((object)methodInfo != null)
				{
					return methodInfo;
				}
				methodInfo = AccessTools.Method(attribute.declaringType, attribute.methodName, attribute.argumentTypes);
				if ((object)methodInfo != null)
				{
					string text = GetPatchName();
					object[] obj = new object[4] { attribute.methodName, null, null, null };
					Type[] argumentTypes = attribute.argumentTypes;
					obj[1] = ((argumentTypes != null) ? argumentTypes.Length : 0);
					obj[2] = attribute.declaringType.FullDescription();
					obj[3] = methodInfo.DeclaringType.FullDescription();
					Logger.LogText(Logger.LogChannel.Warn, text + string.Format(" - Could not find method {0} with {1} parameters in type {2}, but it was found in base class of this type {3}", obj));
					return methodInfo;
				}
				return MakeFailure("Could not find method " + attribute.methodName + " with " + attribute.argumentTypes.Description() + " parameters in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.Getter:
			{
				if (string.IsNullOrEmpty(attribute.methodName))
				{
					return MakeFailure("methodName can't be empty");
				}
				PropertyInfo propertyInfo2 = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo2 != null)
				{
					MethodInfo getMethod = propertyInfo2.GetGetMethod(nonPublic: true);
					if ((object)getMethod == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Getter");
					}
					return getMethod;
				}
				propertyInfo2 = AccessTools.Property(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo2 != null)
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription() + ", but it was found in base class of this type: " + propertyInfo2.DeclaringType.FullDescription());
					MethodInfo getMethod2 = propertyInfo2.GetGetMethod(nonPublic: true);
					if ((object)getMethod2 == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Getter");
					}
					return getMethod2;
				}
				return MakeFailure("Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.Setter:
			{
				if (string.IsNullOrEmpty(attribute.methodName))
				{
					return MakeFailure("methodName can't be empty");
				}
				PropertyInfo propertyInfo = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo != null)
				{
					MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
					if ((object)setMethod == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Setter");
					}
					return setMethod;
				}
				propertyInfo = AccessTools.Property(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo != null)
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription() + ", but it was found in base class of this type: " + propertyInfo.DeclaringType.FullDescription());
					MethodInfo setMethod2 = propertyInfo.GetSetMethod(nonPublic: true);
					if ((object)setMethod2 == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Setter");
					}
					return setMethod2;
				}
				return MakeFailure("Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.Constructor:
			{
				ConstructorInfo constructorInfo2 = AccessTools.DeclaredConstructor(attribute.declaringType, attribute.argumentTypes);
				if ((object)constructorInfo2 != null)
				{
					return constructorInfo2;
				}
				return MakeFailure("Could not find constructor with " + attribute.argumentTypes.Description() + " parameters in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.StaticConstructor:
			{
				ConstructorInfo constructorInfo = AccessTools.GetDeclaredConstructors(attribute.declaringType).FirstOrDefault((ConstructorInfo c) => c.IsStatic);
				if ((object)constructorInfo != null)
				{
					return constructorInfo;
				}
				return MakeFailure("Could not find static constructor in type " + attribute.declaringType.FullDescription());
			}
			default:
				throw new ArgumentOutOfRangeException("methodType", attribute.methodType, "Unknown method type");
			}
			string GetPatchName()
			{
				return attribute.method?.FullDescription() ?? "Unknown patch";
			}
			MethodBase MakeFailure(string reason)
			{
				Logger.Log(Logger.LogChannel.Error, () => "Failed to process patch " + GetPatchName() + " - " + reason);
				return null;
			}
		}

		private T RunMethod<S, T>(T defaultIfNotExisting, params object[] parameters)
		{
			if ((object)container == null)
			{
				return defaultIfNotExisting;
			}
			string name = typeof(S).Name.Replace("Harmony", "");
			MethodInfo patchMethod = GetPatchMethod<S>(container, name);
			if ((object)patchMethod != null)
			{
				if (typeof(T).IsAssignableFrom(patchMethod.ReturnType))
				{
					object[] emptyTypes = Type.EmptyTypes;
					return (T)patchMethod.Invoke(null, emptyTypes);
				}
				object[] inputs = (parameters ?? new object[0]).Union(new object[1] { instance }).ToArray();
				object[] parameters2 = AccessTools.ActualParameters(patchMethod, inputs);
				patchMethod.Invoke(null, parameters2);
				return defaultIfNotExisting;
			}
			return defaultIfNotExisting;
		}

		private void RunMethod<S>(params object[] parameters)
		{
			if ((object)container != null)
			{
				string name = typeof(S).Name.Replace("Harmony", "");
				MethodInfo patchMethod = GetPatchMethod<S>(container, name);
				if ((object)patchMethod != null)
				{
					object[] inputs = (parameters ?? new object[0]).Union(new object[1] { instance }).ToArray();
					object[] parameters2 = AccessTools.ActualParameters(patchMethod, inputs);
					patchMethod.Invoke(null, parameters2);
				}
			}
		}

		private MethodInfo GetPatchMethod<T>(Type patchType, string name)
		{
			string attributeType = typeof(T).FullName;
			MethodInfo methodInfo = patchType.GetMethods(AccessTools.all).FirstOrDefault((MethodInfo m) => m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == attributeType));
			if ((object)methodInfo == null)
			{
				methodInfo = patchType.GetMethod(name, AccessTools.all);
			}
			return methodInfo;
		}

		private void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler, out MethodInfo finalizer)
		{
			prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
			postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
			transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
			finalizer = GetPatchMethod<HarmonyFinalizer>(patchType, "Finalizer");
		}
	}
	public class ReversePatcher
	{
		private readonly Harmony instance;

		private readonly MethodBase original;

		private readonly MethodInfo standin;

		private readonly ILHook ilHook;

		public ReversePatcher(Harmony instance, MethodBase original, MethodInfo standin)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			this.instance = instance;
			this.original = original;
			this.standin = standin;
			ilHook = new ILHook((MethodBase)standin, new Manipulator(ApplyReversePatch), new ILHookConfig
			{
				ManualApply = true
			});
		}

		private void ApplyReversePatch(ILContext ctx)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			DynamicMethodDefinition val = new DynamicMethodDefinition(original);
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body);
			ctx.Body.Variables.Clear();
			Enumerator<VariableDefinition> enumerator = val.Definition.Body.Variables.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					VariableDefinition current = enumerator.Current;
					ctx.Body.Variables.Add(new VariableDefinition(ctx.Module.ImportReference(((VariableReference)current).VariableType)));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodInfo transpiler = GetTranspiler(standin);
			if ((object)transpiler != null)
			{
				iLManipulator.AddTranspiler(transpiler);
			}
			iLManipulator.WriteTo(ctx.Body, standin);
			ctx.IL.Emit(OpCodes.Ret);
		}

		public void Patch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
		{
			if ((object)original == null)
			{
				throw new NullReferenceException("Null method for " + instance.Id);
			}
			ilHook.Apply();
		}

		private MethodInfo GetTranspiler(MethodInfo method)
		{
			string methodName = method.Name;
			List<MethodInfo> declaredMethods = AccessTools.GetDeclaredMethods(method.DeclaringType);
			Type ici = typeof(IEnumerable<CodeInstruction>);
			return declaredMethods.FirstOrDefault((MethodInfo m) => (object)m.ReturnType == ici && m.Name.StartsWith("<" + methodName + ">"));
		}
	}
	public class CodeMatch
	{
		public string name;

		public List<OpCode> opcodes = new List<OpCode>();

		public List<object> operands = new List<object>();

		public List<Label> labels = new List<Label>();

		public List<ExceptionBlock> blocks = new List<ExceptionBlock>();

		public List<int> jumpsFrom = new List<int>();

		public List<int> jumpsTo = new List<int>();

		public Func<CodeInstruction, bool> predicate;

		public CodeMatch(OpCode? opcode = null, object operand = null, string name = null)
		{
			if (opcode.HasValue)
			{
				OpCode valueOrDefault = opcode.GetValueOrDefault();
				opcodes.Add(valueOrDefault);
			}
			if (operand != null)
			{
				operands.Add(operand);
			}
			this.name = name;
		}

		public CodeMatch(CodeInstruction instruction, string name = null)
			: this(instruction.opcode, instruction.operand, name)
		{
		}

		public CodeMatch(Func<CodeInstruction, bool> predicate, string name = null)
		{
			this.predicate = predicate;
			this.name = name;
		}

		internal bool Matches(List<CodeInstruction> codes, CodeInstruction instruction)
		{
			if (predicate != null)
			{
				return predicate(instruction);
			}
			if (opcodes.Count > 0 && !opcodes.Contains(instruction.opcode))
			{
				return false;
			}
			if (operands.Count > 0 && !operands.Contains(instruction.operand))
			{
				return false;
			}
			if (labels.Count > 0 && !labels.Intersect(instruction.labels).Any())
			{
				return false;
			}
			if (blocks.Count > 0 && !blocks.Intersect(instruction.blocks).Any())
			{
				return false;
			}
			if (jumpsFrom.Count > 0 && !jumpsFrom.Select((int index) => codes[index].operand).OfType<Label>().Intersect(instruction.labels)
				.Any())
			{
				return false;
			}
			if (jumpsTo.Count > 0)
			{
				object operand = instruction.operand;
				if (operand == null || (object)operand.GetType() != typeof(Label))
				{
					return false;
				}
				Label label = (Label)operand;
				IEnumerable<int> second = from idx in Enumerable.Range(0, codes.Count)
					where codes[idx].labels.Contains(label)
					select idx;
				if (!jumpsTo.Intersect(second).Any())
				{
					return false;
				}
			}
			return true;
		}

		public override string ToString()
		{
			string text = "[";
			if (name != null)
			{
				text = text + name + ": ";
			}
			if (opcodes.Count > 0)
			{
				text = text + "opcodes=" + opcodes.Join() + " ";
			}
			if (operands.Count > 0)
			{
				text = text + "operands=" + operands.Join() + " ";
			}
			if (labels.Count > 0)
			{
				text = text + "labels=" + labels.Join() + " ";
			}
			if (blocks.Count > 0)
			{
				text = text + "blocks=" + blocks.Join() + " ";
			}
			if (jumpsFrom.Count > 0)
			{
				text = text + "jumpsFrom=" + jumpsFrom.Join() + " ";
			}
			if (jumpsTo.Count > 0)
			{
				text = text + "jumpsTo=" + jumpsTo.Join() + " ";
			}
			if (predicate != null)
			{
				text += "predicate=yes ";
			}
			return text.TrimEnd(new char[0]) + "]";
		}
	}
	public class CodeMatcher
	{
		private readonly ILGenerator generator;

		private readonly List<CodeInstruction> codes = new List<CodeInstruction>();

		private Dictionary<string, CodeInstruction> lastMatches = new Dictionary<string, CodeInstruction>();

		private string lastError;

		private bool lastUseEnd;

		private CodeMatch[] lastCodeMatches;

		public int Pos { get; private set; } = -1;


		public int Length => codes.Count;

		public bool IsValid
		{
			get
			{
				if (Pos >= 0)
				{
					return Pos < Length;
				}
				return false;
			}
		}

		public bool IsInvalid
		{
			get
			{
				if (Pos >= 0)
				{
					return Pos >= Length;
				}
				return true;
			}
		}

		public int Remaining => Length - Math.Max(0, Pos);

		public ref OpCode Opcode => ref codes[Pos].opcode;

		public ref object Operand => ref codes[Pos].operand;

		public ref List<Label> Labels => ref codes[Pos].labels;

		public ref List<ExceptionBlock> Blocks => ref codes[Pos].blocks;

		public CodeInstruction Instruction => codes[Pos];

		private void FixStart()
		{
			Pos = Math.Max(0, Pos);
		}

		private void SetOutOfBounds(int direction)
		{
			Pos = ((direction > 0) ? Length : (-1));
		}

		public CodeMatcher()
		{
		}

		public CodeMatcher(IEnumerable<CodeInstruction> instructions, ILGenerator generator = null)
		{
			this.generator = generator;
			codes = instructions.Select((CodeInstruction c) => new CodeInstruction(c)).ToList();
		}

		public CodeMatcher Clone()
		{
			return new CodeMatcher(codes, generator)
			{
				Pos = Pos,
				lastMatches = lastMatches,
				lastError = lastError,
				lastUseEnd = lastUseEnd,
				lastCodeMatches = lastCodeMatches
			};
		}

		public CodeInstruction InstructionAt(int offset)
		{
			return codes[Pos + offset];
		}

		public List<CodeInstruction> Instructions()
		{
			return codes;
		}

		public IEnumerable<CodeInstruction> InstructionEnumeration()
		{
			return codes.AsEnumerable();
		}

		public List<CodeInstruction> Instructions(int count)
		{
			return (from c in codes.GetRange(Pos, count)
				select new CodeInstruction(c)).ToList();
		}

		public List<CodeInstruction> InstructionsInRange(int start, int end)
		{
			List<CodeInstruction> list = codes;
			if (start > end)
			{
				int num = start;
				start = end;
				end = num;
			}
			return (from c in list.GetRange(start, end - start + 1)
				select new CodeInstruction(c)).ToList();
		}

		public List<CodeInstruction> InstructionsWithOffsets(int startOffset, int endOffset)
		{
			return InstructionsInRange(Pos + startOffset, Pos + endOffset);
		}

		public List<Label> DistinctLabels(IEnumerable<CodeInstruction> instructions)
		{
			return instructions.SelectMany((CodeInstruction instruction) => instruction.labels).Distinct().ToList();
		}

		public bool ReportFailure(MethodBase method, Action<string> logger)
		{
			if (IsValid)
			{
				return false;
			}
			string arg = lastError ?? "Unexpected code";
			logger($"{arg} in {method}");
			return true;
		}

		public CodeMatcher SetInstruction(CodeInstruction instruction)
		{
			codes[Pos] = instruction;
			return this;
		}

		public CodeMatcher SetInstructionAndAdvance(CodeInstruction instruction)
		{
			SetInstruction(instruction);
			Pos++;
			return this;
		}

		public CodeMatcher Set(OpCode opcode, object operand)
		{
			Opcode = opcode;
			Operand = operand;
			return this;
		}

		public CodeMatcher SetAndAdvance(OpCode opcode, object operand)
		{
			Set(opcode, operand);
			Pos++;
			return this;
		}

		public CodeMatcher SetOpcodeAndAdvance(OpCode opcode)
		{
			Opcode = opcode;
			Pos++;
			return this;
		}

		public CodeMatcher SetOperandAndAdvance(object operand)
		{
			Operand = operand;
			Pos++;
			return this;
		}

		public CodeMatcher CreateLabel(out Label label)
		{
			label = generator.DefineLabel();
			Labels.Add(label);
			return this;
		}

		public CodeMatcher CreateLabelAt(int position, out Label label)
		{
			label = generator.DefineLabel();
			AddLabelsAt(position, new Label[1] { label });
			return this;
		}

		public CodeMatcher AddLabels(IEnumerable<Label> labels)
		{
			Labels.AddRange(labels);
			return this;
		}

		public CodeMatcher AddLabelsAt(int position, IEnumerable<Label> labels)
		{
			codes[position].labels.AddRange(labels);
			return this;
		}

		public CodeMatcher SetJumpTo(OpCode opcode, int destination, out Label label)
		{
			CreateLabelAt(destination, out label);
			Set(opcode, label);
			return this;
		}

		public CodeMatcher Insert(params CodeInstruction[] instructions)
		{
			codes.InsertRange(Pos, instructions);
			return this;
		}

		public CodeMatcher Insert(IEnumerable<CodeInstruction> instructions)
		{
			codes.InsertRange(Pos, instructions);
			return this;
		}

		public CodeMatcher InsertBranch(OpCode opcode, int destination)
		{
			CreateLabelAt(destination, out var label);
			codes.Insert(Pos, new CodeInstruction(opcode, label));
			return this;
		}

		public CodeMatcher InsertAndAdvance(params CodeInstruction[] instructions)
		{
			foreach (CodeInstruction codeInstruction in instructions)
			{
				Insert(codeInstruction);
				Pos++;
			}
			return this;
		}

		public CodeMatcher InsertAndAdvance(IEnumerable<CodeInstruction> instructions)
		{
			foreach (CodeInstruction instruction in instructions)
			{
				InsertAndAdvance(instruction);
			}
			return this;
		}

		public CodeMatcher InsertBranchAndAdvance(OpCode opcode, int destination)
		{
			InsertBranch(opcode, destination);
			Pos++;
			return this;
		}

		public CodeMatcher RemoveInstruction()
		{
			codes.RemoveAt(Pos);
			return this;
		}

		public CodeMatcher RemoveInstructions(int count)
		{
			codes.RemoveRange(Pos, count);
			return this;
		}

		public CodeMatcher RemoveInstructionsInRange(int start, int end)
		{
			if (start > end)
			{
				int num = start;
				start = end;
				end = num;
			}
			codes.RemoveRange(start, end - start + 1);
			return this;
		}

		public CodeMatcher RemoveInstructionsWithOffsets(int startOffset, int endOffset)
		{
			RemoveInstructionsInRange(Pos + startOffset, Pos + endOffset);
			return this;
		}

		public CodeMatcher Advance(int offset)
		{
			Pos += offset;
			if (!IsValid)
			{
				SetOutOfBounds(offset);
			}
			return this;
		}

		public CodeMatcher Start()
		{
			Pos = 0;
			return this;
		}

		public CodeMatcher End()
		{
			Pos = Length - 1;
			return this;
		}

		public CodeMatcher SearchForward(Func<CodeInstruction, bool> predicate)
		{
			return Search(predicate, 1);
		}

		public CodeMatcher SearchBack(Func<CodeInstruction, bool> predicate)
		{
			return Search(predicate, -1);
		}

		private CodeMatcher Search(Func<CodeInstruction, bool> predicate, int direction)
		{
			FixStart();
			while (IsValid && !predicate(Instruction))
			{
				Pos += direction;
			}
			lastError = (IsInvalid ? $"Cannot find {predicate}" : null);
			return this;
		}

		public CodeMatcher MatchForward(bool useEnd, params CodeMatch[] matches)
		{
			return Match(matches, 1, useEnd);
		}

		public CodeMatcher MatchBack(bool useEnd, params CodeMatch[] matches)
		{
			return Match(matches, -1, useEnd);
		}

		private CodeMatcher Match(CodeMatch[] matches, int direction, bool useEnd)
		{
			FixStart();
			while (IsValid)
			{
				lastUseEnd = useEnd;
				lastCodeMatches = matches;
				if (MatchSequence(Pos, matches))
				{
					if (useEnd)
					{
						Pos += matches.Count() - 1;
					}
					break;
				}
				Pos += direction;
			}
			lastError = (IsInvalid ? ("Cannot find " + matches.Join()) : null);
			return this;
		}

		public CodeMatcher Repeat(Action<CodeMatcher> matchAction, Action<string> notFoundAction = null)
		{
			int num = 0;
			if (lastCodeMatches == null)
			{
				throw new InvalidOperationException("No previous Match operation - cannot repeat");
			}
			while (IsValid)
			{
				matchAction(this);
				MatchForward(lastUseEnd, lastCodeMatches);
				num++;
			}
			lastCodeMatches = null;
			if (num == 0)
			{
				notFoundAction?.Invoke(lastError);
			}
			return this;
		}

		public CodeInstruction NamedMatch(string name)
		{
			return lastMatches[name];
		}

		private bool MatchSequence(int start, CodeMatch[] matches)
		{
			if (start < 0)
			{
				return false;
			}
			lastMatches = new Dictionary<string, CodeInstruction>();
			foreach (CodeMatch codeMatch in matches)
			{
				if (start >= Length || !codeMatch.Matches(codes, codes[start]))
				{
					return false;
				}
				if (codeMatch.name != null)
				{
					lastMatches.Add(codeMatch.name, codes[start]);
				}
				start++;
			}
			return true;
		}
	}
	public static class CodeInstructionExtensions
	{
		private static readonly HashSet<OpCode> LoadVarCodes = new HashSet<OpCode>
		{
			OpCodes.Ldloc_0,
			OpCodes.Ldloc_1,
			OpCodes.Ldloc_2,
			OpCodes.Ldloc_3,
			OpCodes.Ldloc,
			OpCodes.Ldloca,
			OpCodes.Ldloc_S,
			OpCodes.Ldloca_S
		};

		private static readonly HashSet<OpCode> StoreVarCodes = new HashSet<OpCode>
		{
			OpCodes.Stloc_0,
			OpCodes.Stloc_1,
			OpCodes.Stloc_2,
			OpCodes.Stloc_3,
			OpCodes.Stloc,
			OpCodes.Stloc_S
		};

		private static readonly HashSet<OpCode> BranchCodes = new HashSet<OpCode>
		{
			OpCodes.Br_S,
			OpCodes.Brfalse_S,
			OpCodes.Brtrue_S,
			OpCodes.Beq_S,
			OpCodes.Bge_S,
			OpCodes.Bgt_S,
			OpCodes.Ble_S,
			OpCodes.Blt_S,
			OpCodes.Bne_Un_S,
			OpCodes.Bge_Un_S,
			OpCodes.Bgt_Un_S,
			OpCodes.Ble_Un_S,
			OpCodes.Blt_Un_S,
			OpCodes.Br,
			OpCodes.Brfalse,
			OpCodes.Brtrue,
			OpCodes.Beq,
			OpCodes.Bge,
			OpCodes.Bgt,
			OpCodes.Ble,
			OpCodes.Blt,
			OpCodes.Bne_Un,
			OpCodes.Bge_Un,
			OpCodes.Bgt_Un,
			OpCodes.Ble_Un,
			OpCodes.Blt_Un
		};

		private static readonly HashSet<OpCode> ConstantLoadingCodes = new HashSet<OpCode>
		{
			OpCodes.Ldc_I4_M1,
			OpCodes.Ldc_I4_0,
			OpCodes.Ldc_I4_1,
			OpCodes.Ldc_I4_2,
			OpCodes.Ldc_I4_3,
			OpCodes.Ldc_I4_4,
			OpCodes.Ldc_I4_5,
			OpCodes.Ldc_I4_6,
			OpCodes.Ldc_I4_7,
			OpCodes.Ldc_I4_8,
			OpCodes.Ldc_I4,
			OpCodes.Ldc_I4_S,
			OpCodes.Ldc_I8,
			OpCodes.Ldc_R4,
			OpCodes.Ldc_R8
		};

		public static bool OperandIs(this CodeInstruction code, object value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (code.operand == null)
			{
				return false;
			}
			Type type = value.GetType();
			Type type2 = code.operand.GetType();
			if (AccessTools.IsInteger(type) && AccessTools.IsNumber(type2))
			{
				return Convert.ToInt64(code.operand) == Convert.ToInt64(value);
			}
			if (AccessTools.IsFloatingPoint(type) && AccessTools.IsNumber(type2))
			{
				return Convert.ToDouble(code.operand) == Convert.ToDouble(value);
			}
			return object.Equals(code.operand, value);
		}

		public static bool Is(this CodeInstruction code, OpCode opcode, object operand)
		{
			if (code.opcode == opcode)
			{
				return code.OperandIs(operand);
			}
			return false;
		}

		public static bool IsLdarg(this CodeInstruction code, int? n = null)
		{
			if ((!n.HasValue || n.Value == 0) && code.opcode == OpCodes.Ldarg_0)
			{
				return true;
			}
			if ((!n.HasValue || n.Value == 1) && code.opcode == OpCodes.Ldarg_1)
			{
				return true;
			}
			if ((!n.HasValue || n.Value == 2) && code.opcode == OpCodes.Ldarg_2)
			{
				return true;
			}
			if ((!n.HasValue || n.Value == 3) && code.opcode == OpCodes.Ldarg_3)
			{
				return true;
			}
			if (code.opcode == OpCodes.Ldarg && (!n.HasValue || n.Value == Convert.ToInt32(code.operand)))
			{
				return true;
			}
			if (code.opcode == OpCodes.Ldarg_S && (!n.HasValue || n.Value == Convert.ToInt32(code.operand)))
			{
				return true;
			}
			return false;
		}

		public static bool IsLdarga(this CodeInstruction code, int? n = null)
		{
			if (code.opcode != OpCodes.Ldarga && code.opcode != OpCodes.Ldarga_S)
			{
				return false;
			}
			if (n.HasValue)
			{
				return n.Value == Convert.ToInt32(code.operand);
			}
			return true;
		}

		public static bool IsStarg(this CodeInstruction code, int? n = null)
		{
			if (code.opcode != OpCodes.Starg && code.opcode != OpCodes.Starg_S)
			{
				return false;
			}
			if (n.HasValue)
			{
				return n.Value == Convert.ToInt32(code.operand);
			}
			return true;
		}

		public static bool IsLdloc(this CodeInstruction code, LocalBuilder variable = null)
		{
			if (!LoadVarCodes.Contains(code.opcode))
			{
				return false;
			}
			if (variable != null)
			{
				return object.Equals(variable, code.operand);
			}
			return true;
		}

		public static bool IsStloc(this CodeInstruction code, LocalBuilder variable = null)
		{
			if (!StoreVarCodes.Contains(code.opcode))
			{
				return false;
			}
			if (variable != null)
			{
				return object.Equals(variable, code.operand);
			}
			return true;
		}

		public static bool Branches(this CodeInstruction code, out Label? label)
		{
			if (BranchCodes.Contains(code.opcode))
			{
				label = (Label)code.operand;
				return true;
			}
			label = null;
			return false;
		}

		public static bool Calls(this CodeInstruction code, MethodInfo method)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			if (code.opcode != OpCodes.Call && code.opcode != OpCodes.Callvirt)
			{
				return false;
			}
			return object.Equals(code.operand, method);
		}

		public static bool LoadsConstant(this CodeInstruction code)
		{
			return ConstantLoadingCodes.Contains(code.opcode);
		}

		public static bool LoadsConstant(this CodeInstruction code, long number)
		{
			OpCode opcode = code.opcode;
			if (number == -1 && opcode == OpCodes.Ldc_I4_M1)
			{
				return true;
			}
			if (number == 0L && opcode == OpCodes.Ldc_I4_0)
			{
				return true;
			}
			if (number == 1 && opcode == OpCodes.Ldc_I4_1)
			{
				return true;
			}
			if (number == 2 && opcode == OpCodes.Ldc_I4_2)
			{
				return true;
			}
			if (number == 3 && opcode == OpCodes.Ldc_I4_3)
			{
				return true;
			}
			if (number == 4 && opcode == OpCodes.Ldc_I4_4)
			{
				return true;
			}
			if (number == 5 && opcode == OpCodes.Ldc_I4_5)
			{
				return true;
			}
			if (number == 6 && opcode == OpCodes.Ldc_I4_6)
			{
				return true;
			}
			if (number == 7 && opcode == OpCodes.Ldc_I4_7)
			{
				return true;
			}
			if (number == 8 && opcode == OpCodes.Ldc_I4_8)
			{
				return true;
			}
			if (opcode != OpCodes.Ldc_I4 && opcode != OpCodes.Ldc_I4_S && opcode != OpCodes.Ldc_I8)
			{
				return false;
			}
			return Convert.ToInt64(code.operand) == number;
		}

		public static bool LoadsConstant(this CodeInstruction code, double number)
		{
			if (code.opcode != OpCodes.Ldc_R4 && code.opcode != OpCodes.Ldc_R8)
			{
				return false;
			}
			return Convert.ToDouble(code.operand) == number;
		}

		public static bool LoadsConstant(this CodeInstruction code, Enum e)
		{
			return code.LoadsConstant(Convert.ToInt64(e));
		}

		public static bool LoadsField(this CodeInstruction code, FieldInfo field, bool byAddress = false)
		{
			if ((object)field == null)
			{
				throw new ArgumentNullException("field");
			}
			OpCode opCode = (field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld);
			if (!byAddress && code.opcode == opCode && object.Equals(code.operand, field))
			{
				return true;
			}
			OpCode opCode2 = (field.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda);
			if (byAddress && code.opcode == opCode2 && object.Equals(code.operand, field))
			{
				return true;
			}
			return false;
		}

		public static bool StoresField(this CodeInstruction code, FieldInfo field)
		{
			if ((object)field == null)
			{
				throw new ArgumentNullException("field");
			}
			OpCode opCode = (field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld);
			if (code.opcode == opCode)
			{
				return object.Equals(code.operand, field);
			}
			return false;
		}

		public static CodeInstruction WithLabels(this CodeInstruction code, params Label[] labels)
		{
			code.labels.AddRange(labels);
			return code;
		}

		public static CodeInstruction WithLabels(this CodeInstruction code, IEnumerable<Label> labels)
		{
			code.labels.AddRange(labels);
			return code;
		}

		public static List<Label> ExtractLabels(this CodeInstruction code)
		{
			List<Label> result = new List<Label>(code.labels);
			code.labels.Clear();
			return result;
		}

		public static CodeInstruction MoveLabelsTo(this CodeInstruction code, CodeInstruction other)
		{
			other.WithLabels(code.ExtractLabels());
			return code;
		}

		public static CodeInstruction MoveLabelsFrom(this CodeInstruction code, CodeInstruction other)
		{
			return code.WithLabels(other.ExtractLabels());
		}

		public static CodeInstruction WithBlocks(this CodeInstruction code, params ExceptionBlock[] blocks)
		{
			code.blocks.AddRange(blocks);
			return code;
		}

		public static CodeInstruction WithBlocks(this CodeInstruction code, IEnumerable<ExceptionBlock> blocks)
		{
			code.blocks.AddRange(blocks);
			return code;
		}

		public static List<ExceptionBlock> ExtractBlocks(this CodeInstruction code)
		{
			List<ExceptionBlock> result = new List<ExceptionBlock>(code.blocks);
			code.blocks.Clear();
			return result;
		}

		public static CodeInstruction MoveBlocksTo(this CodeInstruction code, CodeInstruction other)
		{
			other.WithBlocks(code.ExtractBlocks());
			return code;
		}

		public static CodeInstruction MoveBlocksFrom(this CodeInstruction code, CodeInstruction other)
		{
			return code.WithBlocks(other.ExtractBlocks());
		}
	}
	public static class CollectionExtensions
	{
		public static void Do<T>(this IEnumerable<T> sequence, Action<T> action)
		{
			if (sequence != null)
			{
				IEnumerator<T> enumerator = sequence.GetEnumerator();
				while (enumerator.MoveNext())
				{
					action(enumerator.Current);
				}
			}
		}

		public static void DoIf<T>(this IEnumerable<T> sequence, Func<T, bool> condition, Action<T> action)
		{
			sequence.Where(condition).Do(action);
		}

		public static IEnumerable<T> AddItem<T>(this IEnumerable<T> sequence, T item)
		{
			return (sequence ?? Enumerable.Empty<T>()).Concat(new T[1] { item });
		}

		public static T[] AddToArray<T>(this T[] sequence, T item)
		{
			return sequence.AddItem(item).ToArray();
		}

		public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)
		{
			return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();
		}
	}
	public static class GeneralExtensions
	{
		public static string Join<T>(this IEnumerable<T> enumeration, Func<T, string> converter = null, string delimiter = ", ")
		{
			if (converter == null)
			{
				converter = (T t) => t.ToString();
			}
			return enumeration.Aggregate("", (string prev, T curr) => prev + ((prev != "") ? delimiter : "") + converter(curr));
		}

		public static string Description(this Type[] parameters)
		{
			if (parameters == null)
			{
				return "NULL";
			}
			return "(" + parameters.Join((Type p) => p.FullDescription()) + ")";
		}

		public static string FullDescription(this Type type)
		{
			if ((object)type == null)
			{
				return "null";
			}
			string text = type.Namespace;
			if (!string.IsNullOrEmpty(text))
			{
				text += ".";
			}
			string text2 = text + type.Name;
			if (type.IsGenericType)
			{
				text2 += "<";
				Type[] genericArguments = type.GetGenericArguments();
				for (int i = 0; i < genericArguments.Length; i++)
				{
					if (!text2.EndsWith("<", StringComparison.Ordinal))
					{
						text2 += ", ";
					}
					text2 += genericArguments[i].FullDescription();
				}
				text2 += ">";
			}
			return text2;
		}

		public static string FullDescription(this MethodBase method)
		{
			if ((object)method == null)
			{
				return "null";
			}
			Type[] parameters = (from p in method.GetParameters()
				select p.ParameterType).ToArray();
			Type returnedType = AccessTools.GetReturnedType(method);
			return returnedType.FullDescription() + " " + method.DeclaringType.FullDescription() + "." + method.Name + parameters.Description();
		}

		public static Type[] Types(this ParameterInfo[] pinfo)
		{
			return pinfo.Select((ParameterInfo pi) => pi.ParameterType).ToArray();
		}

		public static T GetValueSafe<S, T>(this Dictionary<S, T> dictionary, S key)
		{
			if (dictionary.TryGetValue(key, out var value))
			{
				return value;
			}
			return default(T);
		}

		public static T GetTypedValue<T>(this Dictionary<string, object> dictionary, string key)
		{
			if (dictionary.TryGetValue(key, out var value) && value is T)
			{
				return (T)value;
			}
			return default(T);
		}
	}
	public static class SymbolExtensions
	{
		public static MethodInfo GetMethodInfo(Expression<Action> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		public static MethodInfo GetMethodInfo<T, TResult>(Expression<Func<T, TResult>> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		public static MethodInfo GetMethodInfo(LambdaExpression expression)
		{
			return ((expression.Body as MethodCallExpression) ?? throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only.")).Method ?? throw new MemberNotFoundException($"Cannot find method for expression {expression}");
		}
	}
	[Obsolete("Use HarmonyFileLog instead", true)]
	public static class FileLog
	{
		public static string logPath;

		public static char indentChar;

		public static int indentLevel;

		private static List<string> buffer;

		static FileLog()
		{
			indentChar = '\t';
			buffer = new List<string>();
			logPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}{Path.DirectorySeparatorChar}harmony.log.txt";
		}

		private static string IndentString()
		{
			return new string(indentChar, indentLevel);
		}

		public static void ChangeIndent(int delta)
		{
			indentLevel = Math.Max(0, indentLevel + delta);
		}

		public static void LogBuffered(string str)
		{
			lock (logPath)
			{
				buffer.Add(IndentString() + str);
			}
		}

		public static void LogBuffered(List<string> strings)
		{
			lock (logPath)
			{
				buffer.AddRange(strings);
			}
		}

		public static List<string> GetBuffer(bool clear)
		{
			lock (logPath)
			{
				List<string> result = buffer;
				if (clear)
				{
					buffer = new List<string>();
				}
				return result;
			}
		}

		public static void SetBuffer(List<string> buffer)
		{
			lock (logPath)
			{
				FileLog.buffer = buffer;
			}
		}

		public static void FlushBuffer()
		{
			lock (logPath)
			{
				if (buffer.Count <= 0)
				{
					return;
				}
				using (StreamWriter streamWriter = File.AppendText(logPath))
				{
					foreach (string item in buffer)
					{
						streamWriter.WriteLine(item);
					}
				}
				buffer.Clear();
			}
		}

		public static void Log(string str)
		{
			lock (logPath)
			{
				using StreamWriter streamWriter = File.AppendText(logPath);
				streamWriter.WriteLine(IndentString() + str);
			}
		}

		public static void Reset()
		{
			lock (logPath)
			{
				File.Delete($"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}{Path.DirectorySeparatorChar}harmony.log.txt");
			}
		}

		public unsafe static void LogBytes(long ptr, int len)
		{
			lock (logPath)
			{
				byte* ptr2 = (byte*)ptr;
				string text = "";
				for (int i = 1; i <= len; i++)
				{
					if (text == "")
					{
						text = "#  ";
					}
					text = $"{text}{*ptr2:X2} ";
					if (i > 1 || len == 1)
					{
						if (i % 8 == 0 || i == len)
						{
							Log(text);
							text = "";
						}
						else if (i % 4 == 0)
						{
							text += " ";
						}
					}
					ptr2++;
				}
				byte[] destination = new byte[len];
				Marshal.Copy((IntPtr)ptr, destination, 0, len);
				byte[] array = MD5.Create().ComputeHash(destination);
				StringBuilder stringBuilder = new StringBuilder();
				for (int j = 0; j < array.Length; j++)
				{
					stringBuilder.Append(array[j].ToString("X2"));
				}
				Log($"HASH: {stringBuilder}");
			}
		}
	}
	public static class AccessTools
	{
		public delegate ref U FieldRef<T, U>(T obj = default(T));

		public delegate ref F FieldRef<F>();

		public static BindingFlags all = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty;

		public static BindingFlags allDeclared = all | BindingFlags.DeclaredOnly;

		private static readonly MethodInfo m_PrepForRemoting = Method(typeof(Exception), "PrepForRemoting") ?? Method(typeof(Exception), "FixRemotingException");

		private static readonly FastInvokeHandler PrepForRemoting = MethodInvoker.GetHandler(m_PrepForRemoting);

		public static bool IsMonoRuntime { get; } = (object)Type.GetType("Mono.Runtime") != null;


		public static Type TypeByName(string name)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			Type type = Type.GetType(name, throwOnError: false);
			if ((object)type == null)
			{
				type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
					select assembly.GetType(name)).FirstOrDefault((Type t) => (object)t != null);
			}
			if ((object)type == null)
			{
				type = AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly x) => x.GetTypes()).FirstOrDefault((Type x) => x.Name == name);
			}
			if ((object)type == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => "AccessTools.TypeByName: Could not find type named " + name);
			}
			return type;
		}

		public static T FindIncludingBaseTypes<T>(Type type, Func<Type, T> func) where T : class
		{
			while (true)
			{
				T val = func(type);
				if (val != null)
				{
					return val;
				}
				if ((object)type == typeof(object))
				{
					break;
				}
				type = type.BaseType;
			}
			return null;
		}

		public static T FindIncludingInnerTypes<T>(Type type, Func<Type, T> func) where T : class
		{
			T val = func(type);
			if (val != null)
			{
				return val;
			}
			Type[] nestedTypes = type.GetNestedTypes(all);
			for (int i = 0; i < nestedTypes.Length; i++)
			{
				val = FindIncludingInnerTypes(nestedTypes[i], func);
				if (val != null)
				{
					break;
				}
			}
			return val;
		}

		public static FieldInfo DeclaredField(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			FieldInfo? field = type.GetField(name, allDeclared);
			if ((object)field == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredField: Could not find field for type {type} and name {name}");
			}
			return field;
		}

		public static FieldInfo Field(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			FieldInfo? fieldInfo = FindIncludingBaseTypes(type, (Type t) => t.GetField(name, all));
			if ((object)fieldInfo == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Field: Could not find field for type {type} and name {name}");
			}
			return fieldInfo;
		}

		public static FieldInfo DeclaredField(Type type, int idx)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			FieldInfo? fieldInfo = GetDeclaredFields(type).ElementAtOrDefault(idx);
			if ((object)fieldInfo == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredField: Could not find field for type {type} and idx {idx}");
			}
			return fieldInfo;
		}

		public static PropertyInfo DeclaredProperty(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			try
			{
				PropertyInfo? property = type.GetProperty(name, allDeclared);
				if ((object)property == null)
				{
					Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredProperty: Could not find property for type {type} and name {name}");
				}
				return property;
			}
			catch (AmbiguousMatchException inner)
			{
				throw new AmbiguousMatchException($"Ambiguous match for property {type}::{name}", inner);
			}
		}

		public static MethodInfo DeclaredPropertyGetter(Type type, string name)
		{
			return DeclaredProperty(type, name)?.GetGetMethod(nonPublic: true);
		}

		public static MethodInfo DeclaredPropertySetter(Type type, string name)
		{
			return DeclaredProperty(type, name)?.GetSetMethod(nonPublic: true);
		}

		public static PropertyInfo Property(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			PropertyInfo? propertyInfo = FindIncludingBaseTypes(type, (Type t) => t.GetProperty(name, all));
			if ((object)propertyInfo == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Property: Could not find property for type {type} and name {name}");
			}
			return propertyInfo;
		}

		public static MethodInfo PropertyGetter(Type type, string name)
		{
			return Property(type, name)?.GetGetMethod(nonPublic: true);
		}

		public static MethodInfo PropertySetter(Type type, string name)
		{
			return Property(type, name)?.GetSetMethod(nonPublic: true);
		}

		public static MethodInfo DeclaredMethod(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			ParameterModifier[] modifiers = new ParameterModifier[0];
			try
			{
				MethodInfo methodInfo = ((parameters != null) ? type.GetMethod(name, allDeclared, null, parameters, modifiers) : type.GetMethod(name, allDeclared));
				if ((object)methodInfo == null)
				{
					Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredMethod: Could not find method for type {type} and name {name} and parameters {parameters?.Description()}");
					return null;
				}
				if (generics != null)
				{
					methodInfo = methodInfo.MakeGenericMethod(generics);
				}
				return methodInfo;
			}
			catch (AmbiguousMatchException inner)
			{
				string text = "";
				if (generics != null)
				{
					text = "<" + string.Join(", ", generics.Select((Type g) => g.FullName).ToArray()) + ">";
				}
				string text2 = "";
				if (parameters != null)
				{
					text2 = string.Join(", ", parameters.Select((Type p) => p.FullName).ToArray());
				}
				throw new AmbiguousMatchException($"Ambiguous match for {type}::{name}{text}(${text2})", inner);
			}
		}

		public static MethodInfo Method(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			try
			{
				ParameterModifier[] modifiers = new ParameterModifier[0];
				MethodInfo methodInfo;
				if (parameters == null)
				{
					try
					{
						methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all));
					}
					catch (AmbiguousMatchException inner)
					{
						methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all, null, new Type[0], modifiers));
						if ((object)methodInfo == null)
						{
							throw new AmbiguousMatchException($"Ambiguous match for {type}:{name}", inner);
						}
					}
				}
				else
				{
					methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all, null, parameters, modifiers));
				}
				if ((object)methodInfo == null)
				{
					Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Method: Could not find method for type {type} and name {name} and parameters {parameters?.Description()}");
					return null;
				}
				if (generics != null)
				{
					methodInfo = methodInfo.MakeGenericMethod(generics);
				}
				return methodInfo;
			}
			catch (AmbiguousMatchException inner2)
			{
				string text = "";
				if (generics != null)
				{
					text = "<" + string.Join(", ", generics.Select((Type g) => g.FullName).ToArray()) + ">";
				}
				string text2 = "";
				if (parameters != null)
				{
					text2 = string.Join(", ", parameters.Select((Type p) => p.FullName).ToArray());
				}
				throw new AmbiguousMatchException($"Ambiguous match for {type}::{name}{text}(${text2})", inner2);
			}
		}

		public static MethodInfo Method(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
		{
			if (typeColonMethodname == null)
			{
				throw new ArgumentNullException("typeColonMethodname");
			}
			string[] array = typeColonMethodname.Split(new char[1] { ':' });
			if (array.Length != 2)
			{
				throw new ArgumentException("Method must be specified as 'Namespace.Type1.Type2:MethodName", "typeColonMethodname");
			}
			return Method(TypeByName(array[0]), array[1], parameters, generics);
		}

		public static List<string> GetMethodNames(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from m in GetDeclaredMethods(type)
				select m.Name).ToList();
		}

		public static List<string> GetMethodNames(object instance)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			return GetMethodNames(instance.GetType());
		}

		public static List<string> GetFieldNames(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from f in GetDeclaredFields(type)
				select f.Name).ToList();
		}

		public static List<string> GetFieldNames(object instance)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			return GetFieldNames(instance.GetType());
		}

		public static List<string> GetPropertyNames(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from f in GetDeclaredProperties(type)
				select f.Name).ToList();
		}

		public static List<string> GetPropertyNames(object instance)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			return GetPropertyNames(instance.GetType());
		}

		public static Type GetUnderlyingType(this MemberInfo member)
		{
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			return member.MemberType switch
			{
				MemberTypes.Event => ((EventInfo)member).EventHandlerType, 
				MemberTypes.Field => ((FieldInfo)member).FieldType, 
				MemberTypes.Method => ((MethodInfo)member).ReturnType, 
				MemberTypes.Property => ((PropertyInfo)member).PropertyType, 
				_ => throw new ArgumentException("Member must be of type EventInfo, FieldInfo, MethodInfo, or PropertyInfo"), 
			};
		}

		public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			return type.GetConstructor(allDeclared, null, parameters, new ParameterModifier[0]);
		}

		public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters, bool searchForStatic)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			BindingFlags bindingFlags = (searchForStatic ? BindingFlags.Instance : BindingFlags.Static);
			return type.GetConstructor(allDeclared & ~bindingFlags, null, parameters, new ParameterModifier[0]);
		}

		public static ConstructorInfo Constructor(Type type, Type[] parameters = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			return FindIncludingBaseTypes(type, (Type t) => t.GetConstructor(all, null, parameters, new ParameterModifier[0]));
		}

		public static ConstructorInfo Constructor(Type type, Type[] parameters, bool searchForStatic)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			BindingFlags exclude = (searchForStatic ? BindingFlags.Instance : BindingFlags.Static);
			return FindIncludingBaseTypes(type, (Type t) => t.GetConstructor(all & ~exclude, null, parameters, new ParameterModifier[0]));
		}

		public static List<ConstructorInfo> GetDeclaredConstructors(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from method in type.GetConstructors(allDeclared)
				where (object)method.DeclaringType == type
				select method).ToList();
		}

		public static List<ConstructorInfo> GetDeclaredConstructors(Type type, bool? searchForStatic)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			BindingFlags bindingFlags = BindingFlags.Default;
			if (searchForStatic.HasValue)
			{
				bindingFlags = (searchForStatic.Value ? BindingFlags.Instance : BindingFlags.Static);
			}
			return (from method in type.GetConstructors(allDeclared & ~bindingFlags)
				where (object)method.DeclaringType == type
				select method).ToList();
		}

		public static List<MethodInfo> GetDeclaredMethods(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return type.GetMethods(allDeclared).ToList();
		}

		public static List<PropertyInfo> GetDeclaredProperties(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return type.GetProperties(allDeclared).ToList();
		}

		public static List<FieldInfo> GetDeclaredFields(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return type.GetFields(allDeclared).ToList();
		}

		public static Type GetReturnedType(MethodBase methodOrConstructor)
		{
			if ((object)methodOrConstructor == null)
			{
				throw new ArgumentNullException("methodOrConstructor");
			}
			if (methodOrConstructor is ConstructorInfo)
			{
				return typeof(void);
			}
			return ((MethodInfo)methodOrConstructor).ReturnType;
		}

		public static Type Inner(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			return FindIncludingBaseTypes(type, (Type t) => t.GetNestedType(name, all));
		}

		public static Type FirstInner(Type type, Func<Type, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetNestedTypes(all).FirstOrDefault(predicate);
		}

		public static MethodInfo FirstMethod(Type type, Func<MethodInfo, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetMethods(allDeclared).FirstOrDefault(predicate);
		}

		public static ConstructorInfo FirstConstructor(Type type, Func<ConstructorInfo, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetConstructors(allDeclared).FirstOrDefault(predicate);
		}

		public static PropertyInfo FirstProperty(Type type, Func<PropertyInfo, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetProperties(allDeclared).FirstOrDefault(predicate);
		}

		public static Type[] GetTypes(object[] parameters)
		{
			if (parameters == null)
			{
				return new Type[0];
			}
			return parameters.Select((object p) => (p != null) ? p.GetType() : typeof(object)).ToArray();
		}

		public static object[] ActualParameters(MethodBase method, object[] inputs)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			if (inputs == null)
			{
				throw new ArgumentNullException("inputs");
			}
			List<Type> inputTypes = inputs.Select((object obj) => obj?.GetType()).ToList();
			return (from p in method.GetParameters()
				select p.ParameterType).Select(delegate(Type pType)
			{
				int num = inputTypes.FindIndex((Type inType) => inputTypes != null && pType.IsAssignableFrom(inType));
				return (num >= 0) ? inputs[num] : GetDefaultValue(pType);
			}).ToArray();
		}

		public static FieldRef<T, U> FieldRefAccess<T, U>(string fieldName)
		{
			return FieldRefAccess<T, U>(typeof(T).GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic));
		}

		public static FieldRef<T, U> FieldRefAccess<T, U>(FieldInfo fieldInfo)
		{
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			if ((object)fieldInfo == null)
			{
				throw new ArgumentNullException("fieldInfo");
			}
			if (!typeof(U).IsAssignableFrom(fieldInfo.FieldType))
			{
				throw new ArgumentException("FieldInfo type does not match FieldRefAccess return type.");
			}
			if ((object)typeof(T) != typeof(object) && ((object)fieldInfo.DeclaringType == null || !fieldInfo.DeclaringType.IsAssignableFrom(typeof(T))))
			{
				throw new MissingFieldException(typeof(T).Name, fieldInfo.Name);
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition("__refget_" + typeof(T).Name + "_fi_" + fieldInfo.Name, typeof(U).MakeByRefType(), new Type[1] { typeof(T) });
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldflda, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return Extensions.CreateDelegate<FieldRef<T, U>>((MethodBase)val.Generate());
		}

		public static ref U FieldRefAccess<T, U>(T instance, string fieldName)
		{
			return ref FieldRefAccess<T, U>(fieldName)(instance);
		}

		public static FieldRef<object, F> FieldRefAccess<F>(Type type, string fieldName)
		{
			return FieldRefAccess<object, F>(Field(type, fieldName));
		}

		public static ref F StaticFieldRefAccess<T, F>(string fieldName)
		{
			return ref StaticFieldRefAccess<F>(typeof(T), fieldName);
		}

		public static ref F StaticFieldRefAccess<T, F>(FieldInfo fieldInfo)
		{
			return ref StaticFieldRefAccess<F>(fieldInfo)();
		}

		public static FieldRef<F> StaticFieldRefAccess<F>(FieldInfo fieldInfo)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if ((object)fieldInfo == null)
			{
				throw new ArgumentNullException("fieldInfo");
			}
			Type declaringType = fieldInfo.DeclaringType;
			DynamicMethodDefinition val = new DynamicMethodDefinition("__refget_" + declaringType.Name + "_static_fi_" + fieldInfo.Name, typeof(F).MakeByRefType(), new Type[0]);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldsflda, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return Extensions.CreateDelegate<FieldRef<F>>((MethodBase)val.Generate());
		}

		public static ref F StaticFieldRefAccess<F>(Type type, string fieldName)
		{
			return ref StaticFieldRefAccess<F>(type.GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic))();
		}

		public static MethodBase GetOutsideCaller()
		{
			StackFrame[] frames = new StackTrace(fNeedFileInfo: true).GetFrames();
			for (int i = 0; i < frames.Length; i++)
			{
				Met

BepInEx/core/BepInEx.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.ConsoleUtil;
using BepInEx.Logging;
using BepInEx.Unix;
using HarmonyLib;
using HarmonyLib.Tools;
using Microsoft.Win32.SafeHandles;
using Mono.Cecil;
using MonoMod.Utils;
using UnityEngine;
using UnityInjector.ConsoleUtil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BepInEx")]
[assembly: AssemblyDescription("Unity plugin injection framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BepInEx")]
[assembly: AssemblyCopyright("Copyright © Bepis 2018")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4ffba620-f5ed-47f9-b90c-dad1316fd9b9")]
[assembly: InternalsVisibleTo("BepInEx.Preloader")]
[assembly: InternalsVisibleTo("BepInExTests")]
[assembly: AssemblyFileVersion("5.4.22.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.4.22.0")]
[module: UnverifiableCode]
namespace UnityEngine
{
	internal sealed class UnityLogWriter
	{
		[MethodImpl(MethodImplOptions.InternalCall)]
		public static extern void WriteStringToUnityLogImpl(string s);

		[MethodImpl(MethodImplOptions.InternalCall)]
		public static extern void WriteStringToUnityLog(string s);
	}
}
namespace UnityInjector.ConsoleUtil
{
	internal class ConsoleEncoding : Encoding
	{
		private byte[] _byteBuffer = new byte[256];

		private char[] _charBuffer = new char[256];

		private byte[] _zeroByte = new byte[0];

		private char[] _zeroChar = new char[0];

		private readonly uint _codePage;

		public override int CodePage => (int)_codePage;

		public static Encoding OutputEncoding => new ConsoleEncoding(ConsoleCodePage);

		public static uint ConsoleCodePage
		{
			get
			{
				return GetConsoleOutputCP();
			}
			set
			{
				SetConsoleOutputCP(value);
			}
		}

		private void ExpandByteBuffer(int count)
		{
			if (_byteBuffer.Length < count)
			{
				_byteBuffer = new byte[count];
			}
		}

		private void ExpandCharBuffer(int count)
		{
			if (_charBuffer.Length < count)
			{
				_charBuffer = new char[count];
			}
		}

		private void ReadByteBuffer(byte[] bytes, int index, int count)
		{
			for (int i = 0; i < count; i++)
			{
				bytes[index + i] = _byteBuffer[i];
			}
		}

		private void ReadCharBuffer(char[] chars, int index, int count)
		{
			for (int i = 0; i < count; i++)
			{
				chars[index + i] = _charBuffer[i];
			}
		}

		private void WriteByteBuffer(byte[] bytes, int index, int count)
		{
			ExpandByteBuffer(count);
			for (int i = 0; i < count; i++)
			{
				_byteBuffer[i] = bytes[index + i];
			}
		}

		private void WriteCharBuffer(char[] chars, int index, int count)
		{
			ExpandCharBuffer(count);
			for (int i = 0; i < count; i++)
			{
				_charBuffer[i] = chars[index + i];
			}
		}

		public static uint GetActiveCodePage()
		{
			return GetACP();
		}

		private ConsoleEncoding(uint codePage)
		{
			_codePage = codePage;
		}

		public static ConsoleEncoding GetEncoding(uint codePage)
		{
			return new ConsoleEncoding(codePage);
		}

		public override int GetByteCount(char[] chars, int index, int count)
		{
			WriteCharBuffer(chars, index, count);
			return WideCharToMultiByte(_codePage, 0u, _charBuffer, count, _zeroByte, 0, IntPtr.Zero, IntPtr.Zero);
		}

		public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
		{
			int byteCount = GetByteCount(chars, charIndex, charCount);
			WriteCharBuffer(chars, charIndex, charCount);
			ExpandByteBuffer(byteCount);
			int result = WideCharToMultiByte(_codePage, 0u, chars, charCount, _byteBuffer, byteCount, IntPtr.Zero, IntPtr.Zero);
			ReadByteBuffer(bytes, byteIndex, byteCount);
			return result;
		}

		public override int GetCharCount(byte[] bytes, int index, int count)
		{
			WriteByteBuffer(bytes, index, count);
			return MultiByteToWideChar(_codePage, 0u, bytes, count, _zeroChar, 0);
		}

		public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
		{
			int charCount = GetCharCount(bytes, byteIndex, byteCount);
			WriteByteBuffer(bytes, byteIndex, byteCount);
			ExpandCharBuffer(charCount);
			int result = MultiByteToWideChar(_codePage, 0u, bytes, byteCount, _charBuffer, charCount);
			ReadCharBuffer(chars, charIndex, charCount);
			return result;
		}

		public override int GetMaxByteCount(int charCount)
		{
			return charCount * 2;
		}

		public override int GetMaxCharCount(int byteCount)
		{
			return byteCount;
		}

		[DllImport("kernel32.dll")]
		private static extern uint GetConsoleOutputCP();

		[DllImport("kernel32.dll")]
		private static extern uint GetACP();

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern int MultiByteToWideChar(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, [Out][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar);

		[DllImport("kernel32.dll")]
		private static extern IntPtr SetConsoleOutputCP(uint codepage);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern int WideCharToMultiByte(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar);
	}
	internal class ConsoleWindow
	{
		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private delegate bool SetForegroundWindowDelegate(IntPtr hWnd);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate IntPtr GetForegroundWindowDelegate();

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate IntPtr GetSystemMenuDelegate(IntPtr hwnd, bool bRevert);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate bool DeleteMenuDelegate(IntPtr hMenu, uint uPosition, uint uFlags);

		private const uint SC_CLOSE = 61536u;

		private const uint MF_BYCOMMAND = 0u;

		private const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 2048u;

		public static IntPtr ConsoleOutHandle;

		public static IntPtr OriginalStdoutHandle;

		private static bool methodsInited;

		private static SetForegroundWindowDelegate setForeground;

		private static GetForegroundWindowDelegate getForeground;

		private static GetSystemMenuDelegate getSystemMenu;

		private static DeleteMenuDelegate deleteMenu;

		public static bool IsAttached { get; private set; }

		public static string Title
		{
			set
			{
				if (IsAttached)
				{
					if (value == null)
					{
						throw new ArgumentNullException("value");
					}
					if (value.Length > 24500)
					{
						throw new InvalidOperationException("Console title too long");
					}
					if (!SetConsoleTitle(value))
					{
						throw new InvalidOperationException("Console title invalid");
					}
				}
			}
		}

		public static void Attach()
		{
			if (!IsAttached)
			{
				Initialize();
				if (OriginalStdoutHandle == IntPtr.Zero)
				{
					OriginalStdoutHandle = GetStdHandle(-11);
				}
				IntPtr hWnd = getForeground();
				GetConsoleWindow();
				if (GetConsoleWindow() == IntPtr.Zero && !AllocConsole())
				{
					throw new Exception("AllocConsole() failed");
				}
				setForeground(hWnd);
				ConsoleOutHandle = CreateFile("CONOUT$", 3221225472u, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
				Kon.conOut = ConsoleOutHandle;
				if (!SetStdHandle(-11, ConsoleOutHandle))
				{
					throw new Exception("SetStdHandle() failed");
				}
				if (OriginalStdoutHandle != IntPtr.Zero && ConsoleManager.ConfigConsoleOutRedirectType.Value == ConsoleManager.ConsoleOutRedirectType.ConsoleOut)
				{
					CloseHandle(OriginalStdoutHandle);
				}
				IsAttached = true;
			}
		}

		public static void PreventClose()
		{
			if (IsAttached)
			{
				Initialize();
				IntPtr consoleWindow = GetConsoleWindow();
				IntPtr intPtr = getSystemMenu(consoleWindow, bRevert: false);
				if (intPtr != IntPtr.Zero)
				{
					deleteMenu(intPtr, 61536u, 0u);
				}
			}
		}

		public static void Detach()
		{
			if (IsAttached)
			{
				if (!CloseHandle(ConsoleOutHandle))
				{
					throw new Exception("CloseHandle() failed");
				}
				ConsoleOutHandle = IntPtr.Zero;
				if (!FreeConsole())
				{
					throw new Exception("FreeConsole() failed");
				}
				if (!SetStdHandle(-11, OriginalStdoutHandle))
				{
					throw new Exception("SetStdHandle() failed");
				}
				IsAttached = false;
			}
		}

		private static void Initialize()
		{
			if (!methodsInited)
			{
				methodsInited = true;
				IntPtr hModule = LoadLibraryEx("user32.dll", IntPtr.Zero, 2048u);
				setForeground = DynDll.AsDelegate<SetForegroundWindowDelegate>(GetProcAddress(hModule, "SetForegroundWindow"));
				getForeground = DynDll.AsDelegate<GetForegroundWindowDelegate>(GetProcAddress(hModule, "GetForegroundWindow"));
				getSystemMenu = DynDll.AsDelegate<GetSystemMenuDelegate>(GetProcAddress(hModule, "GetSystemMenu"));
				deleteMenu = DynDll.AsDelegate<DeleteMenuDelegate>(GetProcAddress(hModule, "DeleteMenu"));
			}
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool AllocConsole();

		[DllImport("kernel32.dll")]
		private static extern IntPtr GetConsoleWindow();

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		private static extern bool CloseHandle(IntPtr handle);

		[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		private static extern IntPtr CreateFile(string fileName, uint desiredAccess, int shareMode, IntPtr securityAttributes, int creationDisposition, int flagsAndAttributes, IntPtr templateFile);

		[DllImport("kernel32.dll")]
		private static extern bool FreeConsole();

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr GetStdHandle(int nStdHandle);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput);

		[DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Auto, SetLastError = true)]
		private static extern bool SetConsoleTitle(string title);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr LoadLibraryEx(string lpLibFileName, IntPtr hFile, uint dwFlags);
	}
	internal static class SafeConsole
	{
		private delegate ConsoleColor GetColorDelegate();

		private delegate void SetColorDelegate(ConsoleColor value);

		private delegate string GetStringDelegate();

		private delegate void SetStringDelegate(string value);

		private static GetColorDelegate _getBackgroundColor;

		private static SetColorDelegate _setBackgroundColor;

		private static GetColorDelegate _getForegroundColor;

		private static SetColorDelegate _setForegroundColor;

		private static GetStringDelegate _getTitle;

		private static SetStringDelegate _setTitle;

		public static bool BackgroundColorExists { get; private set; }

		public static ConsoleColor BackgroundColor
		{
			get
			{
				return _getBackgroundColor();
			}
			set
			{
				_setBackgroundColor(value);
			}
		}

		public static bool ForegroundColorExists { get; private set; }

		public static ConsoleColor ForegroundColor
		{
			get
			{
				return _getForegroundColor();
			}
			set
			{
				_setForegroundColor(value);
			}
		}

		public static bool TitleExists { get; private set; }

		public static string Title
		{
			get
			{
				return _getTitle();
			}
			set
			{
				_setTitle(value);
			}
		}

		static SafeConsole()
		{
			InitColors(typeof(Console));
		}

		private static void InitColors(Type tConsole)
		{
			MethodInfo method = tConsole.GetMethod("get_ForegroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method2 = tConsole.GetMethod("set_ForegroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method3 = tConsole.GetMethod("get_BackgroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method4 = tConsole.GetMethod("set_BackgroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method5 = tConsole.GetMethod("get_Title", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method6 = tConsole.GetMethod("set_Title", BindingFlags.Static | BindingFlags.Public);
			_setForegroundColor = (((object)method2 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method2)) : ((SetColorDelegate)delegate
			{
			}));
			_setBackgroundColor = (((object)method4 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method4)) : ((SetColorDelegate)delegate
			{
			}));
			_getForegroundColor = (((object)method != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method)) : ((GetColorDelegate)(() => ConsoleColor.Gray)));
			_getBackgroundColor = (((object)method3 != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method3)) : ((GetColorDelegate)(() => ConsoleColor.Black)));
			_getTitle = (((object)method5 != null) ? ((GetStringDelegate)Delegate.CreateDelegate(typeof(GetStringDelegate), method5)) : ((GetStringDelegate)(() => string.Empty)));
			_setTitle = (((object)method6 != null) ? ((SetStringDelegate)Delegate.CreateDelegate(typeof(SetStringDelegate), method6)) : ((SetStringDelegate)delegate
			{
			}));
			BackgroundColorExists = _setBackgroundColor != null && _getBackgroundColor != null;
			ForegroundColorExists = _setForegroundColor != null && _getForegroundColor != null;
			TitleExists = _setTitle != null && _getTitle != null;
		}
	}
}
namespace BepInEx
{
	public static class UnityInput
	{
		private static IInputSystem _current;

		public static IInputSystem Current
		{
			get
			{
				if (_current != null)
				{
					return _current;
				}
				try
				{
					try
					{
						Input.GetKeyDown((KeyCode)97);
						_current = new LegacyInputSystem();
						Logger.LogDebug("[UnityInput] Using LegacyInputSystem");
					}
					catch (InvalidOperationException)
					{
						_current = new NewInputSystem();
						Logger.LogDebug("[UnityInput] Using NewInputSystem");
					}
				}
				catch (Exception arg)
				{
					Logger.LogWarning($"[UnityInput] Failed to detect available input systems - {arg}");
					_current = new NullInputSystem();
				}
				return _current;
			}
		}

		public static bool LegacyInputSystemAvailable => Current is LegacyInputSystem;
	}
	public interface IInputSystem
	{
		Vector3 mousePosition { get; }

		Vector2 mouseScrollDelta { get; }

		bool mousePresent { get; }

		bool anyKey { get; }

		bool anyKeyDown { get; }

		IEnumerable<KeyCode> SupportedKeyCodes { get; }

		bool GetKey(string name);

		bool GetKey(KeyCode key);

		bool GetKeyDown(string name);

		bool GetKeyDown(KeyCode key);

		bool GetKeyUp(string name);

		bool GetKeyUp(KeyCode key);

		bool GetMouseButton(int button);

		bool GetMouseButtonDown(int button);

		bool GetMouseButtonUp(int button);

		void ResetInputAxes();
	}
	internal class NewInputSystem : IInputSystem
	{
		private delegate bool GetButtonDelegate(KeyCode key);

		private delegate Vector2 GetMouseVectorDelegate();

		private delegate bool GetMouseStateDelegate();

		private static bool initialized;

		private static readonly Dictionary<KeyCode, int> keyCodeToIndex = new Dictionary<KeyCode, int>();

		private static readonly Dictionary<string, string> keyToKeyCodeNameRemap = new Dictionary<string, string>
		{
			["LeftCtrl"] = "LeftControl",
			["RightCtrl"] = "RightControl",
			["LeftMeta"] = "LeftApple",
			["RightMeta"] = "RightApple",
			["ContextMenu"] = "Menu",
			["PrintScreen"] = "Print",
			["Enter"] = "Return"
		};

		private static GetButtonDelegate _getKey;

		private static GetButtonDelegate _getKeyDown;

		private static GetButtonDelegate _getKeyUp;

		private static GetButtonDelegate _getMouseButton;

		private static GetButtonDelegate _getMouseButtonDown;

		private static GetButtonDelegate _getMouseButtonUp;

		private static GetMouseVectorDelegate _getMousePosition;

		private static GetMouseVectorDelegate _getMouseScrollDelta;

		private static GetMouseStateDelegate _getMousePresent;

		private static GetMouseStateDelegate _getKeyboardAnyKeyIsPressed;

		private static GetMouseStateDelegate _getKeyboardAnyKeyWasPressedThisFrame;

		public Vector3 mousePosition => Vector2.op_Implicit(_getMousePosition());

		public Vector2 mouseScrollDelta => _getMouseScrollDelta();

		public bool mousePresent => _getMousePresent();

		public bool anyKey
		{
			get
			{
				if (_getKeyboardAnyKeyIsPressed())
				{
					return true;
				}
				if (!GetMouseButton(0) && !GetMouseButton(1) && !GetMouseButton(2) && !GetMouseButton(3))
				{
					return GetMouseButton(4);
				}
				return true;
			}
		}

		public bool anyKeyDown
		{
			get
			{
				if (_getKeyboardAnyKeyWasPressedThisFrame())
				{
					return true;
				}
				if (!GetMouseButtonDown(0) && !GetMouseButtonDown(1) && !GetMouseButtonDown(2) && !GetMouseButtonDown(3))
				{
					return GetMouseButtonDown(4);
				}
				return true;
			}
		}

		public IEnumerable<KeyCode> SupportedKeyCodes => keyCodeToIndex.Keys.ToArray();

		public NewInputSystem()
		{
			Init();
		}

		private static void Init()
		{
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			if (initialized)
			{
				return;
			}
			Assembly assembly = Assembly.Load("Unity.InputSystem");
			Type type = assembly.GetType("UnityEngine.InputSystem.Key");
			foreach (object value3 in Enum.GetValues(type))
			{
				string text = value3.ToString();
				int value = (int)value3;
				string value2;
				if (text.StartsWith("Numpad"))
				{
					text = text.Replace("Numpad", "Keypad");
				}
				else if (text.StartsWith("Digit"))
				{
					text = text.Replace("Digit", "Alpha");
				}
				else if (keyToKeyCodeNameRemap.TryGetValue(text, out value2))
				{
					text = value2;
				}
				if (TryEnumParse<KeyCode>(text, out var val))
				{
					keyCodeToIndex[val] = value;
				}
				else
				{
					Logger.LogDebug("[UnityInput] Unknown key name: " + text + ", skipping remapping");
				}
			}
			FieldInfo keyCodeToIndexField = AccessTools.Field(typeof(NewInputSystem), "keyCodeToIndex");
			MethodInfo tryGetValueMethod = AccessTools.Method(typeof(Dictionary<KeyCode, int>), "TryGetValue", (Type[])null, (Type[])null);
			Type type2 = assembly.GetType("UnityEngine.InputSystem.Keyboard");
			MethodInfo currentProperty = AccessTools.PropertyGetter(type2, "current");
			MethodInfo indexer = AccessTools.Method(type2, "get_Item", new Type[1] { type }, (Type[])null);
			Type buttonControlType = assembly.GetType("UnityEngine.InputSystem.Controls.ButtonControl");
			_getKey = GenerateKeyGetter("InputSystemGetKey", "isPressed");
			_getKeyDown = GenerateKeyGetter("InputSystemGetKeyDown", "wasPressedThisFrame");
			_getKeyUp = GenerateKeyGetter("InputSystemGetKeyUp", "wasReleasedThisFrame");
			Type mouseType = assembly.GetType("UnityEngine.InputSystem.Mouse");
			MethodInfo mouseCurrentProperty = AccessTools.PropertyGetter(mouseType, "current");
			string[] source = new string[5] { "leftButton", "rightButton", "middleButton", "backButton", "forwardButton" };
			MethodInfo[] buttonPropertyGetters = source.Select((string p) => AccessTools.PropertyGetter(mouseType, p)).ToArray();
			_getMouseButton = GenerateMouseGetter("InputSystemGetMouseButton", "isPressed");
			_getMouseButtonDown = GenerateMouseGetter("InputSystemGetMouseButtonDown", "wasPressedThisFrame");
			_getMouseButtonUp = GenerateMouseGetter("InputSystemGetMouseButtonUp", "wasReleasedThisFrame");
			_getMousePosition = GetPositionDelegate("InputSystemGetMousePosition", "position");
			_getMouseScrollDelta = GetPositionDelegate("InputSystemGetMouseScrollDelta", "scroll");
			DynamicMethodDefinition val2 = new DynamicMethodDefinition("InputSystemGetMouseEnabled", typeof(bool), Type.EmptyTypes);
			ILGenerator iLGenerator = val2.GetILGenerator();
			iLGenerator.Emit(OpCodes.Call, mouseCurrentProperty);
			iLGenerator.Emit(OpCodes.Callvirt, AccessTools.PropertyGetter(mouseType, "enabled"));
			iLGenerator.Emit(OpCodes.Ret);
			_getMousePresent = Extensions.CreateDelegate<GetMouseStateDelegate>((MethodBase)val2.Generate());
			MethodInfo anyKeyProperty = AccessTools.PropertyGetter(type2, "anyKey");
			_getKeyboardAnyKeyIsPressed = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyIsPressed", "isPressed");
			_getKeyboardAnyKeyWasPressedThisFrame = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyWasPressedThisFrame", "wasPressedThisFrame");
			initialized = true;
			GetButtonDelegate GenerateKeyGetter(string name, string property)
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				MethodInfo meth4 = AccessTools.PropertyGetter(buttonControlType, property);
				DynamicMethodDefinition val6 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) });
				ILGenerator iLGenerator4 = val6.GetILGenerator();
				LocalBuilder local = iLGenerator4.DeclareLocal(typeof(int));
				Label label2 = iLGenerator4.DefineLabel();
				iLGenerator4.Emit(OpCodes.Ldsfld, keyCodeToIndexField);
				iLGenerator4.Emit(OpCodes.Ldarg_0);
				iLGenerator4.Emit(OpCodes.Ldloca, local);
				iLGenerator4.Emit(OpCodes.Callvirt, tryGetValueMethod);
				iLGenerator4.Emit(OpCodes.Brfalse, label2);
				iLGenerator4.Emit(OpCodes.Call, currentProperty);
				iLGenerator4.Emit(OpCodes.Ldloc, local);
				iLGenerator4.Emit(OpCodes.Callvirt, indexer);
				iLGenerator4.Emit(OpCodes.Callvirt, meth4);
				iLGenerator4.Emit(OpCodes.Ret);
				iLGenerator4.MarkLabel(label2);
				iLGenerator4.Emit(OpCodes.Ldc_I4_0);
				iLGenerator4.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetButtonDelegate>((MethodBase)val6.Generate());
			}
			GetButtonDelegate GenerateMouseGetter(string name, string property)
			{
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Expected O, but got Unknown
				MethodInfo meth3 = AccessTools.PropertyGetter(buttonControlType, property);
				DynamicMethodDefinition val5 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) });
				ILGenerator il = val5.GetILGenerator();
				il.Emit(OpCodes.Ldarg_0);
				il.Emit(OpCodes.Ldc_I4, 323);
				il.Emit(OpCodes.Sub);
				Label[] array = buttonPropertyGetters.Select((MethodInfo _) => il.DefineLabel()).ToArray();
				Label label = il.DefineLabel();
				il.Emit(OpCodes.Switch, array);
				il.Emit(OpCodes.Br, label);
				for (int i = 0; i < array.Length; i++)
				{
					il.MarkLabel(array[i]);
					il.Emit(OpCodes.Call, mouseCurrentProperty);
					il.Emit(OpCodes.Callvirt, buttonPropertyGetters[i]);
					il.Emit(OpCodes.Callvirt, meth3);
					il.Emit(OpCodes.Ret);
				}
				il.MarkLabel(label);
				il.Emit(OpCodes.Ldc_I4_0);
				il.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetButtonDelegate>((MethodBase)val5.Generate());
			}
			GetMouseStateDelegate GetAnyKeyDelegate(string name, string property)
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				MethodInfo meth = AccessTools.PropertyGetter(buttonControlType, property);
				DynamicMethodDefinition val3 = new DynamicMethodDefinition(name, typeof(bool), Type.EmptyTypes);
				ILGenerator iLGenerator2 = val3.GetILGenerator();
				iLGenerator2.Emit(OpCodes.Call, currentProperty);
				iLGenerator2.Emit(OpCodes.Callvirt, anyKeyProperty);
				iLGenerator2.Emit(OpCodes.Callvirt, meth);
				iLGenerator2.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetMouseStateDelegate>((MethodBase)val3.Generate());
			}
			GetMouseVectorDelegate GetPositionDelegate(string name, string property)
			{
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				MethodInfo methodInfo = AccessTools.PropertyGetter(mouseType, property);
				MethodInfo meth2 = AccessTools.Method(methodInfo.ReturnType, "ReadValue", (Type[])null, (Type[])null);
				DynamicMethodDefinition val4 = new DynamicMethodDefinition(name, typeof(Vector2), Type.EmptyTypes);
				ILGenerator iLGenerator3 = val4.GetILGenerator();
				iLGenerator3.Emit(OpCodes.Call, mouseCurrentProperty);
				iLGenerator3.Emit(OpCodes.Callvirt, methodInfo);
				iLGenerator3.Emit(OpCodes.Callvirt, meth2);
				iLGenerator3.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetMouseVectorDelegate>((MethodBase)val4.Generate());
			}
		}

		public bool GetKey(string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return _getKey(GetKeyCode(name));
		}

		public bool GetKey(KeyCode key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return _getKey(key);
		}

		public bool GetKeyDown(string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyDown(GetKeyCode(name));
		}

		public bool GetKeyDown(KeyCode key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyDown(key);
		}

		public bool GetKeyUp(string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyUp(GetKeyCode(name));
		}

		public bool GetKeyUp(KeyCode key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyUp(key);
		}

		public bool GetMouseButton(int button)
		{
			return _getMouseButton((KeyCode)(323 + button));
		}

		public bool GetMouseButtonDown(int button)
		{
			return _getMouseButtonDown((KeyCode)(323 + button));
		}

		public bool GetMouseButtonUp(int button)
		{
			return _getMouseButtonUp((KeyCode)(323 + button));
		}

		public void ResetInputAxes()
		{
		}

		private static KeyCode GetKeyCode(string name)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			return (KeyCode)Enum.Parse(typeof(KeyCode), name, ignoreCase: true);
		}

		private static bool TryEnumParse<T>(string name, out T val)
		{
			try
			{
				val = (T)Enum.Parse(typeof(T), name, ignoreCase: true);
				return true;
			}
			catch (Exception)
			{
				val = default(T);
				return false;
			}
		}
	}
	internal class LegacyInputSystem : IInputSystem
	{
		public Vector3 mousePosition => Input.mousePosition;

		public Vector2 mouseScrollDelta => Input.mouseScrollDelta;

		public bool mousePresent => Input.mousePresent;

		public bool anyKey => Input.anyKey;

		public bool anyKeyDown => Input.anyKeyDown;

		public IEnumerable<KeyCode> SupportedKeyCodes { get; } = (KeyCode[])Enum.GetValues(typeof(KeyCode));


		public bool GetKey(string name)
		{
			return Input.GetKey(name);
		}

		public bool GetKey(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Input.GetKey(key);
		}

		public bool GetKeyDown(string name)
		{
			return Input.GetKeyDown(name);
		}

		public bool GetKeyDown(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Input.GetKeyDown(key);
		}

		public bool GetKeyUp(string name)
		{
			return Input.GetKeyUp(name);
		}

		public bool GetKeyUp(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Input.GetKeyUp(key);
		}

		public bool GetMouseButton(int button)
		{
			return Input.GetMouseButton(button);
		}

		public bool GetMouseButtonDown(int button)
		{
			return Input.GetMouseButtonDown(button);
		}

		public bool GetMouseButtonUp(int button)
		{
			return Input.GetMouseButtonUp(button);
		}

		public void ResetInputAxes()
		{
			Input.ResetInputAxes();
		}
	}
	internal class NullInputSystem : IInputSystem
	{
		private static readonly KeyCode[] NoKeys = (KeyCode[])(object)new KeyCode[0];

		public Vector3 mousePosition => Vector3.zero;

		public Vector2 mouseScrollDelta => Vector2.zero;

		public bool mousePresent => false;

		public bool anyKey => false;

		public bool anyKeyDown => false;

		public IEnumerable<KeyCode> SupportedKeyCodes => NoKeys;

		public bool GetKey(string name)
		{
			return false;
		}

		public bool GetKey(KeyCode key)
		{
			return false;
		}

		public bool GetKeyDown(string name)
		{
			return false;
		}

		public bool GetKeyDown(KeyCode key)
		{
			return false;
		}

		public bool GetKeyUp(string name)
		{
			return false;
		}

		public bool GetKeyUp(KeyCode key)
		{
			return false;
		}

		public bool GetMouseButton(int button)
		{
			return false;
		}

		public bool GetMouseButtonDown(int button)
		{
			return false;
		}

		public bool GetMouseButtonUp(int button)
		{
			return false;
		}

		public void ResetInputAxes()
		{
		}
	}
	internal static class ConsoleManager
	{
		public enum ConsoleOutRedirectType
		{
			[Description("Auto")]
			Auto,
			[Description("Console Out")]
			ConsoleOut,
			[Description("Standard Out")]
			StandardOut
		}

		private const uint SHIFT_JIS_CP = 932u;

		private static readonly bool? EnableConsoleArgOverride;

		private const string ENABLE_CONSOLE_ARG = "--enable-console";

		public static readonly ConfigEntry<bool> ConfigConsoleEnabled;

		public static readonly ConfigEntry<bool> ConfigPreventClose;

		public static readonly ConfigEntry<bool> ConfigConsoleShiftJis;

		public static readonly ConfigEntry<ConsoleOutRedirectType> ConfigConsoleOutRedirectType;

		internal static IConsoleDriver Driver { get; set; }

		public static bool ConsoleActive => Driver?.ConsoleActive ?? false;

		public static TextWriter StandardOutStream => Driver?.StandardOut;

		public static TextWriter ConsoleStream => Driver?.ConsoleOut;

		public static bool ConsoleEnabled => EnableConsoleArgOverride ?? ConfigConsoleEnabled.Value;

		static ConsoleManager()
		{
			ConfigConsoleEnabled = ConfigFile.CoreConfig.Bind("Logging.Console", "Enabled", defaultValue: false, "Enables showing a console for log output.");
			ConfigPreventClose = ConfigFile.CoreConfig.Bind("Logging.Console", "PreventClose", defaultValue: false, "If enabled, will prevent closing the console (either by deleting the close button or in other platform-specific way).");
			ConfigConsoleShiftJis = ConfigFile.CoreConfig.Bind("Logging.Console", "ShiftJisEncoding", defaultValue: false, "If true, console is set to the Shift-JIS encoding, otherwise UTF-8 encoding.");
			ConfigConsoleOutRedirectType = ConfigFile.CoreConfig.Bind("Logging.Console", "StandardOutType", ConsoleOutRedirectType.Auto, new StringBuilder().AppendLine("Hints console manager on what handle to assign as StandardOut. Possible values:").AppendLine("Auto - lets BepInEx decide how to redirect console output").AppendLine("ConsoleOut - prefer redirecting to console output; if possible, closes original standard output")
				.AppendLine("StandardOut - prefer redirecting to standard output; if possible, closes console out")
				.ToString());
			try
			{
				string[] commandLineArgs = Environment.GetCommandLineArgs();
				for (int i = 0; i < commandLineArgs.Length; i++)
				{
					if (commandLineArgs[i] == "--enable-console" && i + 1 < commandLineArgs.Length && bool.TryParse(commandLineArgs[i + 1], out var result))
					{
						EnableConsoleArgOverride = result;
					}
				}
			}
			catch (Exception)
			{
			}
		}

		public static void Initialize(bool alreadyActive)
		{
			if (PlatformHelper.Is((Platform)8))
			{
				Driver = new LinuxConsoleDriver();
			}
			else if (PlatformHelper.Is((Platform)37))
			{
				Driver = new WindowsConsoleDriver();
			}
			Driver.Initialize(alreadyActive);
		}

		private static void DriverCheck()
		{
			if (Driver == null)
			{
				throw new InvalidOperationException("Driver has not been initialized");
			}
		}

		public static void CreateConsole()
		{
			if (!ConsoleActive)
			{
				DriverCheck();
				uint codepage = (ConfigConsoleShiftJis.Value ? 932u : ((uint)Encoding.UTF8.CodePage));
				Driver.CreateConsole(codepage);
				if (ConfigPreventClose.Value)
				{
					Driver.PreventClose();
				}
			}
		}

		public static void DetachConsole()
		{
			if (ConsoleActive)
			{
				DriverCheck();
				Driver.DetachConsole();
			}
		}

		public static void SetConsoleTitle(string title)
		{
			DriverCheck();
			Driver.SetConsoleTitle(title);
		}

		public static void SetConsoleColor(ConsoleColor color)
		{
			DriverCheck();
			Driver.SetConsoleColor(color);
		}
	}
	internal interface IConsoleDriver
	{
		TextWriter StandardOut { get; }

		TextWriter ConsoleOut { get; }

		bool ConsoleActive { get; }

		bool ConsoleIsExternal { get; }

		void PreventClose();

		void Initialize(bool alreadyActive);

		void CreateConsole(uint codepage);

		void DetachConsole();

		void SetConsoleColor(ConsoleColor color);

		void SetConsoleTitle(string title);
	}
	internal class WindowsConsoleDriver : IConsoleDriver
	{
		private static readonly ConstructorInfo FileStreamCtor = new ConstructorInfo[2]
		{
			AccessTools.Constructor(typeof(FileStream), new Type[2]
			{
				typeof(SafeFileHandle),
				typeof(FileAccess)
			}, false),
			AccessTools.Constructor(typeof(FileStream), new Type[2]
			{
				typeof(IntPtr),
				typeof(FileAccess)
			}, false)
		}.FirstOrDefault((ConstructorInfo m) => (object)m != null);

		public TextWriter StandardOut { get; private set; }

		public TextWriter ConsoleOut { get; private set; }

		public bool ConsoleActive { get; private set; }

		public bool ConsoleIsExternal => true;

		public void PreventClose()
		{
			ConsoleWindow.PreventClose();
		}

		public void Initialize(bool alreadyActive)
		{
			ConsoleActive = alreadyActive;
			StandardOut = Console.Out;
		}

		private static FileStream OpenFileStream(IntPtr handle)
		{
			SafeFileHandle safeFileHandle = new SafeFileHandle(handle, ownsHandle: false);
			object[] args = AccessTools.ActualParameters((MethodBase)FileStreamCtor, new object[3]
			{
				safeFileHandle,
				safeFileHandle.DangerousGetHandle(),
				FileAccess.Write
			});
			return (FileStream)Activator.CreateInstance(typeof(FileStream), args);
		}

		public void CreateConsole(uint codepage)
		{
			ConsoleWindow.Attach();
			ConsoleEncoding.ConsoleCodePage = codepage;
			IntPtr outHandle = GetOutHandle();
			if (outHandle == IntPtr.Zero)
			{
				StandardOut = TextWriter.Null;
				ConsoleOut = TextWriter.Null;
				return;
			}
			FileStream stream = OpenFileStream(outHandle);
			StandardOut = new StreamWriter(stream, Utility.UTF8NoBom)
			{
				AutoFlush = true
			};
			FileStream stream2 = OpenFileStream(ConsoleWindow.ConsoleOutHandle);
			ConsoleOut = new StreamWriter(stream2, ConsoleEncoding.OutputEncoding)
			{
				AutoFlush = true
			};
			ConsoleActive = true;
		}

		private IntPtr GetOutHandle()
		{
			switch (ConsoleManager.ConfigConsoleOutRedirectType.Value)
			{
			case ConsoleManager.ConsoleOutRedirectType.ConsoleOut:
				return ConsoleWindow.ConsoleOutHandle;
			case ConsoleManager.ConsoleOutRedirectType.StandardOut:
				return ConsoleWindow.OriginalStdoutHandle;
			default:
				if (!(ConsoleWindow.OriginalStdoutHandle != IntPtr.Zero))
				{
					return ConsoleWindow.ConsoleOutHandle;
				}
				return ConsoleWindow.OriginalStdoutHandle;
			}
		}

		public void DetachConsole()
		{
			ConsoleWindow.Detach();
			ConsoleOut.Close();
			ConsoleOut = null;
			ConsoleActive = false;
		}

		public void SetConsoleColor(ConsoleColor color)
		{
			SafeConsole.ForegroundColor = color;
			Kon.ForegroundColor = color;
		}

		public void SetConsoleTitle(string title)
		{
			ConsoleWindow.Title = title;
		}
	}
	public class PluginInfo : ICacheable
	{
		public BepInPlugin Metadata { get; internal set; }

		public IEnumerable<BepInProcess> Processes { get; internal set; }

		public IEnumerable<BepInDependency> Dependencies { get; internal set; }

		public IEnumerable<BepInIncompatibility> Incompatibilities { get; internal set; }

		public string Location { get; internal set; }

		public BaseUnityPlugin Instance { get; internal set; }

		internal string TypeName { get; set; }

		internal Version TargettedBepInExVersion { get; set; }

		void ICacheable.Save(BinaryWriter bw)
		{
			bw.Write(TypeName);
			bw.Write(Metadata.GUID);
			bw.Write(Metadata.Name);
			bw.Write(Metadata.Version.ToString());
			List<BepInProcess> list = Processes.ToList();
			bw.Write(list.Count);
			foreach (BepInProcess item in list)
			{
				bw.Write(item.ProcessName);
			}
			List<BepInDependency> list2 = Dependencies.ToList();
			bw.Write(list2.Count);
			foreach (BepInDependency item2 in list2)
			{
				((ICacheable)item2).Save(bw);
			}
			List<BepInIncompatibility> list3 = Incompatibilities.ToList();
			bw.Write(list3.Count);
			foreach (BepInIncompatibility item3 in list3)
			{
				((ICacheable)item3).Save(bw);
			}
			bw.Write(TargettedBepInExVersion.ToString(4));
		}

		void ICacheable.Load(BinaryReader br)
		{
			TypeName = br.ReadString();
			Metadata = new BepInPlugin(br.ReadString(), br.ReadString(), br.ReadString());
			int num = br.ReadInt32();
			List<BepInProcess> list = new List<BepInProcess>(num);
			for (int i = 0; i < num; i++)
			{
				list.Add(new BepInProcess(br.ReadString()));
			}
			Processes = list;
			int num2 = br.ReadInt32();
			List<BepInDependency> list2 = new List<BepInDependency>(num2);
			for (int j = 0; j < num2; j++)
			{
				BepInDependency bepInDependency = new BepInDependency("");
				((ICacheable)bepInDependency).Load(br);
				list2.Add(bepInDependency);
			}
			Dependencies = list2;
			int num3 = br.ReadInt32();
			List<BepInIncompatibility> list3 = new List<BepInIncompatibility>(num3);
			for (int k = 0; k < num3; k++)
			{
				BepInIncompatibility bepInIncompatibility = new BepInIncompatibility("");
				((ICacheable)bepInIncompatibility).Load(br);
				list3.Add(bepInIncompatibility);
			}
			Incompatibilities = list3;
			TargettedBepInExVersion = new Version(br.ReadString());
		}

		public override string ToString()
		{
			return $"{Metadata?.Name} {Metadata?.Version}";
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
	public class BepInPlugin : Attribute
	{
		public string GUID { get; protected set; }

		public string Name { get; protected set; }

		public Version Version { get; protected set; }

		public BepInPlugin(string GUID, string Name, string Version)
		{
			this.GUID = GUID;
			this.Name = Name;
			try
			{
				this.Version = new Version(Version);
			}
			catch
			{
				this.Version = null;
			}
		}

		internal static BepInPlugin FromCecilType(TypeDefinition td)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			CustomAttribute val = MetadataHelper.GetCustomAttributes<BepInPlugin>(td, inherit: false).FirstOrDefault();
			if (val == null)
			{
				return null;
			}
			CustomAttributeArgument val2 = val.ConstructorArguments[0];
			string gUID = (string)((CustomAttributeArgument)(ref val2)).Value;
			val2 = val.ConstructorArguments[1];
			string name = (string)((CustomAttributeArgument)(ref val2)).Value;
			val2 = val.ConstructorArguments[2];
			return new BepInPlugin(gUID, name, (string)((CustomAttributeArgument)(ref val2)).Value);
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class BepInDependency : Attribute, ICacheable
	{
		[Flags]
		public enum DependencyFlags
		{
			HardDependency = 1,
			SoftDependency = 2
		}

		public string DependencyGUID { get; protected set; }

		public DependencyFlags Flags { get; protected set; }

		public Version MinimumVersion { get; protected set; }

		public BepInDependency(string DependencyGUID, DependencyFlags Flags = DependencyFlags.HardDependency)
		{
			this.DependencyGUID = DependencyGUID;
			this.Flags = Flags;
			MinimumVersion = new Version();
		}

		public BepInDependency(string DependencyGUID, string MinimumDependencyVersion)
			: this(DependencyGUID)
		{
			MinimumVersion = new Version(MinimumDependencyVersion);
		}

		internal static IEnumerable<BepInDependency> FromCecilType(TypeDefinition td)
		{
			return MetadataHelper.GetCustomAttributes<BepInDependency>(td, inherit: true).Select(delegate(CustomAttribute customAttribute)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				string dependencyGUID = (string)((CustomAttributeArgument)(ref val)).Value;
				val = customAttribute.ConstructorArguments[1];
				object value = ((CustomAttributeArgument)(ref val)).Value;
				return (value is string minimumDependencyVersion) ? new BepInDependency(dependencyGUID, minimumDependencyVersion) : new BepInDependency(dependencyGUID, (DependencyFlags)value);
			}).ToList();
		}

		void ICacheable.Save(BinaryWriter bw)
		{
			bw.Write(DependencyGUID);
			bw.Write((int)Flags);
			bw.Write(MinimumVersion.ToString());
		}

		void ICacheable.Load(BinaryReader br)
		{
			DependencyGUID = br.ReadString();
			Flags = (DependencyFlags)br.ReadInt32();
			MinimumVersion = new Version(br.ReadString());
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class BepInIncompatibility : Attribute, ICacheable
	{
		public string IncompatibilityGUID { get; protected set; }

		public BepInIncompatibility(string IncompatibilityGUID)
		{
			this.IncompatibilityGUID = IncompatibilityGUID;
		}

		internal static IEnumerable<BepInIncompatibility> FromCecilType(TypeDefinition td)
		{
			return MetadataHelper.GetCustomAttributes<BepInIncompatibility>(td, inherit: true).Select(delegate(CustomAttribute customAttribute)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				return new BepInIncompatibility((string)((CustomAttributeArgument)(ref val)).Value);
			}).ToList();
		}

		void ICacheable.Save(BinaryWriter bw)
		{
			bw.Write(IncompatibilityGUID);
		}

		void ICacheable.Load(BinaryReader br)
		{
			IncompatibilityGUID = br.ReadString();
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class BepInProcess : Attribute
	{
		public string ProcessName { get; protected set; }

		public BepInProcess(string ProcessName)
		{
			this.ProcessName = ProcessName;
		}

		internal static List<BepInProcess> FromCecilType(TypeDefinition td)
		{
			return MetadataHelper.GetCustomAttributes<BepInProcess>(td, inherit: true).Select(delegate(CustomAttribute customAttribute)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				return new BepInProcess((string)((CustomAttributeArgument)(ref val)).Value);
			}).ToList();
		}
	}
	public static class MetadataHelper
	{
		internal static IEnumerable<CustomAttribute> GetCustomAttributes<T>(TypeDefinition td, bool inherit) where T : Attribute
		{
			List<CustomAttribute> list = new List<CustomAttribute>();
			Type type = typeof(T);
			TypeDefinition val = td;
			do
			{
				list.AddRange(((IEnumerable<CustomAttribute>)val.CustomAttributes).Where((CustomAttribute ca) => ((MemberReference)ca.AttributeType).FullName == type.FullName));
				TypeReference baseType = val.BaseType;
				val = ((baseType != null) ? baseType.Resolve() : null);
			}
			while (inherit && ((val != null) ? ((MemberReference)val).FullName : null) != "System.Object");
			return list;
		}

		public static BepInPlugin GetMetadata(Type pluginType)
		{
			object[] customAttributes = pluginType.GetCustomAttributes(typeof(BepInPlugin), inherit: false);
			if (customAttributes.Length == 0)
			{
				return null;
			}
			return (BepInPlugin)customAttributes[0];
		}

		public static BepInPlugin GetMetadata(object plugin)
		{
			return GetMetadata(plugin.GetType());
		}

		public static T[] GetAttributes<T>(Type pluginType) where T : Attribute
		{
			return (T[])pluginType.GetCustomAttributes(typeof(T), inherit: true);
		}

		public static IEnumerable<T> GetAttributes<T>(object plugin) where T : Attribute
		{
			return GetAttributes<T>(plugin.GetType());
		}

		public static IEnumerable<BepInDependency> GetDependencies(Type plugin)
		{
			return plugin.GetCustomAttributes(typeof(BepInDependency), inherit: true).Cast<BepInDependency>();
		}
	}
	internal class BuildInfoAttribute : Attribute
	{
		public string Info { get; }

		public BuildInfoAttribute(string info)
		{
			Info = info;
		}
	}
	public abstract class BaseUnityPlugin : MonoBehaviour
	{
		public PluginInfo Info { get; }

		protected ManualLogSource Logger { get; }

		public ConfigFile Config { get; }

		protected BaseUnityPlugin()
		{
			BepInPlugin metadata = MetadataHelper.GetMetadata(this);
			if (metadata == null)
			{
				throw new InvalidOperationException("Can't create an instance of " + ((object)this).GetType().FullName + " because it inherits from BaseUnityPlugin and the BepInPlugin attribute is missing.");
			}
			if (!Chainloader.IsEditor && Chainloader.PluginInfos.TryGetValue(metadata.GUID, out var value))
			{
				Info = value;
			}
			else
			{
				Info = new PluginInfo
				{
					Metadata = metadata,
					Instance = this,
					Dependencies = MetadataHelper.GetDependencies(((object)this).GetType()),
					Processes = MetadataHelper.GetAttributes<BepInProcess>(((object)this).GetType()),
					Location = ((object)this).GetType().Assembly.Location
				};
			}
			Logger = BepInEx.Logging.Logger.CreateLogSource(metadata.Name);
			string text = (Chainloader.IsEditor ? "." : Paths.ConfigPath);
			Config = new ConfigFile(Utility.CombinePaths(text, metadata.GUID + ".cfg"), saveOnInit: false, metadata);
		}
	}
	public static class Paths
	{
		public static string[] DllSearchPaths { get; private set; }

		public static string BepInExAssemblyDirectory { get; private set; }

		public static string BepInExAssemblyPath { get; private set; }

		public static string BepInExRootPath { get; private set; }

		public static string ExecutablePath { get; private set; }

		public static string GameRootPath { get; private set; }

		public static string ManagedPath { get; private set; }

		public static string ConfigPath { get; private set; }

		public static string BepInExConfigPath { get; private set; }

		public static string CachePath { get; private set; }

		public static string PatcherPluginPath { get; private set; }

		public static string PluginPath { get; private set; }

		public static string ProcessName { get; private set; }

		internal static void SetExecutablePath(string executablePath, string bepinRootPath = null, string managedPath = null, string[] dllSearchPath = null)
		{
			ExecutablePath = executablePath;
			ProcessName = Path.GetFileNameWithoutExtension(executablePath);
			GameRootPath = (PlatformHelper.Is((Platform)73) ? Utility.ParentDirectory(executablePath, 4) : Path.GetDirectoryName(executablePath));
			ManagedPath = managedPath ?? Utility.CombinePaths(GameRootPath, ProcessName + "_Data", "Managed");
			BepInExRootPath = bepinRootPath ?? Path.Combine(GameRootPath, "BepInEx");
			ConfigPath = Path.Combine(BepInExRootPath, "config");
			BepInExConfigPath = Path.Combine(ConfigPath, "BepInEx.cfg");
			PluginPath = Path.Combine(BepInExRootPath, "plugins");
			PatcherPluginPath = Path.Combine(BepInExRootPath, "patchers");
			BepInExAssemblyDirectory = Path.Combine(BepInExRootPath, "core");
			BepInExAssemblyPath = Path.Combine(BepInExAssemblyDirectory, Assembly.GetExecutingAssembly().GetName().Name + ".dll");
			CachePath = Path.Combine(BepInExRootPath, "cache");
			DllSearchPaths = (dllSearchPath ?? new string[0]).Concat(new string[1] { ManagedPath }).Distinct().ToArray();
		}

		internal static void SetManagedPath(string managedPath)
		{
			if (managedPath != null)
			{
				ManagedPath = managedPath;
			}
		}

		internal static void SetPluginPath(string pluginPath)
		{
			PluginPath = Utility.CombinePaths(BepInExRootPath, pluginPath);
		}
	}
	public sealed class ThreadingHelper : MonoBehaviour, ISynchronizeInvoke
	{
		private sealed class InvokeResult : IAsyncResult
		{
			internal bool ExceptionThrown;

			public bool IsCompleted { get; private set; }

			public WaitHandle AsyncWaitHandle { get; }

			public object AsyncState { get; private set; }

			public bool CompletedSynchronously { get; private set; }

			public InvokeResult()
			{
				AsyncWaitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset);
			}

			public void Finish(object result, bool completedSynchronously)
			{
				AsyncState = result;
				CompletedSynchronously = completedSynchronously;
				IsCompleted = true;
				((EventWaitHandle)AsyncWaitHandle).Set();
			}
		}

		private readonly object _invokeLock = new object();

		private Action _invokeList;

		private Thread _mainThread;

		public static ThreadingHelper Instance { get; private set; }

		public static ISynchronizeInvoke SynchronizingObject => Instance;

		public bool InvokeRequired
		{
			get
			{
				if (_mainThread != null)
				{
					return _mainThread != Thread.CurrentThread;
				}
				return true;
			}
		}

		internal static void Initialize()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			GameObject val = new GameObject("BepInEx_ThreadingHelper");
			if (Chainloader.ConfigHideBepInExGOs.Value)
			{
				((Object)val).hideFlags = (HideFlags)61;
			}
			Object.DontDestroyOnLoad((Object)(object)val);
			Instance = val.AddComponent<ThreadingHelper>();
		}

		public void StartSyncInvoke(Action action)
		{
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}
			lock (_invokeLock)
			{
				_invokeList = (Action)Delegate.Combine(_invokeList, action);
			}
		}

		private void Update()
		{
			if (_mainThread == null)
			{
				_mainThread = Thread.CurrentThread;
			}
			if (_invokeList == null)
			{
				return;
			}
			Action invokeList;
			lock (_invokeLock)
			{
				invokeList = _invokeList;
				_invokeList = null;
			}
			foreach (Action item in invokeList.GetInvocationList().Cast<Action>())
			{
				try
				{
					item();
				}
				catch (Exception ex)
				{
					LogInvocationException(ex);
				}
			}
		}

		public void StartAsyncInvoke(Func<Action> action)
		{
			if (!ThreadPool.QueueUserWorkItem(DoWork))
			{
				throw new NotSupportedException("Failed to queue the action on ThreadPool");
			}
			void DoWork(object _)
			{
				try
				{
					Action action2 = action();
					if (action2 != null)
					{
						StartSyncInvoke(action2);
					}
				}
				catch (Exception ex)
				{
					LogInvocationException(ex);
				}
			}
		}

		private static void LogInvocationException(Exception ex)
		{
			Logger.Log(LogLevel.Error, ex);
			if (ex.InnerException != null)
			{
				Logger.Log(LogLevel.Error, "INNER: " + ex.InnerException);
			}
		}

		IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args)
		{
			InvokeResult result = new InvokeResult();
			if (!InvokeRequired)
			{
				result.Finish(Invoke(), completedSynchronously: true);
			}
			else
			{
				StartSyncInvoke(delegate
				{
					result.Finish(Invoke(), completedSynchronously: false);
				});
			}
			return result;
			object Invoke()
			{
				try
				{
					return method.DynamicInvoke(args);
				}
				catch (Exception result2)
				{
					result.ExceptionThrown = true;
					return result2;
				}
			}
		}

		object ISynchronizeInvoke.EndInvoke(IAsyncResult result)
		{
			InvokeResult invokeResult = (InvokeResult)result;
			invokeResult.AsyncWaitHandle.WaitOne();
			if (invokeResult.ExceptionThrown)
			{
				throw (Exception)invokeResult.AsyncState;
			}
			return invokeResult.AsyncState;
		}

		object ISynchronizeInvoke.Invoke(Delegate method, object[] args)
		{
			IAsyncResult result = ((ISynchronizeInvoke)this).BeginInvoke(method, args);
			return ((ISynchronizeInvoke)this).EndInvoke(result);
		}
	}
	public static class ThreadingExtensions
	{
		public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IEnumerable<TIn> data, Func<TIn, TOut> work, int workerCount = -1)
		{
			foreach (TOut item in data.ToList().RunParallel(work))
			{
				yield return item;
			}
		}

		public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IList<TIn> data, Func<TIn, TOut> work, int workerCount = -1)
		{
			if (workerCount < 0)
			{
				workerCount = Mathf.Max(2, Environment.ProcessorCount);
			}
			else if (workerCount == 0)
			{
				throw new ArgumentException("Need at least 1 worker", "workerCount");
			}
			int perThreadCount = Mathf.CeilToInt((float)data.Count / (float)workerCount);
			int doneCount = 0;
			object lockObj = new object();
			ManualResetEvent are = new ManualResetEvent(initialState: false);
			IEnumerable<TOut> doneItems = null;
			Exception exceptionThrown = null;
			for (int i = 0; i < workerCount; i++)
			{
				int first = i * perThreadCount;
				int last = Mathf.Min(first + perThreadCount, data.Count);
				ThreadPool.QueueUserWorkItem(delegate
				{
					List<TOut> list = new List<TOut>(perThreadCount);
					try
					{
						for (int j = first; j < last; j++)
						{
							if (exceptionThrown != null)
							{
								break;
							}
							list.Add(work(data[j]));
						}
					}
					catch (Exception ex)
					{
						exceptionThrown = ex;
					}
					lock (lockObj)
					{
						IEnumerable<TOut> enumerable2;
						if (doneItems != null)
						{
							enumerable2 = list.Concat(doneItems);
						}
						else
						{
							IEnumerable<TOut> enumerable3 = list;
							enumerable2 = enumerable3;
						}
						doneItems = enumerable2;
						int num = doneCount;
						doneCount = num + 1;
						are.Set();
					}
				});
			}
			bool isDone;
			do
			{
				are.WaitOne();
				IEnumerable<TOut> enumerable;
				lock (lockObj)
				{
					enumerable = doneItems;
					doneItems = null;
					isDone = doneCount == workerCount;
				}
				if (enumerable == null)
				{
					continue;
				}
				foreach (TOut item in enumerable)
				{
					yield return item;
				}
			}
			while (!isDone);
			if (exceptionThrown != null)
			{
				throw new TargetInvocationException("An exception was thrown inside one of the threads", exceptionThrown);
			}
		}
	}
	public static class Utility
	{
		private static bool? sreEnabled;

		public static bool CLRSupportsDynamicAssemblies => CheckSRE();

		public static Encoding UTF8NoBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);


		private static bool CheckSRE()
		{
			if (sreEnabled.HasValue)
			{
				return sreEnabled.Value;
			}
			try
			{
				new CustomAttributeBuilder(null, new object[0]);
			}
			catch (PlatformNotSupportedException)
			{
				sreEnabled = false;
				return sreEnabled.Value;
			}
			catch (ArgumentNullException)
			{
			}
			sreEnabled = true;
			return sreEnabled.Value;
		}

		public static bool TryDo(Action action, out Exception exception)
		{
			exception = null;
			try
			{
				action();
				return true;
			}
			catch (Exception ex)
			{
				exception = ex;
				return false;
			}
		}

		public static string CombinePaths(params string[] parts)
		{
			return parts.Aggregate(Path.Combine);
		}

		public static string ParentDirectory(string path, int levels = 1)
		{
			for (int i = 0; i < levels; i++)
			{
				path = Path.GetDirectoryName(path);
			}
			return path;
		}

		public static bool SafeParseBool(string input, bool defaultValue = false)
		{
			if (!bool.TryParse(input, out var result))
			{
				return defaultValue;
			}
			return result;
		}

		public static string ConvertToWWWFormat(string path)
		{
			return "file://" + path.Replace('\\', '/');
		}

		public static bool IsNullOrWhiteSpace(this string self)
		{
			return self?.All(char.IsWhiteSpace) ?? true;
		}

		public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
		{
			List<TNode> sorted_list = new List<TNode>();
			HashSet<TNode> visited = new HashSet<TNode>();
			HashSet<TNode> sorted = new HashSet<TNode>();
			foreach (TNode node in nodes)
			{
				Stack<TNode> stack2 = new Stack<TNode>();
				if (!Visit(node, stack2))
				{
					throw new Exception("Cyclic Dependency:\r\n" + stack2.Select((TNode x) => $" - {x}").Aggregate((string a, string b) => a + "\r\n" + b));
				}
			}
			return sorted_list;
			bool Visit(TNode node, Stack<TNode> stack)
			{
				if (visited.Contains(node))
				{
					if (!sorted.Contains(node))
					{
						return false;
					}
				}
				else
				{
					visited.Add(node);
					stack.Push(node);
					foreach (TNode item in dependencySelector(node))
					{
						if (!Visit(item, stack))
						{
							return false;
						}
					}
					sorted.Add(node);
					sorted_list.Add(node);
					stack.Pop();
				}
				return true;
			}
		}

		private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class
		{
			assembly = null;
			List<string> list = new List<string>();
			list.Add(directory);
			list.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));
			foreach (string item in list)
			{
				string text = Path.Combine(item, assemblyName.Name + ".dll");
				if (File.Exists(text))
				{
					try
					{
						assembly = loader(text);
					}
					catch (Exception)
					{
						continue;
					}
					return true;
				}
			}
			return false;
		}

		public static bool IsSubtypeOf(this TypeDefinition self, Type td)
		{
			if (((MemberReference)self).FullName == td.FullName)
			{
				return true;
			}
			if (((MemberReference)self).FullName != "System.Object")
			{
				TypeReference baseType = self.BaseType;
				return ((baseType == null) ? null : baseType.Resolve()?.IsSubtypeOf(td)).GetValueOrDefault();
			}
			return false;
		}

		public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly)
		{
			return TryResolveDllAssembly(assemblyName, directory, (Func<string, Assembly>)Assembly.LoadFile, out assembly);
		}

		public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly)
		{
			return TryResolveDllAssembly(assemblyName, directory, (Func<string, AssemblyDefinition>)((string s) => AssemblyDefinition.ReadAssembly(s, readerParameters)), out assembly);
		}

		public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
		{
			try
			{
				fileStream = new FileStream(path, mode, access, share);
				return true;
			}
			catch (IOException)
			{
				fileStream = null;
				return false;
			}
		}

		public static bool TryParseAssemblyName(string fullName, out AssemblyName assemblyName)
		{
			try
			{
				assemblyName = new AssemblyName(fullName);
				return true;
			}
			catch (Exception)
			{
				assemblyName = null;
				return false;
			}
		}

		public static IEnumerable<string> GetUniqueFilesInDirectories(IEnumerable<string> directories, string pattern = "*")
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
			foreach (string directory in directories)
			{
				string[] files = Directory.GetFiles(directory, pattern);
				foreach (string text in files)
				{
					string fileName = Path.GetFileName(text);
					if (!dictionary.ContainsKey(fileName))
					{
						dictionary[fileName] = text;
					}
				}
			}
			return dictionary.Values;
		}
	}
}
namespace BepInEx.Logging
{
	public class DiskLogListener : ILogListener, IDisposable
	{
		public LogLevel DisplayedLogLevel { get; set; }

		public TextWriter LogWriter { get; protected set; }

		public Timer FlushTimer { get; protected set; }

		public bool WriteFromUnityLog { get; set; }

		public DiskLogListener(string localPath, LogLevel displayedLogLevel = LogLevel.Info, bool appendLog = false, bool includeUnityLog = false)
		{
			WriteFromUnityLog = includeUnityLog;
			DisplayedLogLevel = displayedLogLevel;
			int num = 1;
			FileStream fileStream;
			while (!Utility.TryOpenFileStream(Path.Combine(Paths.BepInExRootPath, localPath), appendLog ? FileMode.Append : FileMode.Create, out fileStream, FileAccess.Write))
			{
				if (num == 5)
				{
					Logger.LogError("Couldn't open a log file for writing. Skipping log file creation");
					return;
				}
				Logger.LogWarning("Couldn't open log file '" + localPath + "' for writing, trying another...");
				localPath = $"LogOutput.log.{num++}";
			}
			LogWriter = TextWriter.Synchronized(new StreamWriter(fileStream, Utility.UTF8NoBom));
			FlushTimer = new Timer(delegate
			{
				LogWriter?.Flush();
			}, null, 2000, 2000);
		}

		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			if ((WriteFromUnityLog || !(eventArgs.Source is UnityLogSource)) && (eventArgs.Level & DisplayedLogLevel) != 0)
			{
				LogWriter.WriteLine(eventArgs.ToString());
			}
		}

		public void Dispose()
		{
			FlushTimer?.Dispose();
			LogWriter?.Flush();
			LogWriter?.Dispose();
		}

		~DiskLogListener()
		{
			Dispose();
		}
	}
	internal class HarmonyLogSource : ILogSource, IDisposable
	{
		private static readonly ConfigEntry<LogChannel> LogChannels = ConfigFile.CoreConfig.Bind<LogChannel>("Harmony.Logger", "LogChannels", (LogChannel)24, "Specifies which Harmony log channels to listen to.\nNOTE: IL channel dumps the whole patch methods, use only when needed!");

		private static readonly Dictionary<LogChannel, LogLevel> LevelMap = new Dictionary<LogChannel, LogLevel>
		{
			[(LogChannel)2] = LogLevel.Info,
			[(LogChannel)8] = LogLevel.Warning,
			[(LogChannel)16] = LogLevel.Error,
			[(LogChannel)4] = LogLevel.Debug
		};

		public string SourceName { get; } = "HarmonyX";


		public event EventHandler<LogEventArgs> LogEvent;

		public HarmonyLogSource()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			Logger.ChannelFilter = LogChannels.Value;
			Logger.MessageReceived += HandleHarmonyMessage;
		}

		private void HandleHarmonyMessage(object sender, LogEventArgs e)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (LevelMap.TryGetValue(e.LogChannel, out var value))
			{
				this.LogEvent?.Invoke(this, new LogEventArgs(e.Message, value, this));
			}
		}

		public void Dispose()
		{
			Logger.MessageReceived -= HandleHarmonyMessage;
		}
	}
	public class LogEventArgs : EventArgs
	{
		public object Data { get; protected set; }

		public LogLevel Level { get; protected set; }

		public ILogSource Source { get; protected set; }

		public LogEventArgs(object data, LogLevel level, ILogSource source)
		{
			Data = data;
			Level = level;
			Source = source;
		}

		public override string ToString()
		{
			return $"[{Level,-7}:{Source.SourceName,10}] {Data}";
		}

		public string ToStringLine()
		{
			return ToString() + Environment.NewLine;
		}
	}
	public static class Logger
	{
		private sealed class LogSourceCollection : ThreadSafeCollection<ILogSource>, ICollection<ILogSource>, IEnumerable<ILogSource>, IEnumerable
		{
			public override void Add(ILogSource item)
			{
				if (item == null)
				{
					throw new ArgumentNullException("item", "Log sources cannot be null when added to the source list.");
				}
				lock (Lock)
				{
					item.LogEvent += InternalLogEvent;
					List<ILogSource> list = new List<ILogSource>(BaseList.Count + 1);
					list.AddRange(BaseList);
					list.Add(item);
					BaseList = list;
				}
			}

			public override void Clear()
			{
				if (base.Count == 0)
				{
					return;
				}
				lock (Lock)
				{
					for (int i = 0; i < BaseList.Count; i++)
					{
						BaseList[i].LogEvent -= InternalLogEvent;
					}
					BaseList = new List<ILogSource>(0);
				}
			}

			public override bool Remove(ILogSource item)
			{
				if (item == null)
				{
					return false;
				}
				lock (Lock)
				{
					bool num = base.Remove(item);
					if (num)
					{
						item.LogEvent -= InternalLogEvent;
					}
					return num;
				}
			}
		}

		private sealed class LogListenerCollection : ThreadSafeCollection<ILogListener>
		{
			public void SendLogEvent(object sender, LogEventArgs eventArgs)
			{
				List<ILogListener> baseList = BaseList;
				for (int i = 0; i < baseList.Count; i++)
				{
					baseList[i].LogEvent(sender, eventArgs);
				}
			}
		}

		private class ThreadSafeCollection<T> : ICollection<T>, IEnumerable<T>, IEnumerable where T : class
		{
			protected readonly object Lock = new object();

			protected List<T> BaseList = new List<T>(0);

			public int Count => BaseList.Count;

			public bool IsReadOnly => false;

			public IEnumerator<T> GetEnumerator()
			{
				return BaseList.GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return BaseList.GetEnumerator();
			}

			public virtual void Add(T item)
			{
				if (item == null)
				{
					throw new ArgumentNullException("item", "item can't be null");
				}
				lock (Lock)
				{
					List<T> list = new List<T>(BaseList.Count + 1);
					list.AddRange(BaseList);
					list.Add(item);
					BaseList = list;
				}
			}

			public virtual void Clear()
			{
				if (Count == 0)
				{
					return;
				}
				lock (Lock)
				{
					BaseList = new List<T>(0);
				}
			}

			public bool Contains(T item)
			{
				return BaseList.Contains(item);
			}

			public void CopyTo(T[] array, int arrayIndex)
			{
				BaseList.CopyTo(array, arrayIndex);
			}

			public virtual bool Remove(T item)
			{
				if (item == null)
				{
					return false;
				}
				lock (Lock)
				{
					List<T> list = new List<T>(BaseList.Count);
					bool result = false;
					for (int i = 0; i < BaseList.Count; i++)
					{
						T val = BaseList[i];
						if (val.Equals(item))
						{
							result = true;
						}
						else
						{
							list.Add(val);
						}
					}
					BaseList = list;
					return result;
				}
			}
		}

		private static readonly LogListenerCollection _Listeners = new LogListenerCollection();

		private static readonly ManualLogSource InternalLogSource = CreateLogSource("BepInEx");

		private static bool internalLogsInitialized;

		public static ICollection<ILogListener> Listeners => _Listeners;

		public static ICollection<ILogSource> Sources { get; } = new LogSourceCollection();


		internal static void InitializeInternalLoggers()
		{
			if (!internalLogsInitialized)
			{
				Sources.Add(new HarmonyLogSource());
				internalLogsInitialized = true;
			}
		}

		internal static void InternalLogEvent(object sender, LogEventArgs eventArgs)
		{
			_Listeners.SendLogEvent(sender, eventArgs);
		}

		internal static void Log(LogLevel level, object data)
		{
			InternalLogSource.Log(level, data);
		}

		internal static void LogFatal(object data)
		{
			Log(LogLevel.Fatal, data);
		}

		internal static void LogError(object data)
		{
			Log(LogLevel.Error, data);
		}

		internal static void LogWarning(object data)
		{
			Log(LogLevel.Warning, data);
		}

		internal static void LogMessage(object data)
		{
			Log(LogLevel.Message, data);
		}

		internal static void LogInfo(object data)
		{
			Log(LogLevel.Info, data);
		}

		internal static void LogDebug(object data)
		{
			Log(LogLevel.Debug, data);
		}

		public static ManualLogSource CreateLogSource(string sourceName)
		{
			ManualLogSource manualLogSource = new ManualLogSource(sourceName);
			Sources.Add(manualLogSource);
			return manualLogSource;
		}
	}
	[Flags]
	public enum LogLevel
	{
		None = 0,
		Fatal = 1,
		Error = 2,
		Warning = 4,
		Message = 8,
		Info = 0x10,
		Debug = 0x20,
		All = 0x3F
	}
	public static class LogLevelExtensions
	{
		public static LogLevel GetHighestLevel(this LogLevel levels)
		{
			Array values = Enum.GetValues(typeof(LogLevel));
			Array.Sort(values);
			foreach (LogLevel item in values)
			{
				if ((levels & item) != 0)
				{
					return item;
				}
			}
			return LogLevel.None;
		}

		public static ConsoleColor GetConsoleColor(this LogLevel level)
		{
			level = level.GetHighestLevel();
			return level switch
			{
				LogLevel.Fatal => ConsoleColor.Red, 
				LogLevel.Error => ConsoleColor.DarkRed, 
				LogLevel.Warning => ConsoleColor.Yellow, 
				LogLevel.Message => ConsoleColor.White, 
				LogLevel.Debug => ConsoleColor.DarkGray, 
				_ => ConsoleColor.Gray, 
			};
		}
	}
	public interface ILogListener : IDisposable
	{
		void LogEvent(object sender, LogEventArgs eventArgs);
	}
	public interface ILogSource : IDisposable
	{
		string SourceName { get; }

		event EventHandler<LogEventArgs> LogEvent;
	}
	public class ManualLogSource : ILogSource, IDisposable
	{
		public string SourceName { get; }

		public event EventHandler<LogEventArgs> LogEvent;

		public ManualLogSource(string sourceName)
		{
			SourceName = sourceName;
		}

		public void Log(LogLevel level, object data)
		{
			this.LogEvent?.Invoke(this, new LogEventArgs(data, level, this));
		}

		public void LogFatal(object data)
		{
			Log(LogLevel.Fatal, data);
		}

		public void LogError(object data)
		{
			Log(LogLevel.Error, data);
		}

		public void LogWarning(object data)
		{
			Log(LogLevel.Warning, data);
		}

		public void LogMessage(object data)
		{
			Log(LogLevel.Message, data);
		}

		public void LogInfo(object data)
		{
			Log(LogLevel.Info, data);
		}

		public void LogDebug(object data)
		{
			Log(LogLevel.Debug, data);
		}

		public void Dispose()
		{
		}
	}
	public class TraceLogSource : TraceListener
	{
		private static TraceLogSource traceListener;

		public static bool IsListening { get; protected set; }

		protected ManualLogSource LogSource { get; }

		public static ILogSource CreateSource()
		{
			if (traceListener == null)
			{
				traceListener = new TraceLogSource();
				Trace.Listeners.Add(traceListener);
				IsListening = true;
			}
			return traceListener.LogSource;
		}

		protected TraceLogSource()
		{
			LogSource = new ManualLogSource("Trace");
		}

		public override void Write(string message)
		{
			LogSource.LogInfo(message);
		}

		public override void WriteLine(string message)
		{
			LogSource.LogInfo(message);
		}

		public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
		{
			TraceEvent(eventCache, source, eventType, id, string.Format(format, args));
		}

		public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
		{
			LogSource.Log(eventType switch
			{
				TraceEventType.Critical => LogLevel.Fatal, 
				TraceEventType.Error => LogLevel.Error, 
				TraceEventType.Warning => LogLevel.Warning, 
				TraceEventType.Information => LogLevel.Info, 
				_ => LogLevel.Debug, 
			}, (message ?? "").Trim());
		}
	}
	public class ConsoleLogListener : ILogListener, IDisposable
	{
		private static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Console", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Which log levels to show in the console output.");

		internal bool WriteUnityLogs { get; set; } = true;


		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			if ((WriteUnityLogs || !(sender is UnityLogSource)) && (eventArgs.Level & ConfigConsoleDisplayedLevel.Value) != 0)
			{
				ConsoleManager.SetConsoleColor(eventArgs.Level.GetConsoleColor());
				ConsoleManager.ConsoleStream?.Write(eventArgs.ToStringLine());
				ConsoleManager.SetConsoleColor(ConsoleColor.Gray);
			}
		}

		public void Dispose()
		{
		}
	}
	public class UnityLogListener : ILogListener, IDisposable
	{
		internal static readonly Action<string> WriteStringToUnityLog;

		private ConfigEntry<bool> LogConsoleToUnity = ConfigFile.CoreConfig.Bind("Logging", "LogConsoleToUnityLog", defaultValue: false, new StringBuilder().AppendLine("If enabled, writes Standard Output messages to Unity log").AppendLine("NOTE: By default, Unity does so automatically. Only use this option if no console messages are visible in Unity log").ToString());

		static UnityLogListener()
		{
			MethodInfo[] methods = typeof(UnityLogWriter).GetMethods(BindingFlags.Static | BindingFlags.Public);
			foreach (MethodInfo methodInfo in methods)
			{
				try
				{
					methodInfo.Invoke(null, new object[1] { "" });
				}
				catch
				{
					continue;
				}
				WriteStringToUnityLog = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), methodInfo);
				break;
			}
			if (WriteStringToUnityLog == null)
			{
				Logger.LogError("Unable to start Unity log writer");
			}
		}

		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			if (!(eventArgs.Source is UnityLogSource) && (LogConsoleToUnity.Value || eventArgs.Source.SourceName != "Console"))
			{
				WriteStringToUnityLog?.Invoke(eventArgs.ToStringLine());
			}
		}

		public void Dispose()
		{
		}
	}
	public class UnityLogSource : ILogSource, IDisposable
	{
		private bool disposed;

		public string SourceName { get; } = "Unity Log";


		public event EventHandler<LogEventArgs> LogEvent;

		private static event EventHandler<LogEventArgs> InternalUnityLogMessage;

		public UnityLogSource()
		{
			InternalUnityLogMessage += UnityLogMessageHandler;
		}

		private void UnityLogMessageHandler(object sender, LogEventArgs eventArgs)
		{
			LogEventArgs e = new LogEventArgs(eventArgs.Data, eventArgs.Level, this);
			this.LogEvent?.Invoke(this, e);
		}

		public void Dispose()
		{
			if (!disposed)
			{
				InternalUnityLogMessage -= UnityLogMessageHandler;
				disposed = true;
			}
		}

		static UnityLogSource()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			LogCallback val = new LogCallback(OnUnityLogMessageReceived);
			EventInfo @event = typeof(Application).GetEvent("logMessageReceived", BindingFlags.Static | BindingFlags.Public);
			if ((object)@event != null)
			{
				@event.AddEventHandler(null, (Delegate?)(object)val);
				return;
			}
			typeof(Application).GetMethod("RegisterLogCallback", BindingFlags.Static | BindingFlags.Public).Invoke(null, new object[1] { val });
		}

		private static void OnUnityLogMessageReceived(string message, string stackTrace, LogType type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected I4, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			LogLevel level;
			switch ((int)type)
			{
			case 0:
			case 1:
			case 4:
				level = LogLevel.Error;
				break;
			case 2:
				level = LogLevel.Warning;
				break;
			default:
				level = LogLevel.Info;
				break;
			}
			if ((int)type == 4)
			{
				message = message + "\nStack trace:\n" + stackTrace;
			}
			UnityLogSource.InternalUnityLogMessage?.Invoke(null, new LogEventArgs(message, level, null));
		}
	}
}
namespace BepInEx.Bootstrap
{
	public static class Chainloader
	{
		private static readonly List<BaseUnityPlugin> _plugins = new List<BaseUnityPlugin>();

		private static bool? isEditor;

		private static bool _loaded = false;

		private static bool _initialized = false;

		private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;

		private static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;

		internal static readonly ConfigEntry<bool> ConfigHideBepInExGOs = ConfigFile.CoreConfig.Bind("Chainloader", "HideManagerGameObject", defaultValue: false, new StringBuilder().AppendLine("If enabled, hides BepInEx Manager GameObject from Unity.").AppendLine("This can fix loading issues in some games that attempt to prevent BepInEx from being loaded.").AppendLine("Use this only if you know what this option means, as it can affect functionality of some older plugins.")
			.ToString());

		private static readonly ConfigEntry<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Bind("Logging", "UnityLogListening", defaultValue: true, "Enables showing unity log messages in the BepInEx logging system.");

		private static readonly ConfigEntry<bool> ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind("Logging.Disk", "WriteUnityLog", defaultValue: false, "Include unity log messages in log file output.");

		private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind("Logging.Disk", "AppendLog", defaultValue: false, "Appends to the log file instead of overwriting, on game startup.");

		private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind("Logging.Disk", "Enabled", defaultValue: true, "Enables writing log messages to disk.");

		private static readonly ConfigEntry<LogLevel> ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Disk", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Which log leves are saved to the disk log output.");

		public static Dictionary<string, PluginInfo> PluginInfos { get; } = new Dictionary<string, PluginInfo>();


		private static string UnityVersion
		{
			[MethodImpl(MethodImplOptions.NoInlining)]
			get
			{
				return Application.unityVersion;
			}
		}

		private static bool IsHeadless
		{
			get
			{
				MethodInfo methodInfo = AccessTools.PropertyGetter(typeof(Application), "isBatchMode");
				if ((object)methodInfo != null)
				{
					return (bool)methodInfo.Invoke(null, null);
				}
				return SystemInfo.graphicsDeviceID == 0;
			}
		}

		internal static bool IsEditor
		{
			[MethodImpl(MethodImplOptions.NoInlining)]
			get
			{
				bool? flag = isEditor;
				if (!flag.HasValue)
				{
					bool? flag2 = (isEditor = Application.isEditor);
					return flag2.GetValueOrDefault();
				}
				return flag.GetValueOrDefault();
			}
		}

		[Obsolete("Use PluginInfos instead")]
		public static List<BaseUnityPlugin> Plugins
		{
			get
			{
				lock (_plugins)
				{
					_plugins.RemoveAll((BaseUnityPlugin x) => (Object)(object)x == (Object)null);
					return _plugins.ToList();
				}
			}
		}

		public static List<string> DependencyErrors { get; } = new List<string>();


		public static GameObject ManagerObject { get; private set; }

		private static Regex allowedGuidRegex { get; } = new Regex("^[a-zA-Z0-9\\._\\-]+$");


		public static void Initialize(string gameExePath, bool startConsole = true, ICollection<LogEventArgs> preloaderLogEvents = null)
		{
			if (!_initialized)
			{
				ThreadingHelper.Initialize();
				if (gameExePath != null)
				{
					Paths.SetExecutablePath(gameExePath);
				}
				if (ConsoleManager.ConsoleEnabled && startConsole)
				{
					ConsoleManager.CreateConsole();
					Logger.Listeners.Add(new ConsoleLogListener());
				}
				Logger.InitializeInternalLoggers();
				if (ConfigDiskLogging.Value)
				{
					Logger.Listeners.Add(new DiskLogListener("LogOutput.log", ConfigDiskConsoleDisplayedLevel.Value, ConfigDiskAppend.Value, ConfigDiskWriteUnityLog.Value));
				}
				if (!TraceLogSource.IsListening)
				{
					Logger.Sources.Add(TraceLogSource.CreateSource());
				}
				ReplayPreloaderLogs(preloaderLogEvents);
				if (ConfigUnityLogging.Value)
				{
					Logger.Sources.Add(new UnityLogSource());
				}
				if (!IsHeadless)
				{
					Logger.Listeners.Add(new UnityLogListener());
				}
				else if (Logger.Listeners.FirstOrDefault((ILogListener l) => l is ConsoleLogListener) is ConsoleLogListener consoleLogListener)
				{
					consoleLogListener.WriteUnityLogs = false;
				}
				if (PlatformHelper.Is((Platform)8))
				{
					Logger.LogInfo("Detected Unity version: v" + UnityVersion);
				}
				Logger.LogMessage("Chainloader ready");
				_initialized = true;
			}
		}

		private static void ReplayPreloaderLogs(ICollection<LogEventArgs> preloaderLogEvents)
		{
			if (preloaderLogEvents == null)
			{
				return;
			}
			UnityLogListener item = new UnityLogListener();
			Logger.Listeners.Add(item);
			ILogListener logListener = Logger.Listeners.FirstOrDefault((ILogListener logger) => logger is ConsoleLogListener);
			if (logListener != null)
			{
				Logger.Listeners.Remove(logListener);
			}
			ManualLogSource manualLogSource = Logger.CreateLogSource("Preloader");
			foreach (LogEventArgs preloaderLogEvent in preloaderLogEvents)
			{
				Logger.InternalLogEvent(manualLogSource, preloaderLogEvent);
			}
			Logger.Sources.Remove(manualLogSource);
			Logger.Listeners.Remove(item);
			if (logListener != null)
			{
				Logger.Listeners.Add(logListener);
			}
		}

		public static PluginInfo ToPluginInfo(TypeDefinition type)
		{
			if (type.IsInterface || type.IsAbstract)
			{
				return null;
			}
			try
			{
				if (!type.IsSubtypeOf(typeof(BaseUnityPlugin)))
				{
					return null;
				}
			}
			catch (AssemblyResolutionException)
			{
				return null;
			}
			BepInPlugin bepInPlugin = BepInPlugin.FromCecilType(type);
			if (bepInPlugin == null)
			{
				Logger.LogWarning("Skipping over type [" + ((MemberReference)type).FullName + "] as no metadata attribute is specified");
				return null;
			}
			if (string.IsNullOrEmpty(bepInPlugin.GUID) || !allowedGuidRegex.IsMatch(bepInPlugin.GUID))
			{
				Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its GUID [" + bepInPlugin.GUID + "] is of an illegal format.");
				return null;
			}
			if (bepInPlugin.Version == null)
			{
				Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its version is invalid.");
				return null;
			}
			if (bepInPlugin.Name == null)
			{
				Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its name is null.");
				return null;
			}
			List<BepInProcess> processes = BepInProcess.FromCecilType(type);
			IEnumerable<BepInDependency> dependencies = BepInDependency.FromCecilType(type);
			IEnumerable<BepInIncompatibility> incompatibilities = BepInIncompatibility.FromCecilType(type);
			AssemblyNameReference? obj = ((IEnumerable<AssemblyNameReference>)((MemberReference)type).Module.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference reference) => reference.Name == "BepInEx"));
			Version targettedBepInExVersion = ((obj != null) ? obj.Version : null) ?? new Version();
			return new PluginInfo
			{
				Metadata = bepInPlugin,
				Processes = processes,
				Dependencies = dependencies,
				Incompatibilities = incompatibilities,
				TypeName = ((MemberReference)type).FullName,
				TargettedBepInExVersion = targettedBepInExVersion
			};
		}

		private static bool HasBepinPlugins(AssemblyDefinition ass)
		{
			if (((IEnumerable<AssemblyNameReference>)ass.MainModule.AssemblyReferences).All((AssemblyNameReference r) => r.Name != CurrentAssemblyName))
			{
				return false;
			}
			if (ass.MainModule.GetTypeReferences().All((TypeReference r) => ((MemberReference)r).FullName != typeof(BepInPlugin).FullName))
			{
				return false;
			}
			return true;
		}

		private static bool PluginTargetsWrongBepin(PluginInfo pluginInfo)
		{
			Version targettedBepInExVersion = pluginInfo.TargettedBepInExVersion;
			if (targettedBepInExVersion.Major != CurrentAssemblyVersion.Major)
			{
				return true;
			}
			if (targettedBepInExVersion.Minor > CurrentAssemblyVersion.Minor)
			{
				return true;
			}
			if (targettedBepInExVersion.Minor < CurrentAssemblyVersion.Minor)
			{
				return false;
			}
			return targettedBepInExVersion.Build > CurrentAssemblyVersion.Build;
		}

		public static void Start()
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			if (_loaded)
			{
				return;
			}
			if (!_initialized)
			{
				throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
			}
			if (!Directory.Exists(Paths.PluginPath))
			{
				Directory.CreateDirectory(Paths.PluginPath);
			}
			if (!Directory.Exists(Paths.PatcherPluginPath))
			{
				Directory.CreateDirectory(Paths.PatcherPluginPath);
			}
			try
			{
				PropertyInfo property = typeof(Application).GetProperty("productName", BindingFlags.Static | BindingFlags.Public);
				if (ConsoleManager.ConsoleActive)
				{
					ConsoleManager.SetConsoleTitle($"{CurrentAssemblyName} {CurrentAssemblyVersion} - {property?.GetValue(null, null) ?? Paths.ProcessName}");
				}
				Logger.LogMessage("Chainloader started");
				ManagerObject = new GameObject("BepInEx_Manager");
				if (ConfigHideBepInExGOs.Value)
				{
					((Object)ManagerObject).hideFlags = (HideFlags)61;
				}
				Object.DontDestroyOnLoad((Object)(object)ManagerObject);
				Dictionary<string, List<PluginInfo>> dictionary = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader");
				foreach (KeyValuePair<string, List<PluginInfo>> item in dictionary)
				{
					foreach (PluginInfo item2 in item.Value)
					{
						item2.Location = item.Key;
					}
				}
				List<PluginInfo> list = dictionary.SelectMany((KeyValuePair<string, List<PluginInfo>> p) => p.Value).ToList();
				Dictionary<string, Assembly> dictionary2 = new Dictionary<string, Assembly>();
				Logger.LogInfo(string.Format("{0} plugin{1} to load", list.Count, (list.Count == 1) ? "" : "s"));
				SortedDictionary<string, IEnumerable<string>> dependencyDict = new SortedDictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase);
				Dictionary<string, PluginInfo> pluginsByGUID = new Dictionary<string, PluginInfo>();
				foreach (IGrouping<string, PluginInfo> item3 in from info in list
					group info by info.Metadata.GUID)
				{
					PluginInfo pluginInfo = null;
					foreach (PluginInfo item4 in item3.OrderByDescending((PluginInfo x) => x.Metadata.Version))
					{
						if (pluginInfo != null)
						{
							Logger.LogWarning($"Skipping [{item4}] because a newer version exists ({pluginInfo})");
							continue;
						}
						List<BepInProcess> list2 = item4.Processes.ToList();
						if (list2.Count != 0 && list2.All((BepInProcess x) => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase)))
						{
							Logger.LogWarning(string.Format("Skipping [{0}] because of process filters ({1})", item4, string.Join(", ", item4.Processes.Select((BepInProcess p) => p.ProcessName).ToArray())));
							continue;
						}
						pluginInfo = item4;
						dependencyDict[item4.Metadata.GUID] = item4.Dependencies.Select((BepInDependency d) => d.DependencyGUID);
						pluginsByGUID[item4.Metadata.GUID] = item4;
					}
				}
				foreach (PluginInfo item5 in pluginsByGUID.Values.ToList())
				{
					if (item5.Incompatibilities.Any((BepInIncompatibility incompatibility) => pluginsByGUID.ContainsKey(incompatibility.IncompatibilityGUID)))
					{
						pluginsByGUID.Remove(item5.Metadata.GUID);
						dependencyDict.Remove(item5.Metadata.GUID);
						string[] value = (from x in item5.Incompatibilities
							select x.IncompatibilityGUID into x
							where pluginsByGUID.ContainsKey(x)
							select x).ToArray();
						string text = string.Format("Could not load [{0}] because it is incompatible with: {1}", item5, string.Join(", ", value));
						DependencyErrors.Add(text);
						Logger.LogError(text);
					}
					else if (PluginTargetsWrongBepin(item5))
					{
						string text2 = $"Plugin [{item5}] targets a wrong version of BepInEx ({item5.TargettedBepInExVersion}) and might not work until you update";
						DependencyErrors.Add(text2);
						Logger.LogWarning(text2);
					}
				}
				string[] emptyDependencies = new string[0];
				IEnumerable<string> value5;
				List<string> list3 = Utility.TopologicalSort(dependencyDict.Keys, (string x) => (!dependencyDict.TryGetValue(x, out value5)) ? emptyDependencies : value5).ToList();
				HashSet<string> hashSet = new HashSet<string>();
				Dictionary<string, Version> dictionary3 = new Dictionary<string, Version>();
				foreach (string item6 in list3)
				{
					if (!pluginsByGUID.TryGetValue(item6, out var value2))
					{
						continue;
					}
					bool flag = false;
					List<BepInDependency> list4 = new List<BepInDependency>();
					foreach (BepInDependency dependency in value2.Dependencies)
					{
						if (!dictionary3.TryGetValue(dependency.DependencyGUID, out var value3) || value3 < dependency.MinimumVersion)
						{
							if (IsHardDependency(dependency))
							{
								list4.Add(dependency);
							}
						}
						else if (hashSet.Contains(dependency.DependencyGUID) && IsHardDependency(dependency))
						{
							flag = true;
							break;
						}
					}
					dictionary3.Add(item6, value2.Metadata.Version);
					if (flag)
					{
						string text3 = $"Skipping [{value2}] because it has a dependency that was not loaded. See previous errors for details.";
						DependencyErrors.Add(text3);
						Logger.LogWarning(text3);
						continue;
					}
					if (list4.Count != 0)
					{
						string text4 = string.Format("Could not load [{0}] because it has missing dependencies: {1}", value2, string.Join(", ", list4.Select((BepInDependency s) => (!IsEmptyVersion(s.MinimumVersion)) ? $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)" : s.DependencyGUID).ToArray()));
						DependencyErrors.Add(text4);
						Logger.LogError(text4);
						hashSet.Add(item6);
						continue;
					}
					try
					{
						Logger.LogInfo($"Loading [{value2}]");
						if (!dictionary2.TryGetValue(value2.Location, out var value4))
						{
							value4 = (dictionary2[value2.Location] = Assembly.LoadFile(value2.Location));
						}
						PluginInfos[item6] = value2;
						value2.Instance = (BaseUnityPlugin)(object)ManagerObject.AddComponent(value4.GetType(value2.TypeName));
						_plugins.Add(value2.Instance);
					}
					catch (Exception ex)
					{
						hashSet.Add(item6);
						PluginInfos.Remove(item6);
						Logger.LogError($"Error loading [{value2}] : {ex.Message}");
						if (ex is ReflectionTypeLoadException ex2)
						{
							Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(ex2));
						}
						else
						{
							Logger.LogDebug(ex);
						}
					}
				}
			}
			catch (Exception ex3)
			{
				try
				{
					ConsoleManager.CreateConsole();
				}
				catch
				{
				}
				Logger.LogFatal("Error occurred starting the game");
				Logger.LogFatal(ex3.ToString());
			}
			Logger.LogMessage("Chainloader startup complete");
			_loaded = true;
			static bool IsEmptyVersion(Version v)
			{
				if (v.Major == 0 && v.Minor == 0 && v.Build <= 0)
				{
					return v.Revision <= 0;
				}
				return false;
			}
			static bool IsHardDependency(BepInDependency dep)
			{
				return (dep.Flags & BepInDependency.DependencyFlags.HardDependency) != 0;
			}
		}
	}
	public interface ICacheable
	{
		void Save(BinaryWriter bw);

		void Load(BinaryReader br);
	}
	public class CachedAssembly<T> where T : ICacheable
	{
		public List<T> CacheItems { get; set; }

		public long Timestamp { get; set; }
	}
	public static class TypeLoader
	{
		public static readonly DefaultAssemblyResolver Resolver;

		public static readonly ReaderParameters ReaderParameters;

		[CompilerGenerated]
		private static AssemblyResolveEventHandler m_AssemblyResolve;

		private static readonly ConfigEntry<bool> EnableAssemblyCache;

		public static event AssemblyResolveEventHandler AssemblyResolve
		{
			[CompilerGenerated]
			add
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Expected O, but got Unknown
				AssemblyResolveEventHandler val = TypeLoader.m_AssemblyResolve;
				AssemblyResolveEventHandler val2;
				do
				{
					val2 = val;
					AssemblyResolveEventHandler value2 = (AssemblyResolveEventHandler)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref TypeLoader.m_AssemblyResolve, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Expected O, but got Unknown
				AssemblyResolveEventHandler val = TypeLoader.m_AssemblyResolve;
				AssemblyResolveEventHandler val2;
				do
				{
					val2 = val;
					AssemblyResolveEventHandler value2 = (AssemblyResolveEventHandler)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref TypeLoader.m_AssemblyResolve, value2, val2);
				}
				while (val != val2);
			}
		}

		static TypeLoader()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//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_003e: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			EnableAssemblyCache = ConfigFile.CoreConfig.Bind("Caching", "EnableAssemblyCache", defaultValue: true, "Enable/disable assembly metadata cache\nEnabling this will speed up discovery of plugins and patchers by caching the metadata of all types BepInEx discovers.");
			Resolver = new DefaultAssemblyResolver();
			ReaderParameters = new ReaderParameters
			{
				AssemblyResolver = (IAssemblyResolver)(object)Resolver
			};
			((BaseAssemblyResolver)Resolver).ResolveFailure += (AssemblyResolveEventHandler)delegate(object sender, AssemblyNameReference reference)
			{
				if (!Utility.TryParseAssemblyName(reference.FullName, out var assemblyName))
				{
					AssemblyResolveEventHandler assemblyResolve = TypeLoader.AssemblyResolve;
					if (assemblyResolve == null)
					{
						return null;
					}
					return assemblyResolve.Invoke(sender, reference);
				}
				foreach (string item in new string[3]
				{
					Paths.BepInExAssemblyDirectory,
					Paths.PluginPath,
					Paths.PatcherPluginPath
				}.Concat(Paths.DllSearchPaths))
				{
					if (Utility.TryResolveDllAssembly(assemblyName, item, ReaderParameters, out var assembly))
					{
						return assembly;
					}
				}
				AssemblyResolveEventHandler assemblyResolve2 = TypeLoader.AssemblyResolve;
				return (assemblyResolve2 == null) ? null : assemblyResolve2.Invoke(sender, reference);
			};
		}

		public static Dictionary<string, List<T>> FindPluginTypes<T>(string directory, Func<TypeDefinition, T> typeSelector, Func<AssemblyDefinition, bool> assemblyFilter = null, string cacheName = null) where T : ICacheable, new()
		{
			Dictionary<string, List<T>> dictionary = new Dictionary<string, List<T>>();
			Dictionary<string, CachedAssembly<T>> dictionary2 = null;
			if (cacheName != null)
			{
				dictionary2 = LoadAssemblyCache<T>(cacheName);
			}
			string[] files = Directory.GetFiles(Path.GetFullPath(directory), "*.dll", SearchOption.AllDirectories);
			foreach (string text in files)
			{
				try
				{
					if (dictionary2 != null && dictionary2.TryGetValue(text, out var value) && File.GetLastWriteTimeUtc(text).Ticks == value.Timestamp)
					{
						dictionary[text] = value.CacheItems;
						continue;
					}
					AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text, ReaderParameters);
					if (assemblyFilter != null && !assemblyFilter(val))
					{
						dictionary[text] = new List<T>();
						val.Dispose();
						continue;
					}
					List<T> value2 = (from t in ((IEnumerable<TypeDefinition>)val.MainModule.Types).Select(typeSelector)
						where t != null
						select t).ToList();
					dictionary[text] = value2;
					val.Dispose();
				}
				catch (BadImageFormatException ex)
				{
					Logger.LogDebug("Skipping loading " + text + " because it's not a valid .NET assembly. Full error: " + ex.Message);
				}
				catch (Exception ex2)
				{
					Logger.LogError(ex2.ToString());
				}
			}
			if (cacheName != null)
			{
				SaveAssemblyCache(cacheName, dictionary);
			}
			return dictionary;
		}

		public static Dictionary<string, CachedAssembly<T>> LoadAssemblyCache<T>(string cacheName) where T : ICacheable, new()
		{
			if (!EnableAssemblyCache.Value)
			{
				return null;
			}
			Dictionary<string, CachedAssembly<T>> dictionary = new Dictionary<string, CachedAssembly<T>>();
			try
			{
				string path = Path.Combine(Paths.CachePath, cacheName + "_typeloader.dat");
				if (!File.Exists(path))
				{
					return null;
				}
				using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path));
				int num = binaryReader.ReadInt32();
				for (int i = 0; i < num; i++)
				{
					string key = binaryReader.ReadString();
					long timestamp = binaryReader.ReadInt64();
					int num2 = binaryReader.ReadInt32();
					List<T> list = new List<T>();
					for (int j = 0; j < num2; j++)
					{
						T item = new T();
						item.Load(binaryReader);
						list.Add(item);
					}
					dictionary[key] = new CachedAssembly<T>
					{
						Timestamp = timestamp,
						CacheItems = list
					};
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning("Failed to load cache \"" + cacheName + "\"; skipping loading cache. Reason: " + ex.Message + ".");
			}
			return dictionary;
		}

		public static void SaveAssemblyCache<T>(string cacheName, Dictionary<string, List<T>> entries) where T : ICacheable
		{
			if (!EnableAssemblyCache.Value)
			{
				return;
			}
			try
			{
				if (!Directory.Exists(Paths.CachePath))
				{
					Directory.CreateDirectory(Paths.CachePath);
				}
				using BinaryWriter binaryWriter = new BinaryWriter(File.OpenWrite(Path.Combine(Paths.CachePath, cacheName + "_typeloader.dat")));
				binaryWriter.Write(entries.Count);
				foreach (KeyValuePair<string, List<T>> entry in entries)
				{
					binaryWriter.Write(entry.Key);
					binaryWriter.Write(File.GetLastWriteTimeUtc(entry.Key).Ticks);
					binaryWriter.Write(entry.Value.Count);
					foreach (T item in entry.Value)
					{
						item.Save(binaryWriter);
					}
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning("Failed to save cache \"" + cacheName + "\"; skipping saving cache. Reason: " + ex.Message + ".");
			}
		}

		public static string TypeLoadExceptionToString(ReflectionTypeLoadException ex)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Exception[] loaderExceptions = ex.LoaderExceptions;
			foreach (Exception ex2 in loaderExceptions)
			{
				stringBuilder.AppendLine(ex2.Message);
				if (ex2 is FileNotFoundException ex3)
				{
					if (!string.IsNullOrEmpty(ex3.FusionLog))
					{
						stringBuilder.AppendLine("Fusion Log:");
						stringBuilder.AppendLine(ex3.FusionLog);
					}
				}
				else if (ex2 is FileLoadException ex4 && !string.IsNullOrEmpty(ex4.FusionLog))
				{
					stringBuilder.AppendLine("Fusion Log:");
					stringBuilder.AppendLine(ex4.FusionLog);
				}
				stringBuilder.AppendLine();
			}
			return stringBuilder.ToString();
		}
	}
}
namespace BepInEx.ConsoleUtil
{
	internal class Kon
	{
		private struct CONSOLE_SCREEN_BUFFER_INFO
		{
			internal COORD dwSize;

			internal COORD dwCursorPosition;

			internal short wAttributes;

			internal SMALL_RECT srWindow;

			internal COORD dwMaximumWindowSize;
		}

		private struct COORD
		{
			internal short X;

			internal short Y;
		}

		private struct SMALL_RECT
		{
			internal short Left;

			internal short Top;

			internal short Right;

			internal short Bottom;
		}

		private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);

		internal static IntPtr conOut = IntPtr.Zero;

		public static ConsoleColor ForegroundColor
		{
			get
			{
				return GetConsoleColor(isBackground: false);
			}
			set
			{
				SetConsoleColor(isBackground: false, value);
			}
		}

		public static ConsoleColor BackgroundColor
		{
			get
			{
				return GetConsoleColor(isBackground: true);
			}
			set
			{
				SetConsoleColor(isBackground: true, value);
			}
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, short attributes);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr GetStdHandle(int nStdHandle);

		private static short ConsoleColorToColorAttribute(sh

BepInEx/core/BepInEx.Harmony.dll

Decompiled 8 months ago
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BepInEx.Harmony")]
[assembly: AssemblyDescription("Harmony wrapper for BepInEx")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BepInEx.Harmony")]
[assembly: AssemblyCopyright("Copyright © Bepis 2019")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("54161cfe-ff42-4dde-b161-3a49545db5cd")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyVersion("2.0.0.0")]
namespace BepInEx.Harmony;

[AttributeUsage(AttributeTargets.Method)]
[Obsolete("Use HarmonyLib.ParameterByRefAttribute directly", true)]
public class ParameterByRefAttribute : ParameterByRefAttribute
{
	public int[] ParameterIndices => ((ParameterByRefAttribute)this).ParameterIndices;

	public ParameterByRefAttribute(params int[] parameterIndices)
		: base(parameterIndices)
	{
	}
}
public static class HarmonyExtensions
{
	[Obsolete("Use HarmonyLib.Harmony.PatchAll directly", true)]
	public static void PatchAll(this Harmony harmonyInstance, Type type)
	{
		HarmonyWrapper.PatchAll(type, harmonyInstance);
	}
}
public class HarmonyWrapper
{
	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll or HarmonyLib.Harmony.PatchAll", true)]
	public static Harmony PatchAll(Type type, Harmony harmonyInstance = null)
	{
		if (harmonyInstance == null)
		{
			return Harmony.CreateAndPatchAll(type, (string)null);
		}
		harmonyInstance.PatchAll(type);
		return harmonyInstance;
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll", true)]
	public static Harmony PatchAll(Type type, string harmonyInstanceId)
	{
		return Harmony.CreateAndPatchAll(type, harmonyInstanceId);
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll or HarmonyLib.Harmony.PatchAll", true)]
	public static Harmony PatchAll(Assembly assembly, Harmony harmonyInstance = null)
	{
		return assembly.GetTypes().Aggregate(harmonyInstance, (Harmony current, Type type) => PatchAll(type, current));
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll", true)]
	public static Harmony PatchAll(Assembly assembly, string harmonyInstanceId)
	{
		return Harmony.CreateAndPatchAll(assembly, harmonyInstanceId);
	}

	[Obsolete("Use HarmonyLib.Harmony.PatchAll with no arguments", true)]
	public static Harmony PatchAll(Harmony harmonyInstance = null)
	{
		return PatchAll(Assembly.GetCallingAssembly(), harmonyInstance);
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), ...)", true)]
	public static Harmony PatchAll(string harmonyInstanceId)
	{
		return PatchAll(Assembly.GetCallingAssembly(), harmonyInstanceId);
	}

	[Obsolete("Use HarmonyLib.Transpilers.EmitDelegate instead", true)]
	public static CodeInstruction EmitDelegate<T>(T action) where T : Delegate
	{
		return Transpilers.EmitDelegate<T>(action);
	}
}

BepInEx/core/BepInEx.Preloader.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Preloader.Patching;
using BepInEx.Preloader.RuntimeFixes;
using HarmonyLib;
using HarmonyXInterop;
using Mono.Cecil;
using Mono.Cecil.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.RuntimeDetour.Platforms;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BepInEx.Preloader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BepInEx.Preloader")]
[assembly: AssemblyCopyright("Copyright ©  2019")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f7abbe07-c02f-4f7c-bf6e-c6656bf588ca")]
[assembly: AssemblyFileVersion("5.4.22.0")]
[assembly: AssemblyVersion("5.4.22.0")]
namespace BepInEx.Preloader
{
	public static class EnvVars
	{
		public static string DOORSTOP_INVOKE_DLL_PATH { get; private set; }

		public static string DOORSTOP_MANAGED_FOLDER_DIR { get; private set; }

		public static string DOORSTOP_PROCESS_PATH { get; private set; }

		public static string[] DOORSTOP_DLL_SEARCH_DIRS { get; private set; }

		internal static void LoadVars()
		{
			DOORSTOP_INVOKE_DLL_PATH = Environment.GetEnvironmentVariable("DOORSTOP_INVOKE_DLL_PATH");
			DOORSTOP_MANAGED_FOLDER_DIR = Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR");
			DOORSTOP_PROCESS_PATH = Environment.GetEnvironmentVariable("DOORSTOP_PROCESS_PATH");
			DOORSTOP_DLL_SEARCH_DIRS = Environment.GetEnvironmentVariable("DOORSTOP_DLL_SEARCH_DIRS")?.Split(new char[1] { Path.PathSeparator }) ?? new string[0];
		}
	}
	internal static class PreloaderRunner
	{
		private static readonly string[] CriticalAssemblies = new string[7] { "Mono.Cecil.dll", "Mono.Cecil.Mdb.dll", "Mono.Cecil.Pdb.dll", "Mono.Cecil.Rocks.dll", "MonoMod.Utils.dll", "MonoMod.RuntimeDetour.dll", "0Harmony.dll" };

		private static void LoadCriticalAssemblies()
		{
			string[] criticalAssemblies = CriticalAssemblies;
			foreach (string path in criticalAssemblies)
			{
				try
				{
					Assembly.LoadFile(Path.Combine(Paths.BepInExAssemblyDirectory, path));
				}
				catch (Exception)
				{
				}
			}
		}

		public static void PreloaderPreMain()
		{
			PlatformUtils.SetPlatform();
			string text = Utility.ParentDirectory(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH), 2);
			Paths.SetExecutablePath(EnvVars.DOORSTOP_PROCESS_PATH, text, EnvVars.DOORSTOP_MANAGED_FOLDER_DIR, EnvVars.DOORSTOP_DLL_SEARCH_DIRS);
			LoadCriticalAssemblies();
			AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
			AppDomain.CurrentDomain.AssemblyResolve -= Entrypoint.ResolveCurrentDirectory;
			PreloaderMain();
		}

		private static void PreloaderMain()
		{
			if (Preloader.ConfigApplyRuntimePatches.Value)
			{
				XTermFix.Apply();
				ConsoleSetOutFix.Apply();
			}
			Preloader.Run();
		}

		private static Assembly LocalResolve(object sender, ResolveEventArgs args)
		{
			AssemblyName assemblyName = default(AssemblyName);
			if (!Utility.TryParseAssemblyName(args.Name, ref assemblyName))
			{
				return null;
			}
			AssemblyName assemblyName2 = default(AssemblyName);
			var source = (from a in AppDomain.CurrentDomain.GetAssemblies()
				select new
				{
					assembly = a,
					name = (Utility.TryParseAssemblyName(a.FullName, ref assemblyName2) ? assemblyName2 : null)
				} into a
				where a.name != null && a.name.Name == assemblyName.Name
				orderby a.name.Version descending
				select a).ToList();
			Assembly assembly = (source.FirstOrDefault(a => a.name.Version == assemblyName.Version) ?? source.FirstOrDefault())?.assembly;
			if ((object)assembly != null)
			{
				return assembly;
			}
			if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, ref assembly) || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, ref assembly) || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, ref assembly))
			{
				return assembly;
			}
			return null;
		}
	}
	internal static class Entrypoint
	{
		private static string preloaderPath;

		public static void Main()
		{
			string text = $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log";
			try
			{
				EnvVars.LoadVars();
				text = Path.Combine(Path.GetDirectoryName(EnvVars.DOORSTOP_PROCESS_PATH) ?? ".", text);
				preloaderPath = Path.GetDirectoryName(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH));
				AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory;
				typeof(Entrypoint).Assembly.GetType("BepInEx.Preloader.PreloaderRunner")?.GetMethod("PreloaderPreMain")?.Invoke(null, null);
			}
			catch (Exception ex)
			{
				File.WriteAllText(text, ex.ToString());
			}
			finally
			{
				AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory;
			}
		}

		internal static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args)
		{
			AssemblyName assemblyName = new AssemblyName(args.Name);
			try
			{
				return Assembly.LoadFile(Path.Combine(preloaderPath, assemblyName.Name + ".dll"));
			}
			catch (Exception)
			{
				return null;
			}
		}
	}
	internal static class PlatformUtils
	{
		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct utsname_osx
		{
			private const int osx_utslen = 256;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string sysname;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string nodename;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string release;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string version;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string machine;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct utsname_linux
		{
			private const int linux_utslen = 65;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string sysname;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string nodename;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string release;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string version;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string machine;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string domainname;
		}

		[DllImport("libc.so.6", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")]
		private static extern IntPtr uname_linux(ref utsname_linux utsname);

		[DllImport("/usr/lib/libSystem.dylib", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")]
		private static extern IntPtr uname_osx(ref utsname_osx utsname);

		public static void SetPlatform()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			Platform val = (Platform)17;
			PropertyInfo property = typeof(Environment).GetProperty("Platform", BindingFlags.Static | BindingFlags.NonPublic);
			string text = (((object)property == null) ? Environment.OSVersion.Platform.ToString() : property.GetValue(null, new object[0]).ToString());
			text = text.ToLowerInvariant();
			if (text.Contains("win"))
			{
				val = (Platform)37;
			}
			else if (text.Contains("mac") || text.Contains("osx"))
			{
				val = (Platform)73;
			}
			else if (text.Contains("lin") || text.Contains("unix"))
			{
				val = (Platform)137;
			}
			if (Is(val, (Platform)137) && Directory.Exists("/data") && File.Exists("/system/build.prop"))
			{
				val = (Platform)393;
			}
			else if (Is(val, (Platform)8) && Directory.Exists("/System/Library/AccessibilityBundles"))
			{
				val = (Platform)585;
			}
			MethodInfo methodInfo = typeof(Environment).GetProperty("Is64BitOperatingSystem")?.GetGetMethod();
			val = (Platform)(((object)methodInfo == null) ? (val | ((IntPtr.Size >= 8) ? 2 : 0)) : (val | (((bool)methodInfo.Invoke(null, new object[0])) ? 2 : 0)));
			if ((Is(val, (Platform)73) || Is(val, (Platform)137)) && (object)Type.GetType("Mono.Runtime") != null)
			{
				IntPtr intPtr;
				string machine;
				if (Is(val, (Platform)73))
				{
					utsname_osx utsname = default(utsname_osx);
					intPtr = uname_osx(ref utsname);
					machine = utsname.machine;
				}
				else
				{
					utsname_linux utsname2 = default(utsname_linux);
					intPtr = uname_linux(ref utsname2);
					machine = utsname2.machine;
				}
				if (intPtr == IntPtr.Zero && (machine.StartsWith("aarch") || machine.StartsWith("arm")))
				{
					val = (Platform)(val | 0x10000);
				}
			}
			else
			{
				typeof(object).Module.GetPEKind(out var _, out var machine2);
				if (machine2 == ImageFileMachine.ARM)
				{
					val = (Platform)(val | 0x10000);
				}
			}
			PlatformHelper.Current = val;
		}

		private static bool Is(Platform current, Platform expected)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return (Platform)(current & expected) == expected;
		}
	}
	internal static class Preloader
	{
		private enum MonoModBackend
		{
			[Description("Auto")]
			auto,
			[Description("DynamicMethod")]
			dynamicmethod,
			[Description("MethodBuilder")]
			methodbuilder,
			[Description("Cecil")]
			cecil
		}

		private static readonly ConfigEntry<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Assembly", IsPostUnity2017 ? "UnityEngine.CoreModule.dll" : "UnityEngine.dll", "The local filename of the assembly to target.");

		private static readonly ConfigEntry<string> ConfigEntrypointType = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Type", "Application", "The name of the type in the entrypoint assembly to search for the entrypoint method.");

		private static readonly ConfigEntry<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Method", ".cctor", "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from.");

		internal static readonly ConfigEntry<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Bind<bool>("Preloader", "ApplyRuntimePatches", true, "Enables or disables runtime patches.\nThis should always be true, unless you cannot start the game due to a Harmony related issue (such as running .NET Standard runtime) or you know what you're doing.");

		private static readonly ConfigEntry<MonoModBackend> HarmonyBackend = ConfigFile.CoreConfig.Bind<MonoModBackend>("Preloader", "HarmonyBackend", MonoModBackend.auto, "Specifies which MonoMod backend to use for Harmony patches. Auto uses the best available backend.\nThis setting should only be used for development purposes (e.g. debugging in dnSpy). Other code might override this setting.");

		private static PreloaderConsoleListener PreloaderLog { get; set; }

		public static bool IsPostUnity2017 { get; } = File.Exists(Path.Combine(Paths.ManagedPath, "UnityEngine.CoreModule.dll"));


		public static void Run()
		{
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				InitializeHarmony();
				HarmonyInteropFix.Apply();
				ConsoleManager.Initialize(false);
				AllocateConsole();
				Exception ex = default(Exception);
				Utility.TryDo((Action)delegate
				{
					if (ConfigApplyRuntimePatches.Value)
					{
						UnityPatches.Apply();
					}
				}, ref ex);
				Logger.InitializeInternalLoggers();
				Logger.Sources.Add(TraceLogSource.CreateSource());
				PreloaderLog = new PreloaderConsoleListener();
				Logger.Listeners.Add((ILogListener)(object)PreloaderLog);
				Version version = typeof(Paths).Assembly.GetName().Version;
				string text = $"BepInEx {version} - {Paths.ProcessName}";
				if (ConsoleManager.ConsoleActive)
				{
					ConsoleManager.SetConsoleTitle(text);
				}
				Logger.LogMessage((object)$"{text} ({File.GetLastWriteTime(Paths.ExecutablePath)})");
				object[] customAttributes = typeof(BuildInfoAttribute).Assembly.GetCustomAttributes(typeof(BuildInfoAttribute), inherit: false);
				if (customAttributes.Length != 0)
				{
					Logger.LogMessage((object)((BuildInfoAttribute)customAttributes[0]).Info);
				}
				Logger.LogInfo((object)("Running under Unity v" + GetUnityVersion()));
				Logger.LogInfo((object)$"CLR runtime version: {Environment.Version}");
				Logger.LogInfo((object)$"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}");
				Logger.LogInfo((object)$"System platform: {PlatformHelper.Current}");
				if (ex != null)
				{
					Logger.LogWarning((object)("Failed to apply runtime patches for Mono. See more info in the output log. Error message: " + ex.Message));
				}
				Logger.LogMessage((object)"Preloader started");
				AssemblyPatcher.AddPatcher(new PatcherPlugin
				{
					TargetDLLs = () => new string[1] { ConfigEntrypointAssembly.Value },
					Patcher = PatchEntrypoint,
					TypeName = "BepInEx.Chainloader"
				});
				Logger.Log((LogLevel)16, (object)$"Loaded 1 patcher method from [BepInEx.Preloader {version}]");
				AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath);
				Logger.LogInfo((object)string.Format("{0} patcher plugin{1} loaded", AssemblyPatcher.PatcherPlugins.Count, (AssemblyPatcher.PatcherPlugins.Count == 1) ? "" : "s"));
				AssemblyPatcher.PatchAndLoad(Paths.DllSearchPaths);
				AssemblyPatcher.DisposePatchers();
				Logger.LogMessage((object)"Preloader finished");
				Logger.Listeners.Remove((ILogListener)(object)PreloaderLog);
				PreloaderLog.Dispose();
			}
			catch (Exception ex2)
			{
				try
				{
					Logger.LogFatal((object)"Could not run preloader!");
					Logger.LogFatal((object)ex2);
					if (!ConsoleManager.ConsoleActive)
					{
						AllocateConsole();
						Console.Write(PreloaderLog);
					}
				}
				catch
				{
				}
				string text2 = string.Empty;
				try
				{
					text2 = string.Join("\r\n", PreloaderConsoleListener.LogEvents.Select((LogEventArgs x) => ((object)x).ToString()).ToArray());
					text2 += "\r\n";
					PreloaderLog?.Dispose();
					PreloaderLog = null;
				}
				catch
				{
				}
				File.WriteAllText(Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"), text2 + ex2);
			}
		}

		public static void PatchEntrypoint(ref AssemblyDefinition assembly)
		{
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Unknown result type (might be due to invalid IL or missing references)
			if (((IEnumerable<AssemblyNameReference>)assembly.MainModule.AssemblyReferences).Any((AssemblyNameReference x) => x.Name.Contains("BepInEx")))
			{
				throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
			}
			string entrypointType = ConfigEntrypointType.Value;
			string entrypointMethod = ConfigEntrypointMethod.Value;
			bool flag = Utility.IsNullOrWhiteSpace(entrypointMethod) || entrypointMethod == ".cctor";
			TypeDefinition val = ((IEnumerable<TypeDefinition>)assembly.MainModule.Types).FirstOrDefault((Func<TypeDefinition, bool>)((TypeDefinition x) => ((MemberReference)x).Name == entrypointType));
			if (val == null)
			{
				throw new Exception("The entrypoint type is invalid! Please check your config/BepInEx.cfg file");
			}
			AssemblyDefinition val2 = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath);
			try
			{
				MethodDefinition val3 = ((IEnumerable<MethodDefinition>)((IEnumerable<TypeDefinition>)val2.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).Name == "Chainloader").Methods).First((MethodDefinition x) => ((MemberReference)x).Name == "Initialize");
				MethodDefinition val4 = ((IEnumerable<MethodDefinition>)((IEnumerable<TypeDefinition>)val2.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).Name == "Chainloader").Methods).First((MethodDefinition x) => ((MemberReference)x).Name == "Start");
				MethodReference val5 = assembly.MainModule.ImportReference((MethodReference)(object)val3);
				MethodReference val6 = assembly.MainModule.ImportReference((MethodReference)(object)val4);
				List<MethodDefinition> list = new List<MethodDefinition>();
				if (flag)
				{
					MethodDefinition val7 = ((IEnumerable<MethodDefinition>)val.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => m.IsConstructor && m.IsStatic));
					if (val7 == null)
					{
						val7 = new MethodDefinition(".cctor", (MethodAttributes)6289, assembly.MainModule.ImportReference(typeof(void)));
						val.Methods.Add(val7);
						ILProcessor iLProcessor = val7.Body.GetILProcessor();
						iLProcessor.Append(iLProcessor.Create(OpCodes.Ret));
					}
					list.Add(val7);
				}
				else
				{
					list.AddRange(((IEnumerable<MethodDefinition>)val.Methods).Where((MethodDefinition x) => ((MemberReference)x).Name == entrypointMethod));
				}
				if (!list.Any())
				{
					throw new Exception("The entrypoint method is invalid! Please check your config.ini");
				}
				foreach (MethodDefinition item in list)
				{
					ILProcessor iLProcessor2 = item.Body.GetILProcessor();
					Instruction val8 = ((IEnumerable<Instruction>)iLProcessor2.Body.Instructions).First();
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Ldnull));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Ldc_I4_0));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, assembly.MainModule.ImportReference((MethodBase)AccessTools.PropertyGetter(typeof(PreloaderConsoleListener), "LogEvents"))));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, val5));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, val6));
				}
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}

		public static void AllocateConsole()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (!ConsoleManager.ConsoleEnabled)
			{
				return;
			}
			try
			{
				ConsoleManager.CreateConsole();
				Logger.Listeners.Add((ILogListener)new ConsoleLogListener());
			}
			catch (Exception ex)
			{
				Logger.LogError((object)"Failed to allocate console!");
				Logger.LogError((object)ex);
			}
		}

		public static string GetUnityVersion()
		{
			if (PlatformHelper.Is((Platform)37))
			{
				return FileVersionInfo.GetVersionInfo(Paths.ExecutablePath).FileVersion;
			}
			return "Unknown (" + (IsPostUnity2017 ? "post" : "pre") + "-2017)";
		}

		private static void InitializeHarmony()
		{
			switch (HarmonyBackend.Value)
			{
			case MonoModBackend.dynamicmethod:
			case MonoModBackend.methodbuilder:
			case MonoModBackend.cecil:
				Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", HarmonyBackend.Value.ToString());
				break;
			default:
				throw new ArgumentOutOfRangeException("HarmonyBackend", HarmonyBackend.Value, "Unknown backend");
			case MonoModBackend.auto:
				break;
			}
		}
	}
	public class PreloaderConsoleListener : ILogListener, IDisposable
	{
		private static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind<LogLevel>("Logging.Console", "LogLevels", (LogLevel)31, "Which log levels to show in the console output.");

		public static List<LogEventArgs> LogEvents { get; } = new List<LogEventArgs>();


		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if ((eventArgs.Level & ConfigConsoleDisplayedLevel.Value) != 0)
			{
				LogEvents.Add(eventArgs);
			}
		}

		public void Dispose()
		{
		}
	}
}
namespace BepInEx.Preloader.RuntimeFixes
{
	internal static class ConsoleSetOutFix
	{
		private static LoggedTextWriter loggedTextWriter;

		internal static ManualLogSource ConsoleLogSource = Logger.CreateLogSource("Console");

		public static void Apply()
		{
			loggedTextWriter = new LoggedTextWriter
			{
				Parent = Console.Out
			};
			Console.SetOut(loggedTextWriter);
			Harmony.CreateAndPatchAll(typeof(ConsoleSetOutFix), (string)null);
		}

		[HarmonyPatch(typeof(Console), "SetOut")]
		[HarmonyPrefix]
		private static bool OnSetOut(TextWriter newOut)
		{
			loggedTextWriter.Parent = newOut;
			return false;
		}
	}
	internal class LoggedTextWriter : TextWriter
	{
		public override Encoding Encoding { get; } = Encoding.UTF8;


		public TextWriter Parent { get; set; }

		public override void Flush()
		{
			Parent.Flush();
		}

		public override void Write(string value)
		{
			ConsoleSetOutFix.ConsoleLogSource.LogInfo((object)value);
			Parent.Write(value);
		}

		public override void WriteLine(string value)
		{
			ConsoleSetOutFix.ConsoleLogSource.LogInfo((object)value);
			Parent.WriteLine(value);
		}
	}
	internal static class HarmonyInteropFix
	{
		public static void Apply()
		{
			HarmonyInterop.Initialize(Paths.CachePath);
			Harmony.CreateAndPatchAll(typeof(HarmonyInteropFix), "org.bepinex.fixes.harmonyinterop");
		}

		[HarmonyReversePatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPatch(typeof(Assembly), "LoadFile", new Type[] { typeof(string) })]
		private static Assembly LoadFile(string path)
		{
			return null;
		}

		[HarmonyPatch(typeof(Assembly), "LoadFile", new Type[] { typeof(string) })]
		[HarmonyPatch(typeof(Assembly), "LoadFrom", new Type[] { typeof(string) })]
		[HarmonyPrefix]
		private static bool OnAssemblyLoad(ref Assembly __result, string __0)
		{
			HarmonyInterop.TryShim(__0, Paths.GameRootPath, (Action<string>)Logger.LogWarning, TypeLoader.ReaderParameters);
			__result = LoadFile(__0);
			return true;
		}
	}
	internal static class TraceFix
	{
		private static Type TraceImplType;

		private static object ListenersSyncRoot;

		private static TraceListenerCollection Listeners;

		private static PropertyInfo prop_AutoFlush;

		private static bool AutoFlush => (bool)prop_AutoFlush.GetValue(null, null);

		public static void ApplyFix()
		{
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			TraceImplType = AppDomain.CurrentDomain.GetAssemblies().First((Assembly x) => x.GetName().Name == "System").GetTypes()
				.FirstOrDefault((Type x) => x.Name == "TraceImpl");
			if ((object)TraceImplType != null)
			{
				ListenersSyncRoot = AccessTools.Property(TraceImplType, "ListenersSyncRoot").GetValue(null, null);
				Listeners = (TraceListenerCollection)AccessTools.Property(TraceImplType, "Listeners").GetValue(null, null);
				prop_AutoFlush = AccessTools.Property(TraceImplType, "AutoFlush");
				new Harmony("com.bepis.bepinex.tracefix").Patch((MethodBase)typeof(Trace).GetMethod("DoTrace", BindingFlags.Static | BindingFlags.NonPublic), new HarmonyMethod(typeof(TraceFix).GetMethod("DoTraceReplacement", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool DoTraceReplacement(string kind, Assembly report, string message)
		{
			string source = string.Empty;
			try
			{
				source = report.GetName().Name;
			}
			catch (MethodAccessException)
			{
			}
			TraceEventType eventType = (TraceEventType)Enum.Parse(typeof(TraceEventType), kind);
			lock (ListenersSyncRoot)
			{
				foreach (TraceListener listener in Listeners)
				{
					listener.TraceEvent(new TraceEventCache(), source, eventType, 0, message);
					if (AutoFlush)
					{
						listener.Flush();
					}
				}
			}
			return false;
		}
	}
	internal static class UnityPatches
	{
		private static Harmony HarmonyInstance { get; set; }

		public static Dictionary<string, string> AssemblyLocations { get; } = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);


		public static void Apply()
		{
			HarmonyInstance = Harmony.CreateAndPatchAll(typeof(UnityPatches), (string)null);
			try
			{
				TraceFix.ApplyFix();
			}
			catch
			{
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		public static void GetLocation(ref string __result, Assembly __instance)
		{
			if (AssemblyLocations.TryGetValue(__instance.FullName, out var value))
			{
				__result = value;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		public static void GetCodeBase(ref string __result, Assembly __instance)
		{
			if (AssemblyLocations.TryGetValue(__instance.FullName, out var value))
			{
				__result = "file://" + value.Replace('\\', '/');
			}
		}
	}
	internal static class XTermFix
	{
		public static int intOffset;

		public static void Apply()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Expected O, but got Unknown
			if (!PlatformHelper.Is((Platform)37) && (object)typeof(Console).Assembly.GetType("System.ConsoleDriver") != null && (object)AccessTools.Method("System.TermInfoReader:DetermineVersion", (Type[])null, (Type[])null) == null)
			{
				DetourHelper.Native = (IDetourNativePlatform)new DetourNativeX86Platform();
				Harmony val = new Harmony("com.bepinex.xtermfix");
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:ReadHeader", (Type[])null, (Type[])null), new HarmonyMethod(typeof(XTermFix), "ReadHeaderPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoNumbers") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoNumbersTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:GetStringBytes", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				DetourHelper.Native = null;
			}
		}

		public static int GetInt32(byte[] buffer, int offset)
		{
			byte num = buffer[offset];
			int num2 = buffer[offset + 1];
			int num3 = buffer[offset + 2];
			int num4 = buffer[offset + 3];
			return num | (num2 << 8) | (num3 << 16) | (num4 << 24);
		}

		public static short GetInt16(byte[] buffer, int offset)
		{
			byte num = buffer[offset];
			int num2 = buffer[offset + 1];
			return (short)(num | (num2 << 8));
		}

		public static int GetInteger(byte[] buffer, int offset)
		{
			if (intOffset != 2)
			{
				return GetInt32(buffer, offset);
			}
			return GetInt16(buffer, offset);
		}

		public static void DetermineVersion(short magic)
		{
			switch (magic)
			{
			case 282:
				intOffset = 2;
				break;
			case 542:
				intOffset = 4;
				break;
			default:
				throw new Exception($"Unknown xterm header format: {magic}");
			}
		}

		public static bool ReadHeaderPrefix(byte[] buffer, ref int position, ref short ___boolSize, ref short ___numSize, ref short ___strOffsets)
		{
			short @int = GetInt16(buffer, position);
			position += 2;
			DetermineVersion(@int);
			position += 2;
			___boolSize = GetInt16(buffer, position);
			position += 2;
			___numSize = GetInt16(buffer, position);
			position += 2;
			___strOffsets = GetInt16(buffer, position);
			position += 2;
			position += 2;
			return false;
		}

		public static IEnumerable<CodeInstruction> GetTermInfoNumbersTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			List<CodeInstruction> list = instructions.ToList();
			list[31] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset"));
			list[36] = new CodeInstruction(OpCodes.Nop, (object)null);
			list[39] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(XTermFix), "GetInteger", (Type[])null, (Type[])null));
			return list;
		}

		public static IEnumerable<CodeInstruction> GetTermInfoStringsTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			List<CodeInstruction> list = instructions.ToList();
			list[32] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset"));
			return list;
		}
	}
}
namespace BepInEx.Preloader.Patching
{
	public delegate void AssemblyPatcherDelegate(ref AssemblyDefinition assembly);
	public static class AssemblyPatcher
	{
		private const BindingFlags ALL = BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly string DumpedAssembliesPath = Utility.CombinePaths(new string[3]
		{
			Paths.BepInExRootPath,
			"DumpedAssemblies",
			Paths.ProcessName
		});

		private static readonly Dictionary<string, string> DumpedAssemblyPaths = new Dictionary<string, string>();

		private static readonly ConfigEntry<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "DumpAssemblies", false, "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.");

		private static readonly ConfigEntry<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "LoadDumpedAssemblies", false, "If enabled, BepInEx will load patched assemblies from BepInEx/DumpedAssemblies instead of memory.\nThis can be used to be able to load patched assemblies into debuggers like dnSpy.\nIf set to true, will override DumpAssemblies.");

		private static readonly ConfigEntry<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "BreakBeforeLoadAssemblies", false, "If enabled, BepInEx will call Debugger.Break() once before loading patched assemblies.\nThis can be used with debuggers like dnSpy to install breakpoints into patched assemblies before they are loaded.");

		public static List<PatcherPlugin> PatcherPlugins { get; } = new List<PatcherPlugin>();


		private static IEnumerable<PatcherPlugin> PatcherPluginsSafe => PatcherPlugins.ToList();

		public static void AddPatcher(PatcherPlugin patcher)
		{
			PatcherPlugins.Add(patcher);
		}

		private static T CreateDelegate<T>(MethodInfo method) where T : class
		{
			if ((object)method == null)
			{
				return null;
			}
			return Delegate.CreateDelegate(typeof(T), method) as T;
		}

		private static PatcherPlugin ToPatcherPlugin(TypeDefinition type)
		{
			if (type.IsInterface || (type.IsAbstract && !type.IsSealed))
			{
				return null;
			}
			MethodDefinition val = ((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name.Equals("get_TargetDLLs", StringComparison.InvariantCultureIgnoreCase) && m.IsPublic && m.IsStatic));
			if (val == null || ((MemberReference)((MethodReference)val).ReturnType).FullName != "System.Collections.Generic.IEnumerable`1<System.String>")
			{
				return null;
			}
			if (((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name.Equals("Patch") && m.IsPublic && m.IsStatic && ((MemberReference)((MethodReference)m).ReturnType).FullName == "System.Void" && ((MethodReference)m).Parameters.Count == 1 && (((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).FullName == "Mono.Cecil.AssemblyDefinition&" || ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).FullName == "Mono.Cecil.AssemblyDefinition"))) == null)
			{
				return null;
			}
			return new PatcherPlugin
			{
				TypeName = ((MemberReference)type).FullName
			};
		}

		public static void AddPatchersFromDirectory(string directory)
		{
			if (!Directory.Exists(directory))
			{
				return;
			}
			SortedDictionary<string, PatcherPlugin> sortedDictionary = new SortedDictionary<string, PatcherPlugin>();
			foreach (KeyValuePair<string, List<PatcherPlugin>> item in TypeLoader.FindPluginTypes<PatcherPlugin>(directory, (Func<TypeDefinition, PatcherPlugin>)ToPatcherPlugin, (Func<AssemblyDefinition, bool>)null, (string)null))
			{
				string key = item.Key;
				List<PatcherPlugin> value = item.Value;
				if (value.Count == 0)
				{
					continue;
				}
				Assembly assembly = Assembly.LoadFile(key);
				foreach (PatcherPlugin item2 in value)
				{
					try
					{
						Type type = assembly.GetType(item2.TypeName);
						MethodInfo[] methods = type.GetMethods(BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
						item2.Initializer = CreateDelegate<Action>(methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Initialize", StringComparison.InvariantCultureIgnoreCase) && m.GetParameters().Length == 0 && (object)m.ReturnType == typeof(void)));
						item2.Finalizer = CreateDelegate<Action>(methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Finish", StringComparison.InvariantCultureIgnoreCase) && m.GetParameters().Length == 0 && (object)m.ReturnType == typeof(void)));
						item2.TargetDLLs = CreateDelegate<Func<IEnumerable<string>>>(type.GetProperty("TargetDLLs", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod());
						MethodInfo patcher = methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Patch", StringComparison.CurrentCultureIgnoreCase) && (object)m.ReturnType == typeof(void) && m.GetParameters().Length == 1 && ((object)m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition) || (object)m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition).MakeByRefType()));
						item2.Patcher = delegate(ref AssemblyDefinition pAss)
						{
							//IL_001e: Unknown result type (might be due to invalid IL or missing references)
							//IL_0024: Expected O, but got Unknown
							object[] array = new object[1] { pAss };
							patcher.Invoke(null, array);
							pAss = (AssemblyDefinition)array[0];
						};
						sortedDictionary.Add(assembly.GetName().Name + "/" + type.FullName, item2);
					}
					catch (Exception ex)
					{
						Logger.LogError((object)("Failed to load patcher [" + item2.TypeName + "]: " + ex.Message));
						if (ex is ReflectionTypeLoadException ex2)
						{
							Logger.LogDebug((object)TypeLoader.TypeLoadExceptionToString(ex2));
						}
						else
						{
							Logger.LogDebug((object)ex.ToString());
						}
					}
				}
				AssemblyName name = assembly.GetName();
				Logger.Log((LogLevel)(value.Any() ? 16 : 32), (object)string.Format("Loaded {0} patcher method{1} from [{2} {3}]", value.Count, (value.Count == 1) ? "" : "s", name.Name, name.Version));
			}
			foreach (KeyValuePair<string, PatcherPlugin> item3 in sortedDictionary)
			{
				AddPatcher(item3.Value);
			}
		}

		private static void InitializePatchers()
		{
			foreach (PatcherPlugin item in PatcherPluginsSafe)
			{
				try
				{
					item.Initializer?.Invoke();
				}
				catch (Exception arg)
				{
					Logger.LogError((object)$"Failed to run Initializer of {item.TypeName}: {arg}");
				}
			}
		}

		private static void FinalizePatching()
		{
			foreach (PatcherPlugin item in PatcherPluginsSafe)
			{
				try
				{
					item.Finalizer?.Invoke();
				}
				catch (Exception arg)
				{
					Logger.LogError((object)$"Failed to run Finalizer of {item.TypeName}: {arg}");
				}
			}
		}

		public static void DisposePatchers()
		{
			PatcherPlugins.Clear();
		}

		private static string GetAssemblyName(string fullName)
		{
			AssemblyName assemblyName = default(AssemblyName);
			if (!Utility.TryParseAssemblyName(fullName, ref assemblyName))
			{
				return fullName;
			}
			return assemblyName.Name;
		}

		public static void PatchAndLoad(params string[] directories)
		{
			Dictionary<string, AssemblyDefinition> dictionary = new Dictionary<string, AssemblyDefinition>(StringComparer.InvariantCultureIgnoreCase);
			foreach (string uniqueFilesInDirectory in Utility.GetUniqueFilesInDirectories((IEnumerable<string>)directories, "*.dll"))
			{
				AssemblyDefinition val;
				try
				{
					val = AssemblyDefinition.ReadAssembly(uniqueFilesInDirectory);
				}
				catch (BadImageFormatException)
				{
					continue;
				}
				if (((AssemblyNameReference)val.Name).Name == "System" || ((AssemblyNameReference)val.Name).Name == "mscorlib")
				{
					val.Dispose();
					continue;
				}
				if (UnityPatches.AssemblyLocations.ContainsKey(val.FullName))
				{
					Logger.LogWarning((object)("Tried to load duplicate assembly " + Path.GetFileName(uniqueFilesInDirectory) + " from Managed folder! Skipping..."));
					continue;
				}
				dictionary.Add(Path.GetFileName(uniqueFilesInDirectory), val);
				UnityPatches.AssemblyLocations.Add(val.FullName, Path.GetFullPath(uniqueFilesInDirectory));
			}
			InitializePatchers();
			HashSet<string> patchedAssemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
			Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
			HashSet<string> hashSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
			foreach (PatcherPlugin item in PatcherPluginsSafe)
			{
				foreach (string item2 in item.TargetDLLs())
				{
					if (!dictionary.TryGetValue(item2, out var value) || hashSet.Contains(item2))
					{
						continue;
					}
					Logger.LogInfo((object)("Patching [" + ((AssemblyNameReference)value.Name).Name + "] with [" + item.TypeName + "]"));
					try
					{
						item.Patcher?.Invoke(ref value);
					}
					catch (Exception arg)
					{
						Logger.LogError((object)$"Failed to run [{item.TypeName}] when patching [{((AssemblyNameReference)value.Name).Name}]. This assembly will not be patched. Error: {arg}");
						patchedAssemblies.Remove(item2);
						hashSet.Add(item2);
						continue;
					}
					dictionary[item2] = value;
					patchedAssemblies.Add(item2);
					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
					for (int i = 0; i < assemblies.Length; i++)
					{
						string assemblyName = GetAssemblyName(assemblies[i].FullName);
						if (!dictionary2.ContainsKey(assemblyName))
						{
							dictionary2[assemblyName] = item.TypeName;
						}
					}
				}
			}
			HashSet<string> patchedAssemblyNames = new HashSet<string>(from kv in dictionary
				where patchedAssemblies.Contains(kv.Key)
				select ((AssemblyNameReference)kv.Value.Name).Name, StringComparer.InvariantCultureIgnoreCase);
			List<KeyValuePair<string, string>> list = dictionary2.Where((KeyValuePair<string, string> kv) => patchedAssemblyNames.Contains(kv.Key)).ToList();
			if (list.Count != 0)
			{
				Logger.LogWarning((object)new StringBuilder().AppendLine("The following assemblies have been loaded too early and will not be patched by preloader:").AppendLine(string.Join(Environment.NewLine, list.Select((KeyValuePair<string, string> kv) => "* [" + kv.Key + "] (first loaded by [" + kv.Value + "])").ToArray())).AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.")
					.ToString());
			}
			DumpedAssemblyPaths.Clear();
			if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value)
			{
				if (!Directory.Exists(DumpedAssembliesPath))
				{
					Directory.CreateDirectory(DumpedAssembliesPath);
				}
				FileStream fileStream = default(FileStream);
				foreach (KeyValuePair<string, AssemblyDefinition> item3 in dictionary)
				{
					string key = item3.Key;
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(key);
					string extension = Path.GetExtension(key);
					AssemblyDefinition value2 = item3.Value;
					if (!patchedAssemblies.Contains(key))
					{
						continue;
					}
					int num = 0;
					string text2;
					while (true)
					{
						string text = ((num > 0) ? $"_{num}" : "");
						text2 = Path.Combine(DumpedAssembliesPath, fileNameWithoutExtension + text + extension);
						if (Utility.TryOpenFileStream(text2, FileMode.Create, ref fileStream, FileAccess.ReadWrite, FileShare.Read))
						{
							break;
						}
						num++;
					}
					value2.Write((Stream)fileStream);
					fileStream.Dispose();
					DumpedAssemblyPaths[key] = text2;
				}
			}
			if (ConfigBreakBeforeLoadAssemblies.Value)
			{
				Logger.LogInfo((object)("BepInEx is about load the following assemblies:\n" + string.Join("\n", patchedAssemblies.ToArray())));
				Logger.LogInfo((object)("The assemblies were dumped into " + DumpedAssembliesPath));
				Logger.LogInfo((object)"Load any assemblies into the debugger, set breakpoints and continue execution.");
				Debugger.Break();
			}
			foreach (KeyValuePair<string, AssemblyDefinition> item4 in dictionary)
			{
				string key2 = item4.Key;
				AssemblyDefinition value3 = item4.Value;
				if (patchedAssemblies.Contains(key2))
				{
					Load(value3, key2);
				}
				value3.Dispose();
			}
			FinalizePatching();
		}

		public static void Load(AssemblyDefinition assembly, string filename)
		{
			if (ConfigLoadDumpedAssemblies.Value && DumpedAssemblyPaths.TryGetValue(filename, out var value))
			{
				Assembly.LoadFile(value);
				return;
			}
			using MemoryStream memoryStream = new MemoryStream();
			assembly.Write((Stream)memoryStream);
			Assembly.Load(memoryStream.ToArray());
		}
	}
	public class PatcherPlugin : ICacheable
	{
		public Func<IEnumerable<string>> TargetDLLs { get; set; }

		public Action Initializer { get; set; }

		public Action Finalizer { get; set; }

		public AssemblyPatcherDelegate Patcher { get; set; }

		public string TypeName { get; set; } = string.Empty;


		public void Save(BinaryWriter bw)
		{
			bw.Write(TypeName);
		}

		public void Load(BinaryReader br)
		{
			TypeName = br.ReadString();
		}
	}
}

BepInEx/core/HarmonyXInterop.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using HarmonyLib;
using HarmonyLib.Public.Patching;
using HarmonyLib.Tools;
using Mono.Cecil;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("HarmonyXInterop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HarmonyXInterop")]
[assembly: AssemblyCopyright("Copyright ©  2020")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("160F7FE0-288D-435C-9E7E-497D3E0DE3A6")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HarmonyXInterop;

internal static class DMDUtil
{
	public static MethodInfo GenerateWith<T>(this DynamicMethodDefinition dmd, object context = null) where T : DMDGenerator<T>, new()
	{
		return DMDGenerator<T>.Generate(dmd, context);
	}
}
public static class HarmonyInterop
{
	private const string BACKUP_PATH = "BepInEx_Shim_Backup";

	private static Version maxAvailableShimVersion;

	private static readonly SortedDictionary<Version, string> Assemblies = new SortedDictionary<Version, string>();

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

	private static readonly Func<MethodBase, PatchInfo, MethodInfo> UpdateWrapper = AccessTools.MethodDelegate<Func<MethodBase, PatchInfo, MethodInfo>>(AccessTools.Method(typeof(HarmonyManipulator).Assembly.GetType("HarmonyLib.PatchFunctions"), "UpdateWrapper", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Action<LogChannel, Func<string>, bool> HarmonyLog = AccessTools.MethodDelegate<Action<LogChannel, Func<string>, bool>>(AccessTools.Method(typeof(Logger), "Log", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Action<LogChannel, string, bool> HarmonyLogText = AccessTools.MethodDelegate<Action<LogChannel, string, bool>>(AccessTools.Method(typeof(Logger), "LogText", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Dictionary<string, long> shimCache = new Dictionary<string, long>();

	private static BinaryWriter cacheWriter;

	public static void Log(int channel, Func<string> message)
	{
		HarmonyLog((LogChannel)channel, message, arg3: false);
	}

	public static void LogText(int channel, string message)
	{
		HarmonyLogText((LogChannel)channel, message, arg3: false);
	}

	public static void Initialize(string cachePath)
	{
		Directory.CreateDirectory(cachePath);
		string path = Path.Combine(cachePath, "harmony_interop_cache.dat");
		string[] files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "0Harmony*.dll", SearchOption.AllDirectories);
		for (int i = 0; i < files.Length; i++)
		{
			AssemblyDefinition val = AssemblyDefinition.ReadAssembly(files[i]);
			try
			{
				if (((AssemblyNameReference)val.Name).Name != "0Harmony")
				{
					Assemblies.Add(((AssemblyNameReference)val.Name).Version, ((AssemblyNameReference)val.Name).Name);
					InteropAssemblyNames.Add(((AssemblyNameReference)val.Name).Name);
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}
		maxAvailableShimVersion = Assemblies.LastOrDefault().Key;
		if (File.Exists(path))
		{
			try
			{
				using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path));
				while (true)
				{
					string key = binaryReader.ReadString();
					long value = binaryReader.ReadInt64();
					shimCache[key] = value;
				}
			}
			catch (Exception)
			{
			}
		}
		try
		{
			cacheWriter = new BinaryWriter(File.Create(path));
			foreach (KeyValuePair<string, long> item in shimCache)
			{
				cacheWriter.Write(item.Key);
				cacheWriter.Write(item.Value);
			}
			cacheWriter.Flush();
		}
		catch (IOException)
		{
		}
	}

	public static byte[] TryShim(string path, string gameRootDirectory, Action<string> logMessage = null, ReaderParameters readerParameters = null)
	{
		HashSet<string> hashSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
		List<string> deps;
		byte[] result = TryShimInternal(path, gameRootDirectory, logMessage, readerParameters, out deps);
		foreach (string item in deps)
		{
			hashSet.Add(item);
		}
		while (hashSet.Count != 0)
		{
			string text = hashSet.First();
			TryShimInternal(text, gameRootDirectory, logMessage, readerParameters, out deps);
			foreach (string item2 in deps)
			{
				hashSet.Add(item2);
			}
			hashSet.Remove(text);
		}
		return result;
	}

	private static bool NeedsShimming(string path, out long lastWriteTime, Action<string> logMessage = null)
	{
		lastWriteTime = 0L;
		try
		{
			if (!File.Exists(path))
			{
				return false;
			}
		}
		catch (Exception arg)
		{
			logMessage?.Invoke($"Failed to read path {path}: {arg}");
			return false;
		}
		lastWriteTime = File.GetLastWriteTimeUtc(path).Ticks;
		if (shimCache.TryGetValue(path, out var value))
		{
			return value != lastWriteTime;
		}
		return true;
	}

	private static byte[] TryShimInternal(string path, string gameRootDirectory, Action<string> logMessage, ReaderParameters readerParameters, out List<string> deps)
	{
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		deps = new List<string>();
		if (!NeedsShimming(path, out var lastWriteTime, logMessage))
		{
			return null;
		}
		byte[] result = null;
		try
		{
			string dir = Path.GetDirectoryName(path);
			byte[] array;
			try
			{
				array = File.ReadAllBytes(path);
			}
			catch (Exception)
			{
				return null;
			}
			using MemoryStream memoryStream = new MemoryStream(array);
			AssemblyDefinition val = AssemblyDefinition.ReadAssembly((Stream)memoryStream, (ReaderParameters)(((object)readerParameters) ?? ((object)new ReaderParameters())));
			try
			{
				deps.AddRange(from a in (IEnumerable<AssemblyNameReference>)val.MainModule.AssemblyReferences
					select Path.Combine(dir, a.Name + ".dll") into p
					where NeedsShimming(p, out var _, logMessage)
					select p);
				AssemblyNameReference harmonyRef = ((IEnumerable<AssemblyNameReference>)val.MainModule.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference a) => a.Name.StartsWith("0Harmony") && !InteropAssemblyNames.Contains(a.Name)));
				if (harmonyRef != null)
				{
					KeyValuePair<Version, string> keyValuePair = Assemblies.LastOrDefault((KeyValuePair<Version, string> kv) => VersionMatches(kv.Key, harmonyRef.Version));
					if (keyValuePair.Value != null)
					{
						logMessage?.Invoke("Shimming " + path + " to use older version of Harmony (" + keyValuePair.Value + "). Please update the plugin if possible.");
						harmonyRef.Name = keyValuePair.Value;
						using MemoryStream memoryStream2 = new MemoryStream();
						val.Write((Stream)memoryStream2);
						try
						{
							string path2 = Path.Combine(gameRootDirectory, "BepInEx_Shim_Backup");
							string directoryName = Path.GetDirectoryName(Path.GetFullPath(path).Substring(gameRootDirectory.Length + 1));
							string text = Path.Combine(path2, directoryName);
							Directory.CreateDirectory(text);
							File.WriteAllBytes(Path.Combine(text, Path.GetFileName(path)), array);
							File.WriteAllBytes(path, memoryStream2.ToArray());
							lastWriteTime = File.GetLastWriteTimeUtc(path).Ticks;
						}
						catch (IOException)
						{
							lastWriteTime = 0L;
						}
						result = memoryStream2.ToArray();
					}
				}
				shimCache[path] = lastWriteTime;
				if (cacheWriter != null)
				{
					cacheWriter.Write(path);
					cacheWriter.Write(lastWriteTime);
					cacheWriter.Flush();
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}
		catch (Exception arg)
		{
			logMessage?.Invoke($"Failed to shim {path}: {arg}");
		}
		return result;
		static bool VersionMatches(Version cmpV, Version refV)
		{
			if (maxAvailableShimVersion != null && refV <= maxAvailableShimVersion && cmpV.Major == refV.Major && cmpV.Minor == refV.Minor)
			{
				return cmpV <= refV;
			}
			return false;
		}
	}

	public static void ApplyPatch(MethodBase target, PatchInfoWrapper add, PatchInfoWrapper remove)
	{
		PatchInfo val = PatchManager.ToPatchInfo(target);
		lock (val)
		{
			val.prefixes = Sync(add.prefixes, remove.prefixes, val.prefixes);
			val.postfixes = Sync(add.postfixes, remove.postfixes, val.postfixes);
			val.transpilers = Sync(WrapTranspilers(add.transpilers), WrapTranspilers(remove.transpilers), val.transpilers);
			val.finalizers = Sync(add.finalizers, remove.finalizers, val.finalizers);
		}
		UpdateWrapper(target, val);
		static PatchMethod[] WrapTranspilers(PatchMethod[] transpilers)
		{
			return transpilers.Select((PatchMethod p) => new PatchMethod
			{
				after = p.after,
				before = p.before,
				method = TranspilerInterop.WrapInterop(p.method),
				owner = p.owner,
				priority = p.priority
			}).ToArray();
		}
	}

	private static Patch[] Sync(PatchMethod[] add, PatchMethod[] remove, Patch[] current)
	{
		if (add.Length == 0 && remove.Length == 0)
		{
			return current;
		}
		current = current.Where((Patch p) => !remove.Any((PatchMethod r) => (object)r.method == p.PatchMethod && r.owner == p.owner)).ToArray();
		int initialIndex = current.Length;
		return current.Concat(add.Where((PatchMethod method) => method != null).Select((Func<PatchMethod, int, Patch>)((PatchMethod method, int i) => new Patch(method.ToHarmonyMethod(), i + initialIndex, method.owner)))).ToArray();
	}
}
public class PatchInfoWrapper
{
	public PatchMethod[] finalizers;

	public PatchMethod[] postfixes;

	public PatchMethod[] prefixes;

	public PatchMethod[] transpilers;
}
public class PatchMethod
{
	public string[] after;

	public string[] before;

	public MethodInfo method;

	public string owner;

	public int priority = -1;

	public HarmonyMethod ToHarmonyMethod()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: 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_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		return new HarmonyMethod
		{
			after = after,
			before = before,
			method = method,
			priority = priority
		};
	}
}
public class PatchMethodComparer : IEqualityComparer<PatchMethod>
{
	public static PatchMethodComparer Instance { get; } = new PatchMethodComparer();


	public bool Equals(PatchMethod x, PatchMethod y)
	{
		if (x == y)
		{
			return true;
		}
		if (x == null)
		{
			return false;
		}
		if (y == null)
		{
			return false;
		}
		if ((object)x.GetType() != y.GetType())
		{
			return false;
		}
		if (object.Equals(x.method, y.method))
		{
			return x.owner == y.owner;
		}
		return false;
	}

	public int GetHashCode(PatchMethod obj)
	{
		return ((((object)obj.method != null) ? obj.method.GetHashCode() : 0) * 397) ^ ((obj.owner != null) ? obj.owner.GetHashCode() : 0);
	}
}
internal static class TranspilerInterop
{
	private static readonly Dictionary<OpCode, OpCode> AllJumpCodes = new Dictionary<OpCode, OpCode>
	{
		{
			OpCodes.Beq_S,
			OpCodes.Beq
		},
		{
			OpCodes.Bge_S,
			OpCodes.Bge
		},
		{
			OpCodes.Bge_Un_S,
			OpCodes.Bge_Un
		},
		{
			OpCodes.Bgt_S,
			OpCodes.Bgt
		},
		{
			OpCodes.Bgt_Un_S,
			OpCodes.Bgt_Un
		},
		{
			OpCodes.Ble_S,
			OpCodes.Ble
		},
		{
			OpCodes.Ble_Un_S,
			OpCodes.Ble_Un
		},
		{
			OpCodes.Blt_S,
			OpCodes.Blt
		},
		{
			OpCodes.Blt_Un_S,
			OpCodes.Blt_Un
		},
		{
			OpCodes.Bne_Un_S,
			OpCodes.Bne_Un
		},
		{
			OpCodes.Brfalse_S,
			OpCodes.Brfalse
		},
		{
			OpCodes.Brtrue_S,
			OpCodes.Brtrue
		},
		{
			OpCodes.Br_S,
			OpCodes.Br
		},
		{
			OpCodes.Leave_S,
			OpCodes.Leave
		}
	};

	private static readonly Dictionary<MethodInfo, MethodInfo> Wrappers = new Dictionary<MethodInfo, MethodInfo>();

	private static readonly MethodInfo ResolveToken = AccessTools.Method(typeof(MethodBase), "GetMethodFromHandle", new Type[1] { typeof(RuntimeMethodHandle) }, (Type[])null);

	private static readonly MethodInfo ApplyTranspilerMethod = AccessTools.Method(typeof(TranspilerInterop), "ApplyTranspiler", (Type[])null, (Type[])null);

	public static MethodInfo WrapInterop(MethodInfo transpiler)
	{
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Expected O, but got Unknown
		lock (Wrappers)
		{
			if (Wrappers.TryGetValue(transpiler, out var value))
			{
				return value;
			}
		}
		DynamicMethodDefinition val = new DynamicMethodDefinition("TranspilerWrapper<" + Extensions.GetID((MethodBase)transpiler, (string)null, (string)null, true, false, true) + ">", typeof(IEnumerable<CodeInstruction>), new Type[3]
		{
			typeof(IEnumerable<CodeInstruction>),
			typeof(ILGenerator),
			typeof(MethodBase)
		});
		try
		{
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldtoken, transpiler);
			iLGenerator.Emit(OpCodes.Call, ResolveToken);
			iLGenerator.Emit(OpCodes.Castclass, typeof(MethodInfo));
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Ldarg_2);
			iLGenerator.Emit(OpCodes.Call, ApplyTranspilerMethod);
			iLGenerator.Emit(OpCodes.Ret);
			MethodInfo methodInfo = val.GenerateWith<DMDCecilGenerator>((object)null);
			lock (Wrappers)
			{
				Wrappers[transpiler] = methodInfo;
			}
			return methodInfo;
		}
		finally
		{
			((IDisposable)val)?.Dispose();
		}
	}

	private static IEnumerable<CodeInstruction> ApplyTranspiler(MethodInfo transpiler, IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase method)
	{
		Dictionary<object, Dictionary<string, object>> unassignedValues;
		IEnumerable enumerable = ConvertToGeneralInstructions(transpiler, instructions, out unassignedValues);
		List<object> originalInstructions = null;
		if (unassignedValues != null)
		{
			originalInstructions = instructions.Cast<object>().ToList();
		}
		List<object> transpilerCallParameters = GetTranspilerCallParameters(generator, transpiler, method, enumerable);
		if (transpiler.Invoke(null, transpilerCallParameters.ToArray()) is IEnumerable enumerable2)
		{
			enumerable = enumerable2;
		}
		if (unassignedValues != null)
		{
			enumerable = ConvertToOurInstructions(enumerable, typeof(CodeInstruction), originalInstructions, unassignedValues);
		}
		return (enumerable as List<CodeInstruction>) ?? enumerable.Cast<CodeInstruction>().ToList();
	}

	private static OpCode ReplaceShortJumps(OpCode opcode)
	{
		using (IEnumerator<KeyValuePair<OpCode, OpCode>> enumerator = AllJumpCodes.Where((KeyValuePair<OpCode, OpCode> pair) => opcode == pair.Key).GetEnumerator())
		{
			if (enumerator.MoveNext())
			{
				return enumerator.Current.Value;
			}
		}
		return opcode;
	}

	private static object ConvertInstruction(Type type, object instruction, out Dictionary<string, object> unassigned)
	{
		Dictionary<string, object> nonExisting = new Dictionary<string, object>();
		object result = AccessTools.MakeDeepCopy(instruction, type, (Func<string, Traverse, Traverse, object>)delegate(string namePath, Traverse trvSrc, Traverse trvDest)
		{
			object value = trvSrc.GetValue();
			if (trvDest.FieldExists())
			{
				if (!(namePath == "opcode"))
				{
					return value;
				}
				return ReplaceShortJumps((OpCode)value);
			}
			nonExisting[namePath] = value;
			return null;
		}, "");
		unassigned = nonExisting;
		return result;
	}

	private static bool ShouldAddExceptionInfo(object op, int opIndex, List<object> originalInstructions, List<object> newInstructions, Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		int num = originalInstructions.IndexOf(op);
		if (num == -1)
		{
			return false;
		}
		if (!unassignedValues.TryGetValue(op, out var unassigned))
		{
			return false;
		}
		if (!unassigned.TryGetValue("blocks", out var blocksObject))
		{
			return false;
		}
		List<ExceptionBlock> blocks = blocksObject as List<ExceptionBlock>;
		if (newInstructions.Count((object instr) => instr == op) <= 1)
		{
			return true;
		}
		ExceptionBlock val = ((IEnumerable<ExceptionBlock>)blocks).FirstOrDefault((Func<ExceptionBlock, bool>)((ExceptionBlock block) => (int)block.blockType != 5));
		ExceptionBlock val2 = ((IEnumerable<ExceptionBlock>)blocks).FirstOrDefault((Func<ExceptionBlock, bool>)((ExceptionBlock block) => (int)block.blockType == 5));
		if (val != null && val2 == null)
		{
			object obj = originalInstructions.Skip(num + 1).FirstOrDefault(delegate(object instr)
			{
				if (!unassignedValues.TryGetValue(instr, out unassigned))
				{
					return false;
				}
				if (!unassigned.TryGetValue("blocks", out blocksObject))
				{
					return false;
				}
				blocks = blocksObject as List<ExceptionBlock>;
				return blocks.Any();
			});
			if (obj != null)
			{
				int num2 = num + 1;
				int num3 = num2 + originalInstructions.Skip(num2).ToList().IndexOf(obj) - 1;
				IEnumerable<object> first = originalInstructions.GetRange(num2, num3 - num2).Intersect(newInstructions);
				obj = newInstructions.Skip(opIndex + 1).FirstOrDefault(delegate(object instr)
				{
					if (!unassignedValues.TryGetValue(instr, out unassigned))
					{
						return false;
					}
					if (!unassigned.TryGetValue("blocks", out blocksObject))
					{
						return false;
					}
					blocks = blocksObject as List<ExceptionBlock>;
					return blocks.Any();
				});
				if (obj != null)
				{
					num2 = opIndex + 1;
					num3 = num2 + newInstructions.Skip(opIndex + 1).ToList().IndexOf(obj) - 1;
					List<object> range = newInstructions.GetRange(num2, num3 - num2);
					return !first.Except(range).ToList().Any();
				}
			}
		}
		if (val == null && val2 != null)
		{
			object obj2 = originalInstructions.GetRange(0, num).LastOrDefault(delegate(object instr)
			{
				if (!unassignedValues.TryGetValue(instr, out unassigned))
				{
					return false;
				}
				if (!unassigned.TryGetValue("blocks", out blocksObject))
				{
					return false;
				}
				blocks = blocksObject as List<ExceptionBlock>;
				return blocks.Any();
			});
			if (obj2 == null)
			{
				return true;
			}
			int num4 = originalInstructions.GetRange(0, num).LastIndexOf(obj2);
			int num5 = num;
			IEnumerable<object> first2 = originalInstructions.GetRange(num4, num5 - num4).Intersect(newInstructions);
			obj2 = newInstructions.GetRange(0, opIndex).LastOrDefault(delegate(object instr)
			{
				if (!unassignedValues.TryGetValue(instr, out unassigned))
				{
					return false;
				}
				if (!unassigned.TryGetValue("blocks", out blocksObject))
				{
					return false;
				}
				blocks = blocksObject as List<ExceptionBlock>;
				return blocks.Any();
			});
			if (obj2 == null)
			{
				return true;
			}
			num4 = newInstructions.GetRange(0, opIndex).LastIndexOf(obj2);
			num5 = opIndex;
			List<object> range2 = newInstructions.GetRange(num4, num5 - num4);
			return !first2.Except(range2).Any();
		}
		return true;
	}

	private static IEnumerable ConvertInstructionsAndUnassignedValues(Type type, IEnumerable enumerable, out Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		Assembly assembly = type.GetGenericTypeDefinition().Assembly;
		Type? type2 = assembly.GetType(typeof(List<>).FullName);
		Type type3 = type.GetGenericArguments()[0];
		Type type4 = type2.MakeGenericType(type3);
		object obj = Activator.CreateInstance(assembly.GetType(type4.FullName));
		MethodInfo method = obj.GetType().GetMethod("Add");
		unassignedValues = new Dictionary<object, Dictionary<string, object>>();
		foreach (object item in enumerable)
		{
			Dictionary<string, object> unassigned;
			object obj2 = ConvertInstruction(type3, item, out unassigned);
			unassignedValues.Add(obj2, unassigned);
			method.Invoke(obj, new object[1] { obj2 });
		}
		return obj as IEnumerable;
	}

	private static IEnumerable ConvertToOurInstructions(IEnumerable instructions, Type codeInstructionType, List<object> originalInstructions, Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		List<object> newInstructions = instructions.Cast<object>().ToList();
		int index = -1;
		foreach (object item in newInstructions)
		{
			index++;
			object obj = AccessTools.MakeDeepCopy(item, codeInstructionType, (Func<string, Traverse, Traverse, object>)null, "");
			if (unassignedValues.TryGetValue(item, out var value))
			{
				bool addExceptionInfo = ShouldAddExceptionInfo(item, index, originalInstructions, newInstructions, unassignedValues);
				Traverse val = Traverse.Create(obj);
				foreach (KeyValuePair<string, object> item2 in value.Where((KeyValuePair<string, object> field) => addExceptionInfo || field.Key != "blocks"))
				{
					val.Field(item2.Key).SetValue(item2.Value);
				}
			}
			yield return obj;
		}
	}

	private static bool IsCodeInstructionsParameter(Type type)
	{
		if (type.IsGenericType)
		{
			return type.GetGenericTypeDefinition().Name.StartsWith("IEnumerable", StringComparison.Ordinal);
		}
		return false;
	}

	private static IEnumerable ConvertToGeneralInstructions(MethodInfo transpiler, IEnumerable enumerable, out Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		Type type = (from p in transpiler.GetParameters()
			select p.ParameterType).FirstOrDefault((Type t) => IsCodeInstructionsParameter(t));
		if ((object)type == null)
		{
			unassignedValues = new Dictionary<object, Dictionary<string, object>>();
			return enumerable;
		}
		if ((object)type != typeof(IEnumerable<CodeInstruction>))
		{
			return ConvertInstructionsAndUnassignedValues(type, enumerable, out unassignedValues);
		}
		unassignedValues = null;
		return (enumerable as IList<CodeInstruction>) ?? ((enumerable as IEnumerable<CodeInstruction>) ?? enumerable.Cast<CodeInstruction>()).ToList();
	}

	private static List<object> GetTranspilerCallParameters(ILGenerator generator, MethodInfo transpiler, MethodBase method, IEnumerable instructions)
	{
		List<object> parameter = new List<object>();
		CollectionExtensions.Do<Type>(from param in transpiler.GetParameters()
			select param.ParameterType, (Action<Type>)delegate(Type type)
		{
			if (type.IsAssignableFrom(typeof(ILGenerator)))
			{
				parameter.Add(generator);
			}
			else if (type.IsAssignableFrom(typeof(MethodBase)))
			{
				parameter.Add(method);
			}
			else if (IsCodeInstructionsParameter(type))
			{
				parameter.Add(instructions);
			}
		});
		return parameter;
	}
}

BepInEx/core/Mono.Cecil.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using Mono.Collections.Generic;
using Mono.Security.Cryptography;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil")]
[assembly: Guid("fd225bb4-fa53-44b2-a6db-85f5e48dcb54")]
[assembly: InternalsVisibleTo("Mono.Cecil.Pdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: InternalsVisibleTo("Mono.Cecil.Mdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: InternalsVisibleTo("Mono.Cecil.Rocks, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: InternalsVisibleTo("Mono.Cecil.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: AssemblyVersion("0.10.4.0")]
internal static class Consts
{
	public const string AssemblyName = "Mono.Cecil";

	public const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf";
}
namespace Mono
{
	internal static class Disposable
	{
		public static Disposable<T> Owned<T>(T value) where T : class, IDisposable
		{
			return new Disposable<T>(value, owned: true);
		}

		public static Disposable<T> NotOwned<T>(T value) where T : class, IDisposable
		{
			return new Disposable<T>(value, owned: false);
		}
	}
	internal struct Disposable<T> : IDisposable where T : class, IDisposable
	{
		internal readonly T value;

		private readonly bool owned;

		public Disposable(T value, bool owned)
		{
			this.value = value;
			this.owned = owned;
		}

		public void Dispose()
		{
			if (value != null && owned)
			{
				value.Dispose();
			}
		}
	}
	internal static class Empty<T>
	{
		public static readonly T[] Array = new T[0];
	}
	internal class ArgumentNullOrEmptyException : ArgumentException
	{
		public ArgumentNullOrEmptyException(string paramName)
			: base("Argument null or empty", paramName)
		{
		}
	}
	internal class MergeSort<T>
	{
		private readonly T[] elements;

		private readonly T[] buffer;

		private readonly IComparer<T> comparer;

		private MergeSort(T[] elements, IComparer<T> comparer)
		{
			this.elements = elements;
			buffer = new T[elements.Length];
			Array.Copy(this.elements, buffer, elements.Length);
			this.comparer = comparer;
		}

		public static void Sort(T[] source, IComparer<T> comparer)
		{
			Sort(source, 0, source.Length, comparer);
		}

		public static void Sort(T[] source, int start, int length, IComparer<T> comparer)
		{
			new MergeSort<T>(source, comparer).Sort(start, length);
		}

		private void Sort(int start, int length)
		{
			TopDownSplitMerge(buffer, elements, start, length);
		}

		private void TopDownSplitMerge(T[] a, T[] b, int start, int end)
		{
			if (end - start >= 2)
			{
				int num = (end + start) / 2;
				TopDownSplitMerge(b, a, start, num);
				TopDownSplitMerge(b, a, num, end);
				TopDownMerge(a, b, start, num, end);
			}
		}

		private void TopDownMerge(T[] a, T[] b, int start, int middle, int end)
		{
			int num = start;
			int num2 = middle;
			for (int i = start; i < end; i++)
			{
				if (num < middle && (num2 >= end || comparer.Compare(a[num], a[num2]) <= 0))
				{
					b[i] = a[num++];
				}
				else
				{
					b[i] = a[num2++];
				}
			}
		}
	}
	internal static class TypeExtensions
	{
		public static TypeCode GetTypeCode(this Type type)
		{
			return Type.GetTypeCode(type);
		}

		public static Assembly Assembly(this Type type)
		{
			return type.Assembly;
		}

		public static MethodBase DeclaringMethod(this Type type)
		{
			return type.DeclaringMethod;
		}

		public static Type[] GetGenericArguments(this Type type)
		{
			return type.GetGenericArguments();
		}

		public static bool IsGenericType(this Type type)
		{
			return type.IsGenericType;
		}

		public static bool IsGenericTypeDefinition(this Type type)
		{
			return type.IsGenericTypeDefinition;
		}

		public static bool IsValueType(this Type type)
		{
			return type.IsValueType;
		}
	}
}
namespace Mono.Security.Cryptography
{
	internal static class CryptoConvert
	{
		private static int ToInt32LE(byte[] bytes, int offset)
		{
			return (bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset];
		}

		private static uint ToUInt32LE(byte[] bytes, int offset)
		{
			return (uint)((bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]);
		}

		private static byte[] Trim(byte[] array)
		{
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i] != 0)
				{
					byte[] array2 = new byte[array.Length - i];
					Buffer.BlockCopy(array, i, array2, 0, array2.Length);
					return array2;
				}
			}
			return null;
		}

		private static RSA FromCapiPrivateKeyBlob(byte[] blob, int offset)
		{
			RSAParameters parameters = default(RSAParameters);
			try
			{
				if (blob[offset] != 7 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 843141970)
				{
					throw new CryptographicException("Invalid blob header");
				}
				int num = ToInt32LE(blob, offset + 12);
				byte[] array = new byte[4];
				Buffer.BlockCopy(blob, offset + 16, array, 0, 4);
				Array.Reverse((Array)array);
				parameters.Exponent = Trim(array);
				int num2 = offset + 20;
				int num3 = num >> 3;
				parameters.Modulus = new byte[num3];
				Buffer.BlockCopy(blob, num2, parameters.Modulus, 0, num3);
				Array.Reverse((Array)parameters.Modulus);
				num2 += num3;
				int num4 = num3 >> 1;
				parameters.P = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.P, 0, num4);
				Array.Reverse((Array)parameters.P);
				num2 += num4;
				parameters.Q = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.Q, 0, num4);
				Array.Reverse((Array)parameters.Q);
				num2 += num4;
				parameters.DP = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.DP, 0, num4);
				Array.Reverse((Array)parameters.DP);
				num2 += num4;
				parameters.DQ = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.DQ, 0, num4);
				Array.Reverse((Array)parameters.DQ);
				num2 += num4;
				parameters.InverseQ = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.InverseQ, 0, num4);
				Array.Reverse((Array)parameters.InverseQ);
				num2 += num4;
				parameters.D = new byte[num3];
				if (num2 + num3 + offset <= blob.Length)
				{
					Buffer.BlockCopy(blob, num2, parameters.D, 0, num3);
					Array.Reverse((Array)parameters.D);
				}
			}
			catch (Exception inner)
			{
				throw new CryptographicException("Invalid blob.", inner);
			}
			RSA rSA = null;
			try
			{
				rSA = RSA.Create();
				rSA.ImportParameters(parameters);
			}
			catch (CryptographicException)
			{
				bool flag = false;
				try
				{
					rSA = new RSACryptoServiceProvider(new CspParameters
					{
						Flags = CspProviderFlags.UseMachineKeyStore
					});
					rSA.ImportParameters(parameters);
				}
				catch
				{
					flag = true;
				}
				if (flag)
				{
					throw;
				}
			}
			return rSA;
		}

		private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset)
		{
			try
			{
				if (blob[offset] != 6 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 826364754)
				{
					throw new CryptographicException("Invalid blob header");
				}
				int num = ToInt32LE(blob, offset + 12);
				RSAParameters parameters = new RSAParameters
				{
					Exponent = new byte[3]
				};
				parameters.Exponent[0] = blob[offset + 18];
				parameters.Exponent[1] = blob[offset + 17];
				parameters.Exponent[2] = blob[offset + 16];
				int srcOffset = offset + 20;
				int num2 = num >> 3;
				parameters.Modulus = new byte[num2];
				Buffer.BlockCopy(blob, srcOffset, parameters.Modulus, 0, num2);
				Array.Reverse((Array)parameters.Modulus);
				RSA rSA = null;
				try
				{
					rSA = RSA.Create();
					rSA.ImportParameters(parameters);
				}
				catch (CryptographicException)
				{
					rSA = new RSACryptoServiceProvider(new CspParameters
					{
						Flags = CspProviderFlags.UseMachineKeyStore
					});
					rSA.ImportParameters(parameters);
				}
				return rSA;
			}
			catch (Exception inner)
			{
				throw new CryptographicException("Invalid blob.", inner);
			}
		}

		public static RSA FromCapiKeyBlob(byte[] blob)
		{
			return FromCapiKeyBlob(blob, 0);
		}

		public static RSA FromCapiKeyBlob(byte[] blob, int offset)
		{
			if (blob == null)
			{
				throw new ArgumentNullException("blob");
			}
			if (offset >= blob.Length)
			{
				throw new ArgumentException("blob is too small.");
			}
			switch (blob[offset])
			{
			case 0:
				if (blob[offset + 12] == 6)
				{
					return FromCapiPublicKeyBlob(blob, offset + 12);
				}
				break;
			case 6:
				return FromCapiPublicKeyBlob(blob, offset);
			case 7:
				return FromCapiPrivateKeyBlob(blob, offset);
			}
			throw new CryptographicException("Unknown blob format.");
		}
	}
}
namespace Mono.Collections.Generic
{
	public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection
	{
		public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
		{
			private Collection<T> collection;

			private T current;

			private int next;

			private readonly int version;

			public T Current => current;

			object IEnumerator.Current
			{
				get
				{
					CheckState();
					if (next <= 0)
					{
						throw new InvalidOperationException();
					}
					return current;
				}
			}

			internal Enumerator(Collection<T> collection)
			{
				this = default(Enumerator);
				this.collection = collection;
				version = collection.version;
			}

			public bool MoveNext()
			{
				CheckState();
				if (next < 0)
				{
					return false;
				}
				if (next < collection.size)
				{
					current = collection.items[next++];
					return true;
				}
				next = -1;
				return false;
			}

			public void Reset()
			{
				CheckState();
				next = 0;
			}

			private void CheckState()
			{
				if (collection == null)
				{
					throw new ObjectDisposedException(GetType().FullName);
				}
				if (version != collection.version)
				{
					throw new InvalidOperationException();
				}
			}

			public void Dispose()
			{
				collection = null;
			}
		}

		internal T[] items;

		internal int size;

		private int version;

		public int Count => size;

		public T this[int index]
		{
			get
			{
				if (index >= size)
				{
					throw new ArgumentOutOfRangeException();
				}
				return items[index];
			}
			set
			{
				CheckIndex(index);
				if (index == size)
				{
					throw new ArgumentOutOfRangeException();
				}
				OnSet(value, index);
				items[index] = value;
			}
		}

		public int Capacity
		{
			get
			{
				return items.Length;
			}
			set
			{
				if (value < 0 || value < size)
				{
					throw new ArgumentOutOfRangeException();
				}
				Resize(value);
			}
		}

		bool ICollection<T>.IsReadOnly => false;

		bool IList.IsFixedSize => false;

		bool IList.IsReadOnly => false;

		object IList.this[int index]
		{
			get
			{
				return this[index];
			}
			set
			{
				CheckIndex(index);
				try
				{
					this[index] = (T)value;
					return;
				}
				catch (InvalidCastException)
				{
				}
				catch (NullReferenceException)
				{
				}
				throw new ArgumentException();
			}
		}

		int ICollection.Count => Count;

		bool ICollection.IsSynchronized => false;

		object ICollection.SyncRoot => this;

		public Collection()
		{
			items = Empty<T>.Array;
		}

		public Collection(int capacity)
		{
			if (capacity < 0)
			{
				throw new ArgumentOutOfRangeException();
			}
			items = new T[capacity];
		}

		public Collection(ICollection<T> items)
		{
			if (items == null)
			{
				throw new ArgumentNullException("items");
			}
			this.items = new T[items.Count];
			items.CopyTo(this.items, 0);
			size = this.items.Length;
		}

		public void Add(T item)
		{
			if (size == items.Length)
			{
				Grow(1);
			}
			OnAdd(item, size);
			items[size++] = item;
			version++;
		}

		public bool Contains(T item)
		{
			return IndexOf(item) != -1;
		}

		public int IndexOf(T item)
		{
			return Array.IndexOf(items, item, 0, size);
		}

		public void Insert(int index, T item)
		{
			CheckIndex(index);
			if (size == items.Length)
			{
				Grow(1);
			}
			OnInsert(item, index);
			Shift(index, 1);
			items[index] = item;
			version++;
		}

		public void RemoveAt(int index)
		{
			if (index < 0 || index >= size)
			{
				throw new ArgumentOutOfRangeException();
			}
			T item = items[index];
			OnRemove(item, index);
			Shift(index, -1);
			version++;
		}

		public bool Remove(T item)
		{
			int num = IndexOf(item);
			if (num == -1)
			{
				return false;
			}
			OnRemove(item, num);
			Shift(num, -1);
			version++;
			return true;
		}

		public void Clear()
		{
			OnClear();
			Array.Clear(items, 0, size);
			size = 0;
			version++;
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
			Array.Copy(items, 0, array, arrayIndex, size);
		}

		public T[] ToArray()
		{
			T[] array = new T[size];
			Array.Copy(items, 0, array, 0, size);
			return array;
		}

		private void CheckIndex(int index)
		{
			if (index < 0 || index > size)
			{
				throw new ArgumentOutOfRangeException();
			}
		}

		private void Shift(int start, int delta)
		{
			if (delta < 0)
			{
				start -= delta;
			}
			if (start < size)
			{
				Array.Copy(items, start, items, start + delta, size - start);
			}
			size += delta;
			if (delta < 0)
			{
				Array.Clear(items, size, -delta);
			}
		}

		protected virtual void OnAdd(T item, int index)
		{
		}

		protected virtual void OnInsert(T item, int index)
		{
		}

		protected virtual void OnSet(T item, int index)
		{
		}

		protected virtual void OnRemove(T item, int index)
		{
		}

		protected virtual void OnClear()
		{
		}

		internal virtual void Grow(int desired)
		{
			int num = size + desired;
			if (num > items.Length)
			{
				num = Math.Max(Math.Max(items.Length * 2, 4), num);
				Resize(num);
			}
		}

		protected void Resize(int new_size)
		{
			if (new_size != size)
			{
				if (new_size < size)
				{
					throw new ArgumentOutOfRangeException();
				}
				items = items.Resize(new_size);
			}
		}

		int IList.Add(object value)
		{
			try
			{
				Add((T)value);
				return size - 1;
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
			throw new ArgumentException();
		}

		void IList.Clear()
		{
			Clear();
		}

		bool IList.Contains(object value)
		{
			return ((IList)this).IndexOf(value) > -1;
		}

		int IList.IndexOf(object value)
		{
			try
			{
				return IndexOf((T)value);
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
			return -1;
		}

		void IList.Insert(int index, object value)
		{
			CheckIndex(index);
			try
			{
				Insert(index, (T)value);
				return;
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
			throw new ArgumentException();
		}

		void IList.Remove(object value)
		{
			try
			{
				Remove((T)value);
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
		}

		void IList.RemoveAt(int index)
		{
			RemoveAt(index);
		}

		void ICollection.CopyTo(Array array, int index)
		{
			Array.Copy(items, 0, array, index, size);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new Enumerator(this);
		}

		IEnumerator<T> IEnumerable<T>.GetEnumerator()
		{
			return new Enumerator(this);
		}
	}
	public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection
	{
		private static ReadOnlyCollection<T> empty;

		public static ReadOnlyCollection<T> Empty => empty ?? (empty = new ReadOnlyCollection<T>());

		bool ICollection<T>.IsReadOnly => true;

		bool IList.IsFixedSize => true;

		bool IList.IsReadOnly => true;

		private ReadOnlyCollection()
		{
		}

		public ReadOnlyCollection(T[] array)
		{
			if (array == null)
			{
				throw new ArgumentNullException();
			}
			Initialize(array, array.Length);
		}

		public ReadOnlyCollection(Collection<T> collection)
		{
			if (collection == null)
			{
				throw new ArgumentNullException();
			}
			Initialize(collection.items, collection.size);
		}

		private void Initialize(T[] items, int size)
		{
			base.items = new T[size];
			Array.Copy(items, 0, base.items, 0, size);
			base.size = size;
		}

		internal override void Grow(int desired)
		{
			throw new InvalidOperationException();
		}

		protected override void OnAdd(T item, int index)
		{
			throw new InvalidOperationException();
		}

		protected override void OnClear()
		{
			throw new InvalidOperationException();
		}

		protected override void OnInsert(T item, int index)
		{
			throw new InvalidOperationException();
		}

		protected override void OnRemove(T item, int index)
		{
			throw new InvalidOperationException();
		}

		protected override void OnSet(T item, int index)
		{
			throw new InvalidOperationException();
		}
	}
}
namespace Mono.Cecil
{
	internal static class Mixin
	{
		public enum Argument
		{
			name,
			fileName,
			fullName,
			stream,
			type,
			method,
			field,
			parameters,
			module,
			modifierType,
			eventType,
			fieldType,
			declaringType,
			returnType,
			propertyType,
			interfaceType
		}

		public static Version ZeroVersion = new Version(0, 0, 0, 0);

		public const int NotResolvedMarker = -2;

		public const int NoDataMarker = -1;

		internal static object NoValue = new object();

		internal static object NotResolved = new object();

		public const string mscorlib = "mscorlib";

		public const string system_runtime = "System.Runtime";

		public const string system_private_corelib = "System.Private.CoreLib";

		public const string netstandard = "netstandard";

		public const int TableCount = 58;

		public const int CodedIndexCount = 14;

		public static bool IsNullOrEmpty<T>(this T[] self)
		{
			if (self != null)
			{
				return self.Length == 0;
			}
			return true;
		}

		public static bool IsNullOrEmpty<T>(this Collection<T> self)
		{
			if (self != null)
			{
				return self.size == 0;
			}
			return true;
		}

		public static T[] Resize<T>(this T[] self, int length)
		{
			Array.Resize(ref self, length);
			return self;
		}

		public static T[] Add<T>(this T[] self, T item)
		{
			if (self == null)
			{
				self = new T[1] { item };
				return self;
			}
			self = self.Resize(self.Length + 1);
			self[^1] = item;
			return self;
		}

		public static Version CheckVersion(Version version)
		{
			if (version == null)
			{
				return ZeroVersion;
			}
			if (version.Build == -1)
			{
				return new Version(version.Major, version.Minor, 0, 0);
			}
			if (version.Revision == -1)
			{
				return new Version(version.Major, version.Minor, version.Build, 0);
			}
			return version;
		}

		public static bool TryGetUniqueDocument(this MethodDebugInformation info, out Document document)
		{
			document = info.SequencePoints[0].Document;
			for (int i = 1; i < info.SequencePoints.Count; i++)
			{
				if (info.SequencePoints[i].Document != document)
				{
					return false;
				}
			}
			return true;
		}

		public static void ResolveConstant(this IConstantProvider self, ref object constant, ModuleDefinition module)
		{
			if (module == null)
			{
				constant = NoValue;
				return;
			}
			lock (module.SyncRoot)
			{
				if (constant != NotResolved)
				{
					return;
				}
				if (module.HasImage())
				{
					constant = module.Read(self, (IConstantProvider provider, MetadataReader reader) => reader.ReadConstant(provider));
				}
				else
				{
					constant = NoValue;
				}
			}
		}

		public static bool GetHasCustomAttributes(this ICustomAttributeProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.HasCustomAttributes(provider));
			}
			return false;
		}

		public static Collection<CustomAttribute> GetCustomAttributes(this ICustomAttributeProvider self, ref Collection<CustomAttribute> variable, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return variable = new Collection<CustomAttribute>();
			}
			return module.Read(ref variable, self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.ReadCustomAttributes(provider));
		}

		public static bool ContainsGenericParameter(this IGenericInstance self)
		{
			Collection<TypeReference> genericArguments = self.GenericArguments;
			for (int i = 0; i < genericArguments.Count; i++)
			{
				if (genericArguments[i].ContainsGenericParameter)
				{
					return true;
				}
			}
			return false;
		}

		public static void GenericInstanceFullName(this IGenericInstance self, StringBuilder builder)
		{
			builder.Append("<");
			Collection<TypeReference> genericArguments = self.GenericArguments;
			for (int i = 0; i < genericArguments.Count; i++)
			{
				if (i > 0)
				{
					builder.Append(",");
				}
				builder.Append(genericArguments[i].FullName);
			}
			builder.Append(">");
		}

		public static bool GetHasGenericParameters(this IGenericParameterProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (IGenericParameterProvider provider, MetadataReader reader) => reader.HasGenericParameters(provider));
			}
			return false;
		}

		public static Collection<GenericParameter> GetGenericParameters(this IGenericParameterProvider self, ref Collection<GenericParameter> collection, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return collection = new GenericParameterCollection(self);
			}
			return module.Read(ref collection, self, (IGenericParameterProvider provider, MetadataReader reader) => reader.ReadGenericParameters(provider));
		}

		public static bool GetHasMarshalInfo(this IMarshalInfoProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.HasMarshalInfo(provider));
			}
			return false;
		}

		public static MarshalInfo GetMarshalInfo(this IMarshalInfoProvider self, ref MarshalInfo variable, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return null;
			}
			return module.Read(ref variable, self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.ReadMarshalInfo(provider));
		}

		public static bool GetAttributes(this uint self, uint attributes)
		{
			return (self & attributes) != 0;
		}

		public static uint SetAttributes(this uint self, uint attributes, bool value)
		{
			if (value)
			{
				return self | attributes;
			}
			return self & ~attributes;
		}

		public static bool GetMaskedAttributes(this uint self, uint mask, uint attributes)
		{
			return (self & mask) == attributes;
		}

		public static uint SetMaskedAttributes(this uint self, uint mask, uint attributes, bool value)
		{
			if (value)
			{
				self &= ~mask;
				return self | attributes;
			}
			return self & ~(mask & attributes);
		}

		public static bool GetAttributes(this ushort self, ushort attributes)
		{
			return (self & attributes) != 0;
		}

		public static ushort SetAttributes(this ushort self, ushort attributes, bool value)
		{
			if (value)
			{
				return (ushort)(self | attributes);
			}
			return (ushort)(self & ~attributes);
		}

		public static bool GetMaskedAttributes(this ushort self, ushort mask, uint attributes)
		{
			return (self & mask) == attributes;
		}

		public static ushort SetMaskedAttributes(this ushort self, ushort mask, uint attributes, bool value)
		{
			if (value)
			{
				self = (ushort)(self & ~mask);
				return (ushort)(self | attributes);
			}
			return (ushort)(self & ~(mask & attributes));
		}

		public static bool HasImplicitThis(this IMethodSignature self)
		{
			if (self.HasThis)
			{
				return !self.ExplicitThis;
			}
			return false;
		}

		public static void MethodSignatureFullName(this IMethodSignature self, StringBuilder builder)
		{
			builder.Append("(");
			if (self.HasParameters)
			{
				Collection<ParameterDefinition> parameters = self.Parameters;
				for (int i = 0; i < parameters.Count; i++)
				{
					ParameterDefinition parameterDefinition = parameters[i];
					if (i > 0)
					{
						builder.Append(",");
					}
					if (parameterDefinition.ParameterType.IsSentinel)
					{
						builder.Append("...,");
					}
					builder.Append(parameterDefinition.ParameterType.FullName);
				}
			}
			builder.Append(")");
		}

		public static void CheckModule(ModuleDefinition module)
		{
			if (module == null)
			{
				throw new ArgumentNullException(Argument.module.ToString());
			}
		}

		public static bool TryGetAssemblyNameReference(this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
		{
			Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences;
			for (int i = 0; i < assemblyReferences.Count; i++)
			{
				AssemblyNameReference assemblyNameReference = assemblyReferences[i];
				if (Equals(name_reference, assemblyNameReference))
				{
					assembly_reference = assemblyNameReference;
					return true;
				}
			}
			assembly_reference = null;
			return false;
		}

		private static bool Equals(byte[] a, byte[] b)
		{
			if (a == b)
			{
				return true;
			}
			if (a == null)
			{
				return false;
			}
			if (a.Length != b.Length)
			{
				return false;
			}
			for (int i = 0; i < a.Length; i++)
			{
				if (a[i] != b[i])
				{
					return false;
				}
			}
			return true;
		}

		private static bool Equals<T>(T a, T b) where T : class, IEquatable<T>
		{
			if (a == b)
			{
				return true;
			}
			return a?.Equals(b) ?? false;
		}

		private static bool Equals(AssemblyNameReference a, AssemblyNameReference b)
		{
			if (a == b)
			{
				return true;
			}
			if (a.Name != b.Name)
			{
				return false;
			}
			if (!Equals(a.Version, b.Version))
			{
				return false;
			}
			if (a.Culture != b.Culture)
			{
				return false;
			}
			if (!Equals(a.PublicKeyToken, b.PublicKeyToken))
			{
				return false;
			}
			return true;
		}

		public static ParameterDefinition GetParameter(this Mono.Cecil.Cil.MethodBody self, int index)
		{
			MethodDefinition method = self.method;
			if (method.HasThis)
			{
				if (index == 0)
				{
					return self.ThisParameter;
				}
				index--;
			}
			Collection<ParameterDefinition> parameters = method.Parameters;
			if (index < 0 || index >= parameters.size)
			{
				return null;
			}
			return parameters[index];
		}

		public static VariableDefinition GetVariable(this Mono.Cecil.Cil.MethodBody self, int index)
		{
			Collection<VariableDefinition> variables = self.Variables;
			if (index < 0 || index >= variables.size)
			{
				return null;
			}
			return variables[index];
		}

		public static bool GetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics)
		{
			return (self.SemanticsAttributes & semantics) != 0;
		}

		public static void SetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics, bool value)
		{
			if (value)
			{
				self.SemanticsAttributes |= semantics;
			}
			else
			{
				self.SemanticsAttributes &= (MethodSemanticsAttributes)(ushort)(~(int)semantics);
			}
		}

		public static bool IsVarArg(this IMethodSignature self)
		{
			return self.CallingConvention == MethodCallingConvention.VarArg;
		}

		public static int GetSentinelPosition(this IMethodSignature self)
		{
			if (!self.HasParameters)
			{
				return -1;
			}
			Collection<ParameterDefinition> parameters = self.Parameters;
			for (int i = 0; i < parameters.Count; i++)
			{
				if (parameters[i].ParameterType.IsSentinel)
				{
					return i;
				}
			}
			return -1;
		}

		public static void CheckName(object name)
		{
			if (name == null)
			{
				throw new ArgumentNullException(Argument.name.ToString());
			}
		}

		public static void CheckName(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				throw new ArgumentNullOrEmptyException(Argument.name.ToString());
			}
		}

		public static void CheckFileName(string fileName)
		{
			if (string.IsNullOrEmpty(fileName))
			{
				throw new ArgumentNullOrEmptyException(Argument.fileName.ToString());
			}
		}

		public static void CheckFullName(string fullName)
		{
			if (string.IsNullOrEmpty(fullName))
			{
				throw new ArgumentNullOrEmptyException(Argument.fullName.ToString());
			}
		}

		public static void CheckStream(object stream)
		{
			if (stream == null)
			{
				throw new ArgumentNullException(Argument.stream.ToString());
			}
		}

		public static void CheckWriteSeek(Stream stream)
		{
			if (!stream.CanWrite || !stream.CanSeek)
			{
				throw new ArgumentException("Stream must be writable and seekable.");
			}
		}

		public static void CheckReadSeek(Stream stream)
		{
			if (!stream.CanRead || !stream.CanSeek)
			{
				throw new ArgumentException("Stream must be readable and seekable.");
			}
		}

		public static void CheckType(object type)
		{
			if (type == null)
			{
				throw new ArgumentNullException(Argument.type.ToString());
			}
		}

		public static void CheckType(object type, Argument argument)
		{
			if (type == null)
			{
				throw new ArgumentNullException(argument.ToString());
			}
		}

		public static void CheckField(object field)
		{
			if (field == null)
			{
				throw new ArgumentNullException(Argument.field.ToString());
			}
		}

		public static void CheckMethod(object method)
		{
			if (method == null)
			{
				throw new ArgumentNullException(Argument.method.ToString());
			}
		}

		public static void CheckParameters(object parameters)
		{
			if (parameters == null)
			{
				throw new ArgumentNullException(Argument.parameters.ToString());
			}
		}

		public static uint GetTimestamp()
		{
			return (uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
		}

		public static bool HasImage(this ModuleDefinition self)
		{
			return self?.HasImage ?? false;
		}

		public static string GetFileName(this Stream self)
		{
			if (!(self is FileStream fileStream))
			{
				return string.Empty;
			}
			return Path.GetFullPath(fileStream.Name);
		}

		public static void CopyTo(this Stream self, Stream target)
		{
			byte[] array = new byte[8192];
			int count;
			while ((count = self.Read(array, 0, array.Length)) > 0)
			{
				target.Write(array, 0, count);
			}
		}

		public static TargetRuntime ParseRuntime(this string self)
		{
			if (string.IsNullOrEmpty(self))
			{
				return TargetRuntime.Net_4_0;
			}
			switch (self[1])
			{
			case '1':
				if (self[3] != '0')
				{
					return TargetRuntime.Net_1_1;
				}
				return TargetRuntime.Net_1_0;
			case '2':
				return TargetRuntime.Net_2_0;
			default:
				return TargetRuntime.Net_4_0;
			}
		}

		public static string RuntimeVersionString(this TargetRuntime runtime)
		{
			return runtime switch
			{
				TargetRuntime.Net_1_0 => "v1.0.3705", 
				TargetRuntime.Net_1_1 => "v1.1.4322", 
				TargetRuntime.Net_2_0 => "v2.0.50727", 
				_ => "v4.0.30319", 
			};
		}

		public static bool IsWindowsMetadata(this ModuleDefinition module)
		{
			return module.MetadataKind != MetadataKind.Ecma335;
		}

		public static byte[] ReadAll(this Stream self)
		{
			MemoryStream memoryStream = new MemoryStream((int)self.Length);
			byte[] array = new byte[1024];
			int count;
			while ((count = self.Read(array, 0, array.Length)) != 0)
			{
				memoryStream.Write(array, 0, count);
			}
			return memoryStream.ToArray();
		}

		public static void Read(object o)
		{
		}

		public static bool GetHasSecurityDeclarations(this ISecurityDeclarationProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.HasSecurityDeclarations(provider));
			}
			return false;
		}

		public static Collection<SecurityDeclaration> GetSecurityDeclarations(this ISecurityDeclarationProvider self, ref Collection<SecurityDeclaration> variable, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return variable = new Collection<SecurityDeclaration>();
			}
			return module.Read(ref variable, self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.ReadSecurityDeclarations(provider));
		}

		public static TypeReference GetEnumUnderlyingType(this TypeDefinition self)
		{
			Collection<FieldDefinition> fields = self.Fields;
			for (int i = 0; i < fields.Count; i++)
			{
				FieldDefinition fieldDefinition = fields[i];
				if (!fieldDefinition.IsStatic)
				{
					return fieldDefinition.FieldType;
				}
			}
			throw new ArgumentException();
		}

		public static TypeDefinition GetNestedType(this TypeDefinition self, string fullname)
		{
			if (!self.HasNestedTypes)
			{
				return null;
			}
			Collection<TypeDefinition> nestedTypes = self.NestedTypes;
			for (int i = 0; i < nestedTypes.Count; i++)
			{
				TypeDefinition typeDefinition = nestedTypes[i];
				if (typeDefinition.TypeFullName() == fullname)
				{
					return typeDefinition;
				}
			}
			return null;
		}

		public static bool IsPrimitive(this ElementType self)
		{
			switch (self)
			{
			case ElementType.Boolean:
			case ElementType.Char:
			case ElementType.I1:
			case ElementType.U1:
			case ElementType.I2:
			case ElementType.U2:
			case ElementType.I4:
			case ElementType.U4:
			case ElementType.I8:
			case ElementType.U8:
			case ElementType.R4:
			case ElementType.R8:
			case ElementType.I:
			case ElementType.U:
				return true;
			default:
				return false;
			}
		}

		public static string TypeFullName(this TypeReference self)
		{
			if (!string.IsNullOrEmpty(self.Namespace))
			{
				return self.Namespace + "." + self.Name;
			}
			return self.Name;
		}

		public static bool IsTypeOf(this TypeReference self, string @namespace, string name)
		{
			if (self.Name == name)
			{
				return self.Namespace == @namespace;
			}
			return false;
		}

		public static bool IsTypeSpecification(this TypeReference type)
		{
			switch (type.etype)
			{
			case ElementType.Ptr:
			case ElementType.ByRef:
			case ElementType.Var:
			case ElementType.Array:
			case ElementType.GenericInst:
			case ElementType.FnPtr:
			case ElementType.SzArray:
			case ElementType.MVar:
			case ElementType.CModReqD:
			case ElementType.CModOpt:
			case ElementType.Sentinel:
			case ElementType.Pinned:
				return true;
			default:
				return false;
			}
		}

		public static TypeDefinition CheckedResolve(this TypeReference self)
		{
			return self.Resolve() ?? throw new ResolutionException(self);
		}

		public static bool TryGetCoreLibraryReference(this ModuleDefinition module, out AssemblyNameReference reference)
		{
			Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences;
			for (int i = 0; i < assemblyReferences.Count; i++)
			{
				reference = assemblyReferences[i];
				if (IsCoreLibrary(reference))
				{
					return true;
				}
			}
			reference = null;
			return false;
		}

		public static bool IsCoreLibrary(this ModuleDefinition module)
		{
			if (module.Assembly == null)
			{
				return false;
			}
			if (!IsCoreLibrary(module.Assembly.Name))
			{
				return false;
			}
			if (module.HasImage && module.Read(module, (ModuleDefinition m, MetadataReader reader) => reader.image.GetTableLength(Table.AssemblyRef) > 0))
			{
				return false;
			}
			return true;
		}

		public static void KnownValueType(this TypeReference type)
		{
			if (!type.IsDefinition)
			{
				type.IsValueType = true;
			}
		}

		private static bool IsCoreLibrary(AssemblyNameReference reference)
		{
			string name = reference.Name;
			switch (name)
			{
			default:
				return name == "netstandard";
			case "mscorlib":
			case "System.Runtime":
			case "System.Private.CoreLib":
				return true;
			}
		}

		public static ImageDebugHeaderEntry GetCodeViewEntry(this ImageDebugHeader header)
		{
			return header.GetEntry(ImageDebugType.CodeView);
		}

		public static ImageDebugHeaderEntry GetDeterministicEntry(this ImageDebugHeader header)
		{
			return header.GetEntry(ImageDebugType.Deterministic);
		}

		public static ImageDebugHeader AddDeterministicEntry(this ImageDebugHeader header)
		{
			ImageDebugDirectory directory = default(ImageDebugDirectory);
			directory.Type = ImageDebugType.Deterministic;
			ImageDebugHeaderEntry imageDebugHeaderEntry = new ImageDebugHeaderEntry(directory, Empty<byte>.Array);
			if (header == null)
			{
				return new ImageDebugHeader(imageDebugHeaderEntry);
			}
			ImageDebugHeaderEntry[] array = new ImageDebugHeaderEntry[header.Entries.Length + 1];
			Array.Copy(header.Entries, array, header.Entries.Length);
			array[^1] = imageDebugHeaderEntry;
			return new ImageDebugHeader(array);
		}

		public static ImageDebugHeaderEntry GetEmbeddedPortablePdbEntry(this ImageDebugHeader header)
		{
			return header.GetEntry(ImageDebugType.EmbeddedPortablePdb);
		}

		private static ImageDebugHeaderEntry GetEntry(this ImageDebugHeader header, ImageDebugType type)
		{
			if (!header.HasEntries)
			{
				return null;
			}
			for (int i = 0; i < header.Entries.Length; i++)
			{
				ImageDebugHeaderEntry imageDebugHeaderEntry = header.Entries[i];
				if (imageDebugHeaderEntry.Directory.Type == type)
				{
					return imageDebugHeaderEntry;
				}
			}
			return null;
		}

		public static string GetPdbFileName(string assemblyFileName)
		{
			return Path.ChangeExtension(assemblyFileName, ".pdb");
		}

		public static string GetMdbFileName(string assemblyFileName)
		{
			return assemblyFileName + ".mdb";
		}

		public static bool IsPortablePdb(string fileName)
		{
			using FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
			return IsPortablePdb(stream);
		}

		public static bool IsPortablePdb(Stream stream)
		{
			if (stream.Length < 4)
			{
				return false;
			}
			long position = stream.Position;
			try
			{
				return new BinaryReader(stream).ReadUInt32() == 1112167234;
			}
			finally
			{
				stream.Position = position;
			}
		}

		public static uint ReadCompressedUInt32(this byte[] data, ref int position)
		{
			uint result;
			if ((data[position] & 0x80) == 0)
			{
				result = data[position];
				position++;
			}
			else if ((data[position] & 0x40) == 0)
			{
				result = (uint)((data[position] & -129) << 8);
				result |= data[position + 1];
				position += 2;
			}
			else
			{
				result = (uint)((data[position] & -193) << 24);
				result |= (uint)(data[position + 1] << 16);
				result |= (uint)(data[position + 2] << 8);
				result |= data[position + 3];
				position += 4;
			}
			return result;
		}

		public static MetadataToken GetMetadataToken(this CodedIndex self, uint data)
		{
			uint rid;
			TokenType type;
			switch (self)
			{
			case CodedIndex.TypeDefOrRef:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_006d;
				case 2u:
					goto IL_0078;
				default:
					goto end_IL_0001;
				}
				type = TokenType.TypeDef;
				goto IL_05b3;
			case CodedIndex.HasConstant:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_00ad;
				case 2u:
					goto IL_00b8;
				default:
					goto end_IL_0001;
				}
				type = TokenType.Field;
				goto IL_05b3;
			case CodedIndex.HasCustomAttribute:
				rid = data >> 5;
				switch (data & 0x1F)
				{
				case 0u:
					break;
				case 1u:
					goto IL_013a;
				case 2u:
					goto IL_0145;
				case 3u:
					goto IL_0150;
				case 4u:
					goto IL_015b;
				case 5u:
					goto IL_0166;
				case 6u:
					goto IL_0171;
				case 7u:
					goto IL_017c;
				case 8u:
					goto IL_0183;
				case 9u:
					goto IL_018e;
				case 10u:
					goto IL_0199;
				case 11u:
					goto IL_01a4;
				case 12u:
					goto IL_01af;
				case 13u:
					goto IL_01ba;
				case 14u:
					goto IL_01c5;
				case 15u:
					goto IL_01d0;
				case 16u:
					goto IL_01db;
				case 17u:
					goto IL_01e6;
				case 18u:
					goto IL_01f1;
				case 19u:
					goto IL_01fc;
				case 20u:
					goto IL_0207;
				case 21u:
					goto IL_0212;
				default:
					goto end_IL_0001;
				}
				type = TokenType.Method;
				goto IL_05b3;
			case CodedIndex.HasFieldMarshal:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Param;
				}
				else
				{
					type = TokenType.Field;
				}
				goto IL_05b3;
			}
			case CodedIndex.HasDeclSecurity:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_0271;
				case 2u:
					goto IL_027c;
				default:
					goto end_IL_0001;
				}
				type = TokenType.TypeDef;
				goto IL_05b3;
			case CodedIndex.MemberRefParent:
				rid = data >> 3;
				switch (data & 7)
				{
				case 0u:
					break;
				case 1u:
					goto IL_02b9;
				case 2u:
					goto IL_02c4;
				case 3u:
					goto IL_02cf;
				case 4u:
					goto IL_02da;
				default:
					goto end_IL_0001;
				}
				type = TokenType.TypeDef;
				goto IL_05b3;
			case CodedIndex.HasSemantics:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Property;
				}
				else
				{
					type = TokenType.Event;
				}
				goto IL_05b3;
			}
			case CodedIndex.MethodDefOrRef:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.MemberRef;
				}
				else
				{
					type = TokenType.Method;
				}
				goto IL_05b3;
			}
			case CodedIndex.MemberForwarded:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Method;
				}
				else
				{
					type = TokenType.Field;
				}
				goto IL_05b3;
			}
			case CodedIndex.Implementation:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_038d;
				case 2u:
					goto IL_0398;
				default:
					goto end_IL_0001;
				}
				type = TokenType.File;
				goto IL_05b3;
			case CodedIndex.CustomAttributeType:
			{
				rid = data >> 3;
				uint num = data & 7u;
				if (num != 2)
				{
					if (num != 3)
					{
						break;
					}
					type = TokenType.MemberRef;
				}
				else
				{
					type = TokenType.Method;
				}
				goto IL_05b3;
			}
			case CodedIndex.ResolutionScope:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_03f8;
				case 2u:
					goto IL_0403;
				case 3u:
					goto IL_040e;
				default:
					goto end_IL_0001;
				}
				type = TokenType.Module;
				goto IL_05b3;
			case CodedIndex.TypeOrMethodDef:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Method;
				}
				else
				{
					type = TokenType.TypeDef;
				}
				goto IL_05b3;
			}
			case CodedIndex.HasCustomDebugInformation:
				{
					rid = data >> 5;
					switch (data & 0x1F)
					{
					case 0u:
						break;
					case 1u:
						goto IL_04ce;
					case 2u:
						goto IL_04d9;
					case 3u:
						goto IL_04e4;
					case 4u:
						goto IL_04ef;
					case 5u:
						goto IL_04fa;
					case 6u:
						goto IL_0505;
					case 7u:
						goto IL_0510;
					case 8u:
						goto IL_0517;
					case 9u:
						goto IL_0522;
					case 10u:
						goto IL_052d;
					case 11u:
						goto IL_0535;
					case 12u:
						goto IL_053d;
					case 13u:
						goto IL_0545;
					case 14u:
						goto IL_054d;
					case 15u:
						goto IL_0555;
					case 16u:
						goto IL_055d;
					case 17u:
						goto IL_0565;
					case 18u:
						goto IL_056d;
					case 19u:
						goto IL_0575;
					case 20u:
						goto IL_057d;
					case 21u:
						goto IL_0585;
					case 22u:
						goto IL_058d;
					case 23u:
						goto IL_0595;
					case 24u:
						goto IL_059d;
					case 25u:
						goto IL_05a5;
					case 26u:
						goto IL_05ad;
					default:
						goto end_IL_0001;
					}
					type = TokenType.Method;
					goto IL_05b3;
				}
				IL_05ad:
				type = TokenType.ImportScope;
				goto IL_05b3;
				IL_05a5:
				type = TokenType.LocalConstant;
				goto IL_05b3;
				IL_059d:
				type = TokenType.LocalVariable;
				goto IL_05b3;
				IL_0595:
				type = TokenType.LocalScope;
				goto IL_05b3;
				IL_058d:
				type = TokenType.Document;
				goto IL_05b3;
				IL_0585:
				type = TokenType.MethodSpec;
				goto IL_05b3;
				IL_057d:
				type = TokenType.GenericParamConstraint;
				goto IL_05b3;
				IL_0575:
				type = TokenType.GenericParam;
				goto IL_05b3;
				IL_056d:
				type = TokenType.ManifestResource;
				goto IL_05b3;
				IL_0565:
				type = TokenType.ExportedType;
				goto IL_05b3;
				IL_055d:
				type = TokenType.File;
				goto IL_05b3;
				IL_0555:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_054d:
				type = TokenType.Assembly;
				goto IL_05b3;
				IL_0545:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_053d:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_0535:
				type = TokenType.Signature;
				goto IL_05b3;
				IL_052d:
				type = TokenType.Event;
				goto IL_05b3;
				IL_0522:
				type = TokenType.Property;
				goto IL_05b3;
				IL_0517:
				type = TokenType.Permission;
				goto IL_05b3;
				IL_0510:
				type = TokenType.Module;
				goto IL_05b3;
				IL_0505:
				type = TokenType.MemberRef;
				goto IL_05b3;
				IL_04fa:
				type = TokenType.InterfaceImpl;
				goto IL_05b3;
				IL_04ef:
				type = TokenType.Param;
				goto IL_05b3;
				IL_04e4:
				type = TokenType.TypeDef;
				goto IL_05b3;
				IL_04d9:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_04ce:
				type = TokenType.Field;
				goto IL_05b3;
				IL_01db:
				type = TokenType.File;
				goto IL_05b3;
				IL_01d0:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_01ba:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_01c5:
				type = TokenType.Assembly;
				goto IL_05b3;
				IL_040e:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_0403:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_03f8:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_01af:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_01a4:
				type = TokenType.Signature;
				goto IL_05b3;
				IL_018e:
				type = TokenType.Property;
				goto IL_05b3;
				IL_0199:
				type = TokenType.Event;
				goto IL_05b3;
				IL_0398:
				type = TokenType.ExportedType;
				goto IL_05b3;
				IL_038d:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_0183:
				type = TokenType.Permission;
				goto IL_05b3;
				IL_017c:
				type = TokenType.Module;
				goto IL_05b3;
				IL_0166:
				type = TokenType.InterfaceImpl;
				goto IL_05b3;
				IL_0171:
				type = TokenType.MemberRef;
				goto IL_05b3;
				IL_015b:
				type = TokenType.Param;
				goto IL_05b3;
				IL_0145:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_0150:
				type = TokenType.TypeDef;
				goto IL_05b3;
				IL_013a:
				type = TokenType.Field;
				goto IL_05b3;
				IL_006d:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_02da:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_02cf:
				type = TokenType.Method;
				goto IL_05b3;
				IL_02c4:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_02b9:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_00b8:
				type = TokenType.Property;
				goto IL_05b3;
				IL_027c:
				type = TokenType.Assembly;
				goto IL_05b3;
				IL_0271:
				type = TokenType.Method;
				goto IL_05b3;
				IL_00ad:
				type = TokenType.Param;
				goto IL_05b3;
				IL_05b3:
				return new MetadataToken(type, rid);
				IL_0078:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_0212:
				type = TokenType.MethodSpec;
				goto IL_05b3;
				IL_0207:
				type = TokenType.GenericParamConstraint;
				goto IL_05b3;
				IL_01fc:
				type = TokenType.GenericParam;
				goto IL_05b3;
				IL_01f1:
				type = TokenType.ManifestResource;
				goto IL_05b3;
				IL_01e6:
				type = TokenType.ExportedType;
				goto IL_05b3;
				end_IL_0001:
				break;
			}
			return MetadataToken.Zero;
		}

		public static uint CompressMetadataToken(this CodedIndex self, MetadataToken token)
		{
			uint result = 0u;
			if (token.RID == 0)
			{
				return result;
			}
			switch (self)
			{
			case CodedIndex.TypeDefOrRef:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.TypeRef:
					return result | 1u;
				case TokenType.TypeSpec:
					return result | 2u;
				}
				break;
			case CodedIndex.HasConstant:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.Field:
					return result | 0u;
				case TokenType.Param:
					return result | 1u;
				case TokenType.Property:
					return result | 2u;
				}
				break;
			case CodedIndex.HasCustomAttribute:
				result = token.RID << 5;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 0u;
				case TokenType.Field:
					return result | 1u;
				case TokenType.TypeRef:
					return result | 2u;
				case TokenType.TypeDef:
					return result | 3u;
				case TokenType.Param:
					return result | 4u;
				case TokenType.InterfaceImpl:
					return result | 5u;
				case TokenType.MemberRef:
					return result | 6u;
				case TokenType.Module:
					return result | 7u;
				case TokenType.Permission:
					return result | 8u;
				case TokenType.Property:
					return result | 9u;
				case TokenType.Event:
					return result | 0xAu;
				case TokenType.Signature:
					return result | 0xBu;
				case TokenType.ModuleRef:
					return result | 0xCu;
				case TokenType.TypeSpec:
					return result | 0xDu;
				case TokenType.Assembly:
					return result | 0xEu;
				case TokenType.AssemblyRef:
					return result | 0xFu;
				case TokenType.File:
					return result | 0x10u;
				case TokenType.ExportedType:
					return result | 0x11u;
				case TokenType.ManifestResource:
					return result | 0x12u;
				case TokenType.GenericParam:
					return result | 0x13u;
				case TokenType.GenericParamConstraint:
					return result | 0x14u;
				case TokenType.MethodSpec:
					return result | 0x15u;
				}
				break;
			case CodedIndex.HasFieldMarshal:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Field:
					return result | 0u;
				case TokenType.Param:
					return result | 1u;
				}
				break;
			case CodedIndex.HasDeclSecurity:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.Method:
					return result | 1u;
				case TokenType.Assembly:
					return result | 2u;
				}
				break;
			case CodedIndex.MemberRefParent:
				result = token.RID << 3;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.TypeRef:
					return result | 1u;
				case TokenType.ModuleRef:
					return result | 2u;
				case TokenType.Method:
					return result | 3u;
				case TokenType.TypeSpec:
					return result | 4u;
				}
				break;
			case CodedIndex.HasSemantics:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Event:
					return result | 0u;
				case TokenType.Property:
					return result | 1u;
				}
				break;
			case CodedIndex.MethodDefOrRef:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 0u;
				case TokenType.MemberRef:
					return result | 1u;
				}
				break;
			case CodedIndex.MemberForwarded:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Field:
					return result | 0u;
				case TokenType.Method:
					return result | 1u;
				}
				break;
			case CodedIndex.Implementation:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.File:
					return result | 0u;
				case TokenType.AssemblyRef:
					return result | 1u;
				case TokenType.ExportedType:
					return result | 2u;
				}
				break;
			case CodedIndex.CustomAttributeType:
				result = token.RID << 3;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 2u;
				case TokenType.MemberRef:
					return result | 3u;
				}
				break;
			case CodedIndex.ResolutionScope:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.Module:
					return result | 0u;
				case TokenType.ModuleRef:
					return result | 1u;
				case TokenType.AssemblyRef:
					return result | 2u;
				case TokenType.TypeRef:
					return result | 3u;
				}
				break;
			case CodedIndex.TypeOrMethodDef:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.Method:
					return result | 1u;
				}
				break;
			case CodedIndex.HasCustomDebugInformation:
				result = token.RID << 5;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 0u;
				case TokenType.Field:
					return result | 1u;
				case TokenType.TypeRef:
					return result | 2u;
				case TokenType.TypeDef:
					return result | 3u;
				case TokenType.Param:
					return result | 4u;
				case TokenType.InterfaceImpl:
					return result | 5u;
				case TokenType.MemberRef:
					return result | 6u;
				case TokenType.Module:
					return result | 7u;
				case TokenType.Permission:
					return result | 8u;
				case TokenType.Property:
					return result | 9u;
				case TokenType.Event:
					return result | 0xAu;
				case TokenType.Signature:
					return result | 0xBu;
				case TokenType.ModuleRef:
					return result | 0xCu;
				case TokenType.TypeSpec:
					return result | 0xDu;
				case TokenType.Assembly:
					return result | 0xEu;
				case TokenType.AssemblyRef:
					return result | 0xFu;
				case TokenType.File:
					return result | 0x10u;
				case TokenType.ExportedType:
					return result | 0x11u;
				case TokenType.ManifestResource:
					return result | 0x12u;
				case TokenType.GenericParam:
					return result | 0x13u;
				case TokenType.GenericParamConstraint:
					return result | 0x14u;
				case TokenType.MethodSpec:
					return result | 0x15u;
				case TokenType.Document:
					return result | 0x16u;
				case TokenType.LocalScope:
					return result | 0x17u;
				case TokenType.LocalVariable:
					return result | 0x18u;
				case TokenType.LocalConstant:
					return result | 0x19u;
				case TokenType.ImportScope:
					return result | 0x1Au;
				}
				break;
			}
			throw new ArgumentException();
		}

		public static int GetSize(this CodedIndex self, Func<Table, int> counter)
		{
			int num;
			Table[] array;
			switch (self)
			{
			case CodedIndex.TypeDefOrRef:
				num = 2;
				array = new Table[3]
				{
					Table.TypeDef,
					Table.TypeRef,
					Table.TypeSpec
				};
				break;
			case CodedIndex.HasConstant:
				num = 2;
				array = new Table[3]
				{
					Table.Field,
					Table.Param,
					Table.Property
				};
				break;
			case CodedIndex.HasCustomAttribute:
				num = 5;
				array = new Table[22]
				{
					Table.Method,
					Table.Field,
					Table.TypeRef,
					Table.TypeDef,
					Table.Param,
					Table.InterfaceImpl,
					Table.MemberRef,
					Table.Module,
					Table.DeclSecurity,
					Table.Property,
					Table.Event,
					Table.StandAloneSig,
					Table.ModuleRef,
					Table.TypeSpec,
					Table.Assembly,
					Table.AssemblyRef,
					Table.File,
					Table.ExportedType,
					Table.ManifestResource,
					Table.GenericParam,
					Table.GenericParamConstraint,
					Table.MethodSpec
				};
				break;
			case CodedIndex.HasFieldMarshal:
				num = 1;
				array = new Table[2]
				{
					Table.Field,
					Table.Param
				};
				break;
			case CodedIndex.HasDeclSecurity:
				num = 2;
				array = new Table[3]
				{
					Table.TypeDef,
					Table.Method,
					Table.Assembly
				};
				break;
			case CodedIndex.MemberRefParent:
				num = 3;
				array = new Table[5]
				{
					Table.TypeDef,
					Table.TypeRef,
					Table.ModuleRef,
					Table.Method,
					Table.TypeSpec
				};
				break;
			case CodedIndex.HasSemantics:
				num = 1;
				array = new Table[2]
				{
					Table.Event,
					Table.Property
				};
				break;
			case CodedIndex.MethodDefOrRef:
				num = 1;
				array = new Table[2]
				{
					Table.Method,
					Table.MemberRef
				};
				break;
			case CodedIndex.MemberForwarded:
				num = 1;
				array = new Table[2]
				{
					Table.Field,
					Table.Method
				};
				break;
			case CodedIndex.Implementation:
				num = 2;
				array = new Table[3]
				{
					Table.File,
					Table.AssemblyRef,
					Table.ExportedType
				};
				break;
			case CodedIndex.CustomAttributeType:
				num = 3;
				array = new Table[2]
				{
					Table.Method,
					Table.MemberRef
				};
				break;
			case CodedIndex.ResolutionScope:
				num = 2;
				array = new Table[4]
				{
					Table.Module,
					Table.ModuleRef,
					Table.AssemblyRef,
					Table.TypeRef
				};
				break;
			case CodedIndex.TypeOrMethodDef:
				num = 1;
				array = new Table[2]
				{
					Table.TypeDef,
					Table.Method
				};
				break;
			case CodedIndex.HasCustomDebugInformation:
				num = 5;
				array = new Table[27]
				{
					Table.Method,
					Table.Field,
					Table.TypeRef,
					Table.TypeDef,
					Table.Param,
					Table.InterfaceImpl,
					Table.MemberRef,
					Table.Module,
					Table.DeclSecurity,
					Table.Property,
					Table.Event,
					Table.StandAloneSig,
					Table.ModuleRef,
					Table.TypeSpec,
					Table.Assembly,
					Table.AssemblyRef,
					Table.File,
					Table.ExportedType,
					Table.ManifestResource,
					Table.GenericParam,
					Table.GenericParamConstraint,
					Table.MethodSpec,
					Table.Document,
					Table.LocalScope,
					Table.LocalVariable,
					Table.LocalConstant,
					Table.ImportScope
				};
				break;
			default:
				throw new ArgumentException();
			}
			int num2 = 0;
			for (int i = 0; i < array.Length; i++)
			{
				num2 = Math.Max(counter(array[i]), num2);
			}
			if (num2 >= 1 << 16 - num)
			{
				return 4;
			}
			return 2;
		}

		public static RSA CreateRSA(this StrongNameKeyPair key_pair)
		{
			if (!TryGetKeyContainer(key_pair, out var key, out var key_container))
			{
				return CryptoConvert.FromCapiKeyBlob(key);
			}
			return new RSACryptoServiceProvider(new CspParameters
			{
				Flags = CspProviderFlags.UseMachineKeyStore,
				KeyContainerName = key_container,
				KeyNumber = 2
			});
		}

		private static bool TryGetKeyContainer(ISerializable key_pair, out byte[] key, out string key_container)
		{
			SerializationInfo serializationInfo = new SerializationInfo(typeof(StrongNameKeyPair), new FormatterConverter());
			key_pair.GetObjectData(serializationInfo, default(StreamingContext));
			key = (byte[])serializationInfo.GetValue("_keyPairArray", typeof(byte[]));
			key_container = serializationInfo.GetString("_keyPairContainer");
			return key_container != null;
		}
	}
	public struct ArrayDimension
	{
		private int? lower_bound;

		private int? upper_bound;

		public int? LowerBound
		{
			get
			{
				return lower_bound;
			}
			set
			{
				lower_bound = value;
			}
		}

		public int? UpperBound
		{
			get
			{
				return upper_bound;
			}
			set
			{
				upper_bound = value;
			}
		}

		public bool IsSized
		{
			get
			{
				if (!lower_bound.HasValue)
				{
					return upper_bound.HasValue;
				}
				return true;
			}
		}

		public ArrayDimension(int? lowerBound, int? upperBound)
		{
			lower_bound = lowerBound;
			upper_bound = upperBound;
		}

		public override string ToString()
		{
			if (IsSized)
			{
				return lower_bound + "..." + upper_bound;
			}
			return string.Empty;
		}
	}
	public sealed class ArrayType : TypeSpecification
	{
		private Collection<ArrayDimension> dimensions;

		public Collection<ArrayDimension> Dimensions
		{
			get
			{
				if (dimensions != null)
				{
					return dimensions;
				}
				dimensions = new Collection<ArrayDimension>();
				dimensions.Add(default(ArrayDimension));
				return dimensions;
			}
		}

		public int Rank
		{
			get
			{
				if (dimensions != null)
				{
					return dimensions.Count;
				}
				return 1;
			}
		}

		public bool IsVector
		{
			get
			{
				if (dimensions == null)
				{
					return true;
				}
				if (dimensions.Count > 1)
				{
					return false;
				}
				return !dimensions[0].IsSized;
			}
		}

		public override bool IsValueType
		{
			get
			{
				return false;
			}
			set
			{
				throw new InvalidOperationException();
			}
		}

		public override string Name => base.Name + Suffix;

		public override string FullName => base.FullName + Suffix;

		private string Suffix
		{
			get
			{
				if (IsVector)
				{
					return "[]";
				}
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append("[");
				for (int i = 0; i < dimensions.Count; i++)
				{
					if (i > 0)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.Append(dimensions[i].ToString());
				}
				stringBuilder.Append("]");
				return stringBuilder.ToString();
			}
		}

		public override bool IsArray => true;

		public ArrayType(TypeReference type)
			: base(type)
		{
			Mixin.CheckType(type);
			etype = Mono.Cecil.Metadata.ElementType.Array;
		}

		public ArrayType(TypeReference type, int rank)
			: this(type)
		{
			Mixin.CheckType(type);
			if (rank != 1)
			{
				dimensions = new Collection<ArrayDimension>(rank);
				for (int i = 0; i < rank; i++)
				{
					dimensions.Add(default(ArrayDimension));
				}
				etype = Mono.Cecil.Metadata.ElementType.Array;
			}
		}
	}
	public sealed class AssemblyDefinition : ICustomAttributeProvider, IMetadataTokenProvider, ISecurityDeclarationProvider, IDisposable
	{
		private AssemblyNameDefinition name;

		internal ModuleDefinition main_module;

		private Collection<ModuleDefinition> modules;

		private Collection<CustomAttribute> custom_attributes;

		private Collection<SecurityDeclaration> security_declarations;

		public AssemblyNameDefinition Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}

		public string FullName
		{
			get
			{
				if (name == null)
				{
					return string.Empty;
				}
				return name.FullName;
			}
		}

		public MetadataToken MetadataToken
		{
			get
			{
				return new MetadataToken(TokenType.Assembly, 1);
			}
			set
			{
			}
		}

		public Collection<ModuleDefinition> Modules
		{
			get
			{
				if (modules != null)
				{
					return modules;
				}
				if (main_module.HasImage)
				{
					return main_module.Read(ref modules, this, (AssemblyDefinition _, MetadataReader reader) => reader.ReadModules());
				}
				return modules = new Collection<ModuleDefinition>(1) { main_module };
			}
		}

		public ModuleDefinition MainModule => main_module;

		public MethodDefinition EntryPoint
		{
			get
			{
				return main_module.EntryPoint;
			}
			set
			{
				main_module.EntryPoint = value;
			}
		}

		public bool HasCustomAttributes
		{
			get
			{
				if (custom_attributes != null)
				{
					return custom_attributes.Count > 0;
				}
				return this.GetHasCustomAttributes(main_module);
			}
		}

		public Collection<CustomAttribute> CustomAttributes => custom_attributes ?? this.GetCustomAttributes(ref custom_attributes, main_module);

		public bool HasSecurityDeclarations
		{
			get
			{
				if (security_declarations != null)
				{
					return security_declarations.Count > 0;
				}
				return this.GetHasSecurityDeclarations(main_module);
			}
		}

		public Collection<SecurityDeclaration> SecurityDeclarations => security_declarations ?? this.GetSecurityDeclarations(ref security_declarations, main_module);

		internal AssemblyDefinition()
		{
		}

		public void Dispose()
		{
			if (modules == null)
			{
				main_module.Dispose();
				return;
			}
			Collection<ModuleDefinition> collection = Modules;
			for (int i = 0; i < collection.Count; i++)
			{
				collection[i].Dispose();
			}
		}

		public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind)
		{
			return CreateAssembly(assemblyName, moduleName, new ModuleParameters
			{
				Kind = kind
			});
		}

		public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleParameters parameters)
		{
			if (assemblyName == null)
			{
				throw new ArgumentNullException("assemblyName");
			}
			if (moduleName == null)
			{
				throw new ArgumentNullException("moduleName");
			}
			Mixin.CheckParameters(parameters);
			if (parameters.Kind == ModuleKind.NetModule)
			{
				throw new ArgumentException("kind");
			}
			AssemblyDefinition assembly = ModuleDefinition.CreateModule(moduleName, parameters).Assembly;
			assembly.Name = assemblyName;
			return assembly;
		}

		public static AssemblyDefinition ReadAssembly(string fileName)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(fileName));
		}

		public static AssemblyDefinition ReadAssembly(string fileName, ReaderParameters parameters)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(fileName, parameters));
		}

		public static AssemblyDefinition ReadAssembly(Stream stream)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(stream));
		}

		public static AssemblyDefinition ReadAssembly(Stream stream, ReaderParameters parameters)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(stream, parameters));
		}

		private static AssemblyDefinition ReadAssembly(ModuleDefinition module)
		{
			return module.Assembly ?? throw new ArgumentException();
		}

		public void Write(string fileName)
		{
			Write(fileName, new WriterParameters());
		}

		public void Write(string fileName, WriterParameters parameters)
		{
			main_module.Write(fileName, parameters);
		}

		public void Write()
		{
			main_module.Write();
		}

		public void Write(WriterParameters parameters)
		{
			main_module.Write(parameters);
		}

		public void Write(Stream stream)
		{
			Write(stream, new WriterParameters());
		}

		public void Write(Stream stream, WriterParameters parameters)
		{
			main_module.Write(stream, parameters);
		}

		public override string ToString()
		{
			return FullName;
		}
	}
	[Flags]
	public enum AssemblyAttributes : uint
	{
		PublicKey = 1u,
		SideBySideCompatible = 0u,
		Retargetable = 0x100u,
		WindowsRuntime = 0x200u,
		DisableJITCompileOptimizer = 0x4000u,
		EnableJITCompileTracking = 0x8000u
	}
	public enum AssemblyHashAlgorithm : uint
	{
		None = 0u,
		Reserved = 32771u,
		SHA1 = 32772u
	}
	public sealed class AssemblyLinkedResource : Resource
	{
		private AssemblyNameReference reference;

		public AssemblyNameReference Assembly
		{
			get
			{
				return reference;
			}
			set
			{
				reference = value;
			}
		}

		public override ResourceType ResourceType => ResourceType.AssemblyLinked;

		public AssemblyLinkedResource(string name, ManifestResourceAttributes flags)
			: base(name, flags)
		{
		}

		public AssemblyLinkedResource(string name, ManifestResourceAttributes flags, AssemblyNameReference reference)
			: base(name, flags)
		{
			this.reference = reference;
		}
	}
	public sealed class AssemblyNameDefinition : AssemblyNameReference
	{
		public override byte[] Hash => Empty<byte>.Array;

		internal AssemblyNameDefinition()
		{
			token = new MetadataToken(TokenType.Assembly, 1);
		}

		public AssemblyNameDefinition(string name, Version version)
			: base(name, version)
		{
			token = new MetadataToken(TokenType.Assembly, 1);
		}
	}
	public class AssemblyNameReference : IMetadataScope, IMetadataTokenProvider
	{
		private string name;

		private string culture;

		private Version version;

		private uint attributes;

		private byte[] public_key;

		private byte[] public_key_token;

		private AssemblyHashAlgorithm hash_algorithm;

		private byte[] hash;

		internal MetadataToken token;

		private string full_name;

		public string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
				full_name = null;
			}
		}

		public string Culture
		{
			get
			{
				return culture;
			}
			set
			{
				culture = value;
				full_name = null;
			}
		}

		public Version Version
		{
			get
			{
				return version;
			}
			set
			{
				version = Mixin.CheckVersion(value);
				full_name = null;
			}
		}

		public AssemblyAttributes Attributes
		{
			get
			{
				return (AssemblyAttributes)attributes;
			}
			set
			{
				attributes = (uint)value;
			}
		}

		public bool HasPublicKey
		{
			get
			{
				return attributes.GetAttributes(1u);
			}
			set
			{
				attributes = attributes.SetAttributes(1u, value);
			}
		}

		public bool IsSideBySideCompatible
		{
			get
			{
				return attributes.GetAttributes(0u);
			}
			set
			{
				attributes = attributes.SetAttributes(0u, value);
			}
		}

		public bool IsRetargetable
		{
			get
			{
				return attributes.GetAttributes(256u);
			}
			set
			{
				attributes = attributes.SetAttributes(256u, value);
			}
		}

		public bool IsWindowsRuntime
		{
			get
			{
				return attributes.GetAttributes(512u);
			}
			set
			{
				attributes = attributes.SetAttributes(512u, value);
			}
		}

		public byte[] PublicKey
		{
			get
			{
				return public_key ?? Empty<byte>.Array;
			}
			set
			{
				public_key = value;
				HasPublicKey = !public_key.IsNullOrEmpty();
				public_key_token = Empty<byte>.Array;
				full_name = null;
			}
		}

		public byte[] PublicKeyToken
		{
			get
			{
				if (public_key_token.IsNullOrEmpty() && !public_key.IsNullOrEmpty())
				{
					byte[] array = HashPublicKey();
					byte[] array2 = new byte[8];
					Array.Copy(array, array.Length - 8, array2, 0, 8);
					Array.Reverse((Array)array2, 0, 8);
					public_key_token = array2;
				}
				return public_key_token ?? Empty<byte>.Array;
			}
			set
			{
				public_key_token = value;
				full_name = null;
			}
		}

		public virtual MetadataScopeType MetadataScopeType => MetadataScopeType.AssemblyNameReference;

		public string FullName
		{
			get
			{
				if (full_name != null)
				{
					return full_name;
				}
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(name);
				stringBuilder.Append(", ");
				stringBuilder.Append("Version=");
				stringBuilder.Append(version.ToString(4));
				stringBuilder.Append(", ");
				stringBuilder.Append("Culture=");
				stringBuilder.Append(string.IsNullOrEmpty(culture) ? "neutral" : culture);
				stringBuilder.Append(", ");
				stringBuilder.Append("PublicKeyToken=");
				byte[] publicKeyToken = PublicKeyToken;
				if (!publicKeyToken.IsNullOrEmpty() && publicKeyToken.Length != 0)
				{
					for (int i = 0; i < publicKeyToken.Length; i++)
					{
						stringBuilder.Append(publicKeyToken[i].ToString("x2"));
					}
				}
				else
				{
					stringBuilder.Append("null");
				}
				if (IsRetargetable)
				{
					stringBuilder.Append(", ");
					stringBuilder.Append("Retargetable=Yes");
				}
				return full_name = stringBuilder.ToString();
			}
		}

		public AssemblyHashAlgorithm HashAlgorithm
		{
			get
			{
				return hash_algorithm;
			}
			set
			{
				hash_algorithm = value;
			}
		}

		public virtual byte[] Hash
		{
			get
			{
				return hash;
			}
			set
			{
				hash = value;
			}
		}

		public MetadataToken MetadataToken
		{
			get
			{
				return token;
			}
			set
			{
				token = value;
			}
		}

		private byte[] HashPublicKey()
		{
			AssemblyHashAlgorithm assemblyHashAlgorithm = hash_algorithm;
			HashAlgorithm hashAlgorithm = ((assemblyHashAlgorithm != AssemblyHashAlgorithm.Reserved) ? ((HashAlgorithm)SHA1.Create()) : ((HashAlgorithm)MD5.Create()));
			using (hashAlgorithm)
			{
				return hashAlgorithm.ComputeHash(public_key);
			}
		}

		public static AssemblyNameReference Parse(string fullName)
		{
			if (fullName == null)
			{
				throw new ArgumentNullException("fullName");
			}
			if (fullName.Length == 0)
			{
				throw new ArgumentException("Name can not be empty");
			}
			AssemblyNameReference assemblyNameReference = new AssemblyNameReference();
			string[] array = fullName.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (i == 0)
				{
					assemblyNameReference.Name = text;
					continue;
				}
				string[] array2 = text.Split(new char[1] { '=' });
				if (array2.Length != 2)
				{
					throw new ArgumentException("Malformed name");
				}
				switch (array2[0].ToLowerInvariant())
				{
				case "version":
					assemblyNameReference.Version = new Version(array2[1]);
					break;
				case "culture":
					assemblyNameReference.Culture = ((array2[1] == "neutral") ? "" : array2[1]);
					break;
				case "publickeytoken":
				{
					string text2 = array2[1];
					if (!(text2 == "null"))
					{
						assemblyNameReference.PublicKeyToken = new byte[text2.Length / 2];
						for (int j = 0; j < assemblyNameReference.PublicKeyToken.Length; j++)
						{
							assemblyNameReference.PublicKeyToken[j] = byte.Parse(text2.Substring(j * 2, 2), NumberStyles.HexNumber);
						}
					}
					break;
				}
				}
			}
			return assemblyNameReference;
		}

		internal AssemblyNameReference()
		{
			version = Mixin.ZeroVersion;
			token = new MetadataToken(TokenType.AssemblyRef);
		}

		public AssemblyNameReference(string name, Version version)
		{
			Mixin.CheckName(name);
			this.name = name;
			this.version = Mixin.CheckVersion(version);
			hash_algorithm = AssemblyHashAlgorithm.None;
			token = new MetadataToken(TokenType.AssemblyRef);
		}

		public override string ToString()
		{
			return FullName;
		}
	}
	internal abstract class ModuleReader
	{
		protected readonly ModuleDefinition module;

		protected ModuleReader(Image image, ReadingMode mode)
		{
			module = new ModuleDefinition(image);
			module.ReadingMode = mode;
		}

		protected abstract void ReadModule();

		public abstract void ReadSymbols(ModuleDefinition module);

		protected void ReadModuleManifest(MetadataReader reader)
		{
			reader.Populate(module);
			ReadAssembly(reader);
		}

		private void ReadAssembly(MetadataReader reader)
		{
			AssemblyNameDefinition assemblyNameDefinition = reader.ReadAssemblyNameDefinition();
			if (assemblyNameDefinition == null)
			{
				module.kind = ModuleKind.NetModule;
				return;
			}
			AssemblyDefinition assemblyDefinition = new AssemblyDefinition();
			assemblyDefinition.Name = assemblyNameDefinition;
			module.assembly = assemblyDefinition;
			assemblyDefinition.main_module = module;
		}

		public static ModuleDefinition CreateModule(Image image, ReaderParameters parameters)
		{
			ModuleReader moduleReader = CreateModuleReader(image, parameters.ReadingMode);
			ModuleDefinition moduleDefinition = moduleReader.module;
			if (parameters.assembly_resolver != null)
			{
				moduleDefinition.assembly_resolver = Disposable.NotOwned(parameters.assembly_resolver);
			}
			if (parameters.metadata_resolver != null)
			{
				moduleDefinition.metadata_resolver = parameters.metadata_resolver;
			}
			if (parameters.metadata_importer_provider != null)
			{
				moduleDefinition.metadata_importer = parameters.metadata_importer_provider.GetMetadataImporter(moduleDefinition);
			}
			if (parameters.reflection_importer_provider != null)
			{
				moduleDefinition.reflection_importer = parameters.reflection_importer_provider.GetReflectionImporter(moduleDefinition);
			}
			GetMetadataKind(moduleDefinition, parameters);
			moduleReader.ReadModule();
			ReadSymbols(moduleDefinition, parameters);
			moduleReader.ReadSymbols(moduleDefinition);
			if (parameters.ReadingMode == ReadingMode.Immediate)
			{
				moduleDefinition.MetadataSystem.Clear();
			}
			return moduleDefinition;
		}

		private static void ReadSymbols(ModuleDefinition module, ReaderParameters parameters)
		{
			ISymbolReaderProvider symbolReaderProvider = parameters.SymbolReaderProvider;
			if (symbolReaderProvider == null && parameters.ReadSymbols)
			{
				symbolReaderProvider = new DefaultSymbolReaderProvider();
			}
			if (symbolReaderProvider != null)
			{
				module.SymbolReaderProvider = symbolReaderProvider;
				ISymbolReader symbolReader = ((parameters.SymbolStream != null) ? symbolReaderProvider.GetSymbolReader(module, parameters.SymbolStream) : symbolReaderProvider.GetSymbolReader(module, module.FileName));
				if (symbolReader != null)
				{
					try
					{
						module.ReadSymbols(symbolReader, parameters.ThrowIfSymbolsAreNotMatching);
					}
					catch (Exception)
					{
						symbolReader.Dispose();
						throw;
					}
				}
			}
			if (module.Image.HasDebugTables())
			{
				module.ReadSymbols(new PortablePdbReader(module.Image, module));
			}
		}

		private static void GetMetadataKind(ModuleDefinition module, ReaderParameters parameters)
		{
			if (!parameters.ApplyWindowsRuntimeProjections)
			{
				module.MetadataKind = MetadataKind.Ecma335;
				return;
			}
			string runtimeVersion = module.RuntimeVersion;
			if (!runtimeVersion.Contains("WindowsRuntime"))
			{
				module.MetadataKind = MetadataKind.Ecma335;
			}
			else if (runtimeVersion.Contains("CLR"))
			{
				module.MetadataKind = MetadataKind.ManagedWindowsMetadata;
			}
			else
			{
				module.MetadataKind = MetadataKind.WindowsMetadata;
			}
		}

		private static ModuleReader CreateModuleReader(Image image, ReadingMode mode)
		{
			return mode switch
			{
				ReadingMode.Immediate => new ImmediateModuleReader(image), 
				ReadingMode.Deferred => new DeferredModuleReader(image), 
				_ => throw new ArgumentException(), 
			};
		}
	}
	internal sealed class ImmediateModuleReader : ModuleReader
	{
		private bool resolve_attributes;

		public ImmediateModuleReader(Image image)
			: base(image, ReadingMode.Immediate)
		{
		}

		protected override void ReadModule()
		{
			module.Read(module, delegate(ModuleDefinition module, MetadataReader reader)
			{
				ReadModuleManifest(reader);
				ReadModule(module, resolve_attributes: true);
			});
		}

		public void ReadModule(ModuleDefinition module, bool resolve_attributes)
		{
			this.resolve_attributes = resolve_attributes;
			if (module.HasAssemblyReferences)
			{
				Mixin.Read(module.AssemblyReferences);
			}
			if (module.HasResources)
			{
				Mixin.Read(module.Resources);
			}
			if (module.HasModuleReferences)
			{
				Mixin.Read(module.ModuleReferences);
			}
			if (module.HasTypes)
			{
				ReadTypes(module.Types);
			}
			if (module.HasExportedTypes)
			{
				Mixin.Read(module.ExportedTypes);
			}
			ReadCustomAttributes(module);
			AssemblyDefinition assembly = module.Assembly;
			if (assembly != null)
			{
				ReadCustomAttributes(assembly);
				ReadSecurityDeclarations(assembly);
			}
		}

		private void ReadTypes(Collection<TypeDefinition> types)
		{
			for (int i = 0; i < types.Count; i++)
			{
				ReadType(types[i]);
			}
		}

		private void ReadType(TypeDefinition type)
		{
			ReadGenericParameters(type);
			if (type.HasInterfaces)
			{
				ReadInterfaces(type);
			}
			if (type.HasNestedTypes)
			{
				ReadTypes(type.NestedTypes);
			}
			if (type.HasLayoutInfo)
			{
				Mixin.Read(type.ClassSize);
			}
			if (type.HasFields)
			{
				ReadFields(type);
			}
			if (type.HasMethods)
			{
				ReadMethods(type);
			}
			if (type.HasProperties)
			{
				ReadProperties(type);
			}
			if (type.HasEvents)
			{
				ReadEvents(type);
			}
			ReadSecurityDeclarations(type);
			ReadCustomAttributes(type);
		}

		private void ReadInterfaces(TypeDefinition type)
		{
			Collection<InterfaceImplementation> interfaces = type.Interfaces;
			for (int i = 0; i < interfaces.Count; i++)
			{
				ReadCustomAttributes(interfaces[i]);
			}
		}

		private void ReadGenericParameters(IGenericParameterProvider provider)
		{
			if (!provider.HasGenericParameters)
			{
				return;
			}
			Collection<GenericParameter> genericParameters = provider.GenericParameters;
			for (int i = 0; i < genericParameters.Count; i++)
			{
				GenericParameter genericParameter = genericParameters[i];
				if (genericParameter.HasConstraints)
				{
					Mixin.Read(genericParameter.Constraints);
				}
				ReadCustomAttributes(genericParameter);
			}
		}

		private void ReadSecurityDeclarations(ISecurityDeclarationProvider provider)
		{
			if (!provider.HasSecurityDeclarations)
			{
				return;
			}
			Collection<SecurityDeclaration> securityDeclarations = provider.SecurityDeclarations;
			if (resolve_attributes)
			{
				for (int i = 0; i < securityDeclarations.Count; i++)
				{
					Mixin.Read(securityDeclarations[i].SecurityAttributes);
				}
			}
		}

		private void ReadCustomAttributes(ICustomAttributeProvider provider)
		{
			if (!provider.HasCustomAttributes)
			{
				return;
			}
			Collection<CustomAttribute> customAttributes = provider.CustomAttributes;
			if (resolve_attributes)
			{
				for (int i = 0; i < customAttributes.Count; i++)
				{
					Mixin.Read(customAttributes[i].ConstructorArguments);
				}
			}
		}

		private void ReadFields(TypeDefinition type)
		{
			Collection<FieldDefinition> fields = type.Fields;
			for (int i = 0; i < fields.Count; i++)
			{
				FieldDefinition fieldDefinition = fields[i];
				if (fieldDefinition.HasConstant)
				{
					Mixin.Read(fieldDefinition.Constant);
				}
				if (fieldDefinition.HasLayoutInfo)
				{
					Mixin.Read(fieldDefinition.Offset);
				}
				if (fieldDefinition.RVA > 0)
				{
					Mixin.Read(fieldDefinition.InitialValue);
				}
				if (fieldDefinition.HasMarshalInfo)
				{
					Mixin.Read(fieldDefinition.MarshalInfo);
				}
				ReadCustomAttributes(fieldDefinition);
			}
		}

		private void ReadMethods(TypeDefinition type)
		{
			Collection<MethodDefinition> methods = type.Methods;
			for (int i = 0; i < methods.Count; i++)
			{
				MethodDefinition methodDefinition = methods[i];
				ReadGenericParameters(methodDefinition);
				if (methodDefinition.HasParameters)
				{
					ReadParameters(methodDefinition);
				}
				if (methodDefinition.HasOverrides)
				{
					Mixin.Read(methodDefinition.Overrides);
				}
				if (methodDefinition.IsPInvokeImpl)
				{
					Mixin.Read(methodDefinition.PInvokeInfo);
				}
				ReadSecurityDeclarations(methodDefinition);
				ReadCustomAttributes(methodDefinition);
				MethodReturnType methodReturnType = methodDefinition.MethodReturnType;
				if (methodReturnType.HasConstant)
				{
					Mixin.Read(methodReturnType.Constant);
				}
				if (methodReturnType.HasMarshalInfo)
				{
					Mixin.Read(methodReturnType.MarshalInfo);
				}
				ReadCustomAttributes(methodReturnType);
			}
		}

		private void ReadParameters(MethodDefinition method)
		{
			Collection<ParameterDefinition> parameters = method.Parameters;
			for (int i = 0; i < parameters.Count; i++)
			{
				ParameterDefinition parameterDefinition = parameters[i];
				if (parameterDefinition.HasConstant)
				{
					Mixin.Read(parameterDefinition.Constant);
				}
				if (parameterDefinition.HasMarshalInfo)
				{
					Mixin.Read(parameterDefinition.MarshalInfo);
				}
				ReadCustomAttributes(parameterDefinition);
			}
		}

		private void ReadProperties(TypeDefinition type)
		{
			Collection<PropertyDefinition> properties = type.Properties;
			for (int i = 0; i < properties.Count; i++)
			{
				PropertyDefinition propertyDefinition = properties[i];
				Mixin.Read(propertyDefinition.GetMethod);
				if (propertyDefinition.HasConstant)
				{
					Mixin.Read(propertyDefinition.Constant);
				}
				ReadCustomAttributes(propertyDefinition);
			}
		}

		private void ReadEvents(TypeDefinition type)
		{
			Collection<EventDefinition> events = type.Events;
			for (int i = 0; i < events.Count; i++)
			{
				EventDefinition eventDefinition = events[i];
				Mixin.Read(eventDefinition.AddMethod);
				ReadCustomAttributes(eventDefinition);
			}
		}

		public override void ReadSymbols(ModuleDefinition module)
		{
			if (module.symbol_reader != null)
			{
				ReadTypesSymbols(module.Types, module.symbol_reader);
			}
		}

		private void ReadTypesSymbols(Collection<TypeDefinition> types, ISymbolReader symbol_reader)
		{
			for (int i = 0; i < types.Count; i++)
			{
				TypeDefinition typeDefinition = types[i];
				if (typeDefinition.HasNestedTypes)
				{
					ReadTypesSymbols(typeDefinition.NestedTypes, symbol_reader);
				}
				if (typeDefinition.HasMethods)
				{
					ReadMethodsSymbols(typeDefinition, symbol_reader);
				}
			}
		}

		private void ReadMethodsSymbols(TypeDefinition type, ISymbolReader symbol_reader)
		{
			Collection<MethodDefinition> methods = type.Methods;
			for (int i = 0; i < methods.Count; i++)
			{
				MethodDefinition methodDefinition = methods[i];
				if (methodDefinition.HasBody && methodDefinition.token.RID != 0 && methodDefinition.debug_info == null)
				{
					methodDefinition.debug_info = symbol_reader.Read(methodDefinition);
				}
			}
		}
	}
	internal sealed class DeferredModuleReader : ModuleReader
	{
		public DeferredModuleReader(Image image)
			: base(image, ReadingMode.Deferred)
		{
		}

		protected override void ReadModule()
		{
			module.Read(module, delegate(ModuleDefinition _, MetadataReader reader)
			{
				ReadModuleManifest(reader);
			});
		}

		public override void ReadSymbols(ModuleDefinition module)
		{
		}
	}
	internal sealed class MetadataReader : ByteBuffer
	{
		internal readonly Image image;

		internal readonly ModuleDefinition module;

		internal readonly MetadataSystem metadata;

		internal CodeReader code;

		internal IGenericContext context;

		private readonly MetadataReader metadata_reader;

		public MetadataReader(ModuleDefinition module)
			: base(module.Image.TableHeap.data)
		{
			image = module.Image;
			this.module = module;
			metadata = module.MetadataSystem;
			code = new CodeReader(this);
		}

		public MetadataReader(Image image, ModuleDefinition module, MetadataReader metadata_reader)
			: base(image.TableHeap.data)
		{
			this.image = image;
			this.module = module;
			metadata = module.MetadataSystem;
			this.metadata_reader = metadata_reader;
		}

		private int GetCodedIndexSize(CodedIndex index)
		{
			return image.GetCodedIndexSize(index);
		}

		private uint ReadByIndexSize(int size)
		{
			if (size == 4)
			{
				return ReadUInt32();
			}
			return ReadUInt16();
		}

		private byte[] ReadBlob()
		{
			BlobHeap blobHeap = image.BlobHeap;
			if (blobHeap == null)
			{
				position += 2;
				return Empty<byte>.Array;
			}
			return blobHeap.Read(ReadBlobIndex());
		}

		private byte[] ReadBlob(uint signature)
		{
			BlobHeap blobHeap = image.BlobHeap;
			if (blobHeap == null)
			{
				return Empty<byte>.Array;
			}
			return blobHeap.Read(signature);
		}

		private uint ReadBlobIndex()
		{
			return ReadByIndexSize(image.BlobHeap?.IndexSize ?? 2);
		}

		private void GetBlobView(uint signature, out byte[] blob, out int index, out int count)
		{
			BlobHeap blobHeap = image.BlobHeap;
			if (blobHeap == null)
			{
				blob = null;
				index = (count = 0);
			}
			else
			{
				blobHeap.GetView(signature, out blob, out index, out count);
			}
		}

		private string ReadString()
		{
			return image.StringHeap.Read(ReadByIndexSize(image.StringHeap.IndexSize));
		}

		private uint ReadStringIndex()
		{
			return ReadByIndexSize(image.StringHeap.IndexSize);
		}

		private Guid ReadGuid()
		{
			return image.GuidHeap.Read(ReadByIndexSize(image.GuidHeap.IndexSize));
		}

		private uint ReadTableIndex(Table table)
		{
			return ReadByIndexSize(image.GetTableIndexSize(table));
		}

		private MetadataToken ReadMetadataToken(CodedIndex index)
		{
			return index.GetMetadataToken(ReadByIndexSize(GetCodedIndexSize(index)));
		}

		private int MoveTo(Table table)
		{
			TableInformation tableInformation = image.TableHeap[table];
			if (tableInformation.Length != 0)
			{
				position = (int)tableInformation.Offset;
			}
			return (int)tableInformation.Length;
		}

		private bool MoveTo(Table table, uint row)
		{
			TableInformation tableInformation = image.TableHeap[table];
			uint num = tableInformation.Length;
			if (num == 0 || row > num)
			{
				return false;
			}
			position = (int)(tableInformation.Offset + tableInformation.RowSize * (row - 1));
			return true;
		}

		public AssemblyNameDefinition ReadAssemblyNameDefinition()
		{
			if (MoveTo(Table.Assembly) == 0)
			{
				return null;
			}
			AssemblyNameDefinition assemblyNameDefinition = new AssemblyNameDefinition();
			assemblyNameDefinition.HashAlgorithm = (AssemblyHashAlgorithm)ReadUInt32();
			PopulateVersionAndFlags(assemblyNameDefinition);
			assemblyNameDefinition.PublicKey = ReadBlob();
			PopulateNameAndCulture(assemblyNameDefinition);
			return assemblyNameDefinition;
		}

		public ModuleDefinition Populate(ModuleDefinition module)
		{
			if (MoveTo(Table.Module) == 0)
			{
				return module;
			}
			Advance(2);
			module.Name = ReadString();
			module.Mvid = ReadGuid();
			return module;
		}

		private void InitializeAssemblyReferences()
		{
			if (metadata.AssemblyReferences != null)
			{
				return;
			}
			int num = MoveTo(Table.AssemblyRef);
			AssemblyNameReference[] array = (metadata.AssemblyReferences = new AssemblyNameReference[num]);
			for (uint num2 = 0u; num2 < num; num2++)
			{
				AssemblyNameReference assemblyNameReference = new AssemblyNameReference();
				assemblyNameReference.token = new MetadataToken(TokenType.AssemblyRef, num2 + 1);
				PopulateVersionAndFlags(assemblyNameReference);
				byte[] array2 = ReadBlob();
				if (assemblyNameReference.HasPublicKey)
				{
					assemblyNameReference.PublicKey = array2;
				}
				else
				{
					assemblyNameReference.PublicKeyToken = array2;
				}
				PopulateNameAndCulture(assemblyNameReference);
				assemblyNameReference.Hash = ReadBlob();
				array[num2] = assemblyNameReference;
			}
		}

		public Collection<AssemblyNameReference> ReadAssemblyReferences()
		{
			InitializeAssemblyReferences();
			Collection<AssemblyNameReference> collection = new Collection<AssemblyNameReference>(metadata.AssemblyReferences);
			if (module.IsWindowsMetadata())
			{
				module.Projections.AddVirtualReferences(collection);
			}
			return collection;
		}

		public MethodDefinition ReadEntryPoint()
		{
			if (module.Image.EntryPointToken == 0)
			{
				return null;
			}
			return GetMethodDefinition(new MetadataToken(module.Image.EntryPointToken).RID);
		}

		public Collection<ModuleDefinition> ReadModules()
		{
			Collection<ModuleDefinition> collection = new Collection<ModuleDefinition>(1);
			collection.Add(module);
			int num = MoveTo(Table.File);
			for (uint num2 = 1u; num2 <= num; num2++)
			{
				uint num3 = ReadUInt32();
				string name = ReadString();
				ReadBlobIndex();
				if (num3 == 0)
				{
					ReaderParameters parameters = new ReaderParameters
					{
						ReadingMode = module.ReadingMode,
						SymbolReaderProvider = module.SymbolReaderProvider,
						AssemblyResolver = module.AssemblyResolver
					};
					collection.Add(ModuleDefinition.ReadModule(GetModuleFileName(name), parameters));
				}
			}
			return collection;
		}

		private string GetModuleFileName(string name)
		{
			if (module.FileName == null)
			{
				throw new NotSupportedException();
			}
			return Path.Combine(Path.GetDirectoryName(module.FileName), name);
		}

		private void InitializeModuleReferences()
		{
			if (metadata.ModuleReferences == null)
			{
				int num = MoveTo(Table.ModuleRef);
				ModuleReference[] array = (metadata.ModuleReferences = new ModuleReference[num]);
				for (uint num2 = 0u; num2 < num; num2++)
				{
					ModuleReference moduleReference = new ModuleReference(ReadString());
					moduleReference.token = new MetadataToken(TokenType.ModuleRef, num2 + 1);
					array[num2] = moduleReference;
				}
			}
		}

		public Collection<ModuleReference> ReadModuleReferences()
		{
			InitializeModuleReferences();
			return new Collection<ModuleReference>(metadata.ModuleReferences);
		}

		public bool HasFileResource()
		{
			int num = MoveTo(Table.File);
			if (num == 0)
			{
				return false;
			}
			for (uint num2 = 1u; num2 <= num; num2++)
			{
				if (ReadFileRecord(num2).Col1 == FileAttributes.ContainsNoMetaData)
				{
					return true;
				}
			}
			return false;
		}

		public Collection<Resource> ReadResources()
		{
			int num = MoveTo(Table.ManifestResource);
			Collection<Resource> collection = new Collection<Resource>(num);
			for (int i = 1; i <= num; i++)
			{
				uint offset = ReadUInt32();
				ManifestResourceAttributes manifestResourceAttributes = (ManifestResourceAttributes)ReadUInt32();
				string name = ReadString();
				MetadataToken scope = ReadMetadataToken(CodedIndex.Implementation);
				Resource item;
				if (scope.RID == 0)
				{
					item = new EmbeddedResource(name, manifestResourceAttributes, offset, this);
				}
				else if (scope.TokenType == TokenType.AssemblyRef)
				{
					item = new AssemblyLinkedResource(name, manifestResourceAttributes)
					{
						Assembly = (AssemblyNameReference)GetTypeReferenceScope(scope)
					};
				}
				else
				{
					if (scope.TokenType != TokenType.File)
					{
						continue;
					}
					Row<FileAttributes, string, uint> row = ReadFileRecord(scope.RID);
					item = new LinkedResource(name, manifestResourceAttributes)
					{
						File = row.Col2,
						hash = ReadBlob(row.Col3)
					};
				}
				collection.Add(item);
			}
			return collection;
		}

		private Row<FileAttributes, string, uint> ReadFileRecord(uint rid)
		{
			int num = position;
			if (!MoveTo(Table.File, rid))
			{
				throw new ArgumentException();
			}
			Row<FileAttributes, string, uint> result = new Row<FileAttributes, string, uint>((FileAttributes)ReadUInt32(), ReadString(), ReadBlobIndex());
			position = num;
			return result;
		}

		public byte[] GetManagedResource(uint offset)
		{
			return image.GetReaderAt(image.Resources.VirtualAddress, offset, delegate(uint o, BinaryStreamReader reader)
			{
				reader.Advance((int)o);
				return reader.ReadBytes(reader.ReadInt32());
			}) ?? Empty<byte>.Array;
		}

		private void PopulateVersionAndFlags(AssemblyNameReference name)
		{
			name.Version = new Version(ReadUInt16(), ReadUInt16(), ReadUInt16(), ReadUInt16());
			name.Attributes = (AssemblyAttributes)ReadUInt32();
		}

		private void PopulateNameAndCulture(AssemblyNameReference name)
		{
			name.Name = ReadString();
			name.Culture = ReadString();
		}

		public TypeDefinitionCollection ReadTypes()
		{
			InitializeTypeDefinitions();
			TypeDefinition[] types = metadata.Types;
			int capacity = types.Length - metadata.NestedTypes.Count;
			TypeDefinitionCollection typeDefinitionCollection = new TypeDefinitionCollection(module, capacity);
			foreach (TypeDefinition typeDefinition in types)
			{
				if (!IsNested(typeDefinition.Attributes))
				{
					typeDefinitionCollection.Add(typeDefinition);
				}
			}
			if (image.HasTable(Table.MethodPtr) || image.HasTable(Table.FieldPtr))
			{
				CompleteTypes();
			}
			return typeDefinitionCollection;
		}

		private void CompleteTypes()
		{
			TypeDefinition[] types = metadata.Types;
			foreach (TypeDefinition obj in types)
			{
				Mixin.Read(obj.Fields);
				Mixin.Read(obj.Methods);
			}
		}

		private void InitializeTypeDefinitions()
		{
			if (metadata.Types != null)
			{
				return;
			}
			InitializeNestedTypes();
			InitializeFields();
			InitializeMethods();
			int num = MoveTo(Table.TypeDef);
			TypeDefinition[] array = (metadata.Types = new TypeDefinition[num]);
			for (uint num2 = 0u; num2 < num; num2++)
			{
				if (array[num2] == null)
				{
					array[num2] = ReadType(num2 + 1);
				}
			}
			if (module.IsWindowsMetadata())
			{
				for (uint num3 = 0u; num3 < num; num3++)
				{
					WindowsRuntimeProjections.Project(array[num3]);
				}
			}
		}

		private static bool IsNested(TypeAttributes attributes)
		{
			switch (attributes & TypeAttributes.VisibilityMask)
			{
			case TypeAttributes.NestedPublic:
			case TypeAttributes.NestedPrivate:
			case TypeAttributes.NestedFamily:
			case TypeAttributes.NestedAssembly:
			case TypeAttributes.NestedFamANDAssem:
			case TypeAttributes.VisibilityMask:
				return true;
			default:
				return false;
			}
		}

		public bool HasNestedTypes(TypeDefinition type)
		{
			InitializeNestedTypes();
			if (!metadata.TryGetNestedTypeMapping(type, out var mapping))
			{
				return false;
			}
			return mapping.Count > 0;
		}

		public Collection<TypeDefinition> ReadNestedTypes(TypeDefinition type)
		{
			InitializeNestedTypes();
			if (!metadata.TryGetNestedTypeMapping(type, out var mapping))
			{
				return new MemberDefinitionCollection<TypeDefinition>(type);
			}
			MemberDefinitionCollection<TypeDefinition> memberDefinitionCollection = new MemberDefinitionCollection<TypeDefinition>(type, mapping.Count);
			for (int i = 0; i < mapping.Count; i++)
			{
				TypeDefinition typeDefinition = GetTypeDefinition(mapping[i]);
				if (typeDefinition != null)
				{
					memberDefinitionCollection.Add(typeDefinition);
				}
			}
			metadata.RemoveNestedTypeMapping(type);
			return memberDefinitionCollection;
		}

		private void InitializeNestedTypes()
		{
			if (metadata.NestedTypes != null)
			{
				return;
			}
			int num = MoveTo(Table.NestedClass);
			metadata.NestedTypes = new Dictionary<uint, Collection<uint>>(num);
			metadata.ReverseNestedTypes = new Dictionary<uint, uint>(num);
			if (num != 0)
			{
				for (int i = 1; i <= num; i++)
				{
					uint nested = ReadTableIndex(Table.TypeDef);
					uint declaring = ReadTableIndex(Table.TypeDef);
					AddNestedMapping(declaring, nested);
				}
			}
		}

		private void AddNestedMapping(uint declaring, uint nested)
		{
			metadata.SetNestedTypeMapping(declaring, AddMapping(metadata.NestedTypes, declaring, nested));
			metadata.SetReverseNestedTypeMapping(nested, declaring);
		}

		private static Collection<TValue> AddMapping<TKey, TValue>(Dictionary<TKey, Collection<TValue>> cache, TKey key, TValue value)
		{
			if (!cache.TryGetValue(key, out var value2))
			{
				value2 = new Collection<TValue>();
			}
			value2.Add(value);
			return value2;
		}

		private TypeDefinition ReadType(uint rid)
		{
			if (!MoveTo(Table.TypeDef, rid))
			{
				return null;
			}
			TypeAttributes attributes = (TypeAttributes)ReadUInt32();
			string name = ReadString();
			TypeDefinition typeDefinition = new TypeDefinition(ReadString(), name, attributes);
			typeDefinition.token = new MetadataToken(TokenType.TypeDef, rid);
			typeDefinition.scope = module;
			typeDefinition.module = module;
			metadata.AddTypeDefinition(typeDefinition);
			context = typeDefinition;
			typeDefinition.BaseType = GetTypeDefOrRef(ReadMetadataToken(CodedIndex.TypeDefOrRef));
			typeDefinition.fields_range = ReadListRange(rid, Table.TypeDef, Table.Field);
			typeDefinition.methods_range = ReadListRange(rid, Table.TypeDef, Table.Method);
			if (IsNested(attributes))
			{
				typeDefinition.DeclaringType = GetNestedTypeDeclaringType(typeDefinition);
			}
			return typeDefinition;
		}

		private TypeDefinition GetNestedTypeDeclaringType(TypeDefinition type)
		{
			if (!metadata.TryGetReverseNestedTypeMapping(type, out var declaring))
			{
				return null;
			}
			metadata.RemoveReverseNestedTypeMapping(type);
			return GetTypeDefinition(declaring);
		}

		private Range ReadListRange(uint current_index, Table current, Table target)
		{
			Range result = default(Range);
			uint num = ReadTableIndex(target);
			if (num == 0)
			{
				return result;
			}
			TableInformation tableInformation = image.TableHeap[current];
			uint num2;
			if (current_index == tableInformation.Length)
			{
				num2 = image.TableHeap[target].Length + 1;
			}
			else
			{
				int num3 = position;
				position += (int)(tableInformation.RowSize - image.GetTableIndexSize(target));
				num2 = ReadTableIndex(target);
				position = num3;
			}
			result.Start = num;
			result.Length = num2 - num;
			return result;
		}

		public Row<short, int> ReadTypeLayout(TypeDefinition type)
		{
			InitializeTypeLayouts();
			uint rID = type.token.RID;
			if (!metadata.ClassLayouts.TryGetValue(rID, out var value))
			{
				return new Row<short, int>(-1, -1);
			}
			type.PackingSize = (short)value.Col1;
			type.ClassSize = (int)value.Col2;
			metadata.ClassLayouts.Remove(rID);
			return new Row<short, int>((short)value.Col1, (int)value.Col2);
		}

		private void InitializeTypeLayouts()
		{
			if (metadata.ClassLayouts == null)
			{
				int num = MoveTo(Table.ClassLayout);
				Dictionary<uint, Row<ushort, uint>> dictionary = (metadata.ClassLayouts = new Dictionary<uint, Row<ushort, uint>>(num));
				for (uint num2 = 0u; 

BepInEx/core/Mono.Cecil.Mdb.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil.Mdb")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyVersion("0.10.4.0")]
namespace Mono.CompilerServices.SymbolWriter
{
	public class MonoSymbolFileException : Exception
	{
		public MonoSymbolFileException()
		{
		}

		public MonoSymbolFileException(string message, params object[] args)
			: base(string.Format(message, args))
		{
		}

		public MonoSymbolFileException(string message, Exception innerException)
			: base(message, innerException)
		{
		}
	}
	internal sealed class MyBinaryWriter : BinaryWriter
	{
		public MyBinaryWriter(Stream stream)
			: base(stream)
		{
		}

		public void WriteLeb128(int value)
		{
			Write7BitEncodedInt(value);
		}
	}
	internal class MyBinaryReader : BinaryReader
	{
		public MyBinaryReader(Stream stream)
			: base(stream)
		{
		}

		public int ReadLeb128()
		{
			return Read7BitEncodedInt();
		}

		public string ReadString(int offset)
		{
			long position = BaseStream.Position;
			BaseStream.Position = offset;
			string result = ReadString();
			BaseStream.Position = position;
			return result;
		}
	}
	public interface ISourceFile
	{
		SourceFileEntry Entry { get; }
	}
	public interface ICompileUnit
	{
		CompileUnitEntry Entry { get; }
	}
	public interface IMethodDef
	{
		string Name { get; }

		int Token { get; }
	}
	public class MonoSymbolFile : IDisposable
	{
		private List<MethodEntry> methods = new List<MethodEntry>();

		private List<SourceFileEntry> sources = new List<SourceFileEntry>();

		private List<CompileUnitEntry> comp_units = new List<CompileUnitEntry>();

		private Dictionary<int, AnonymousScopeEntry> anonymous_scopes;

		private OffsetTable ot;

		private int last_type_index;

		private int last_method_index;

		private int last_namespace_index;

		public readonly int MajorVersion = 50;

		public readonly int MinorVersion;

		public int NumLineNumbers;

		private MyBinaryReader reader;

		private Dictionary<int, SourceFileEntry> source_file_hash;

		private Dictionary<int, CompileUnitEntry> compile_unit_hash;

		private List<MethodEntry> method_list;

		private Dictionary<int, MethodEntry> method_token_hash;

		private Dictionary<string, int> source_name_hash;

		private Guid guid;

		internal int LineNumberCount;

		internal int LocalCount;

		internal int StringSize;

		internal int LineNumberSize;

		internal int ExtendedLineNumberSize;

		public int CompileUnitCount => ot.CompileUnitCount;

		public int SourceCount => ot.SourceCount;

		public int MethodCount => ot.MethodCount;

		public int TypeCount => ot.TypeCount;

		public int AnonymousScopeCount => ot.AnonymousScopeCount;

		public int NamespaceCount => last_namespace_index;

		public Guid Guid => guid;

		public OffsetTable OffsetTable => ot;

		public SourceFileEntry[] Sources
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				SourceFileEntry[] array = new SourceFileEntry[SourceCount];
				for (int i = 0; i < SourceCount; i++)
				{
					array[i] = GetSourceFile(i + 1);
				}
				return array;
			}
		}

		public CompileUnitEntry[] CompileUnits
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				CompileUnitEntry[] array = new CompileUnitEntry[CompileUnitCount];
				for (int i = 0; i < CompileUnitCount; i++)
				{
					array[i] = GetCompileUnit(i + 1);
				}
				return array;
			}
		}

		public MethodEntry[] Methods
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				lock (this)
				{
					read_methods();
					MethodEntry[] array = new MethodEntry[MethodCount];
					method_list.CopyTo(array, 0);
					return array;
				}
			}
		}

		internal MyBinaryReader BinaryReader
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				return reader;
			}
		}

		public MonoSymbolFile()
		{
			ot = new OffsetTable();
		}

		public int AddSource(SourceFileEntry source)
		{
			sources.Add(source);
			return sources.Count;
		}

		public int AddCompileUnit(CompileUnitEntry entry)
		{
			comp_units.Add(entry);
			return comp_units.Count;
		}

		public void AddMethod(MethodEntry entry)
		{
			methods.Add(entry);
		}

		public MethodEntry DefineMethod(CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			MethodEntry methodEntry = new MethodEntry(this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id);
			AddMethod(methodEntry);
			return methodEntry;
		}

		internal void DefineAnonymousScope(int id)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			if (anonymous_scopes == null)
			{
				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>();
			}
			anonymous_scopes.Add(id, new AnonymousScopeEntry(id));
		}

		internal void DefineCapturedVariable(int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			anonymous_scopes[scope_id].AddCapturedVariable(name, captured_name, kind);
		}

		internal void DefineCapturedScope(int scope_id, int id, string captured_name)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			anonymous_scopes[scope_id].AddCapturedScope(id, captured_name);
		}

		internal int GetNextTypeIndex()
		{
			return ++last_type_index;
		}

		internal int GetNextMethodIndex()
		{
			return ++last_method_index;
		}

		internal int GetNextNamespaceIndex()
		{
			return ++last_namespace_index;
		}

		private void Write(MyBinaryWriter bw, Guid guid)
		{
			bw.Write(5037318119232611860L);
			bw.Write(MajorVersion);
			bw.Write(MinorVersion);
			bw.Write(guid.ToByteArray());
			long position = bw.BaseStream.Position;
			ot.Write(bw, MajorVersion, MinorVersion);
			methods.Sort();
			for (int i = 0; i < methods.Count; i++)
			{
				methods[i].Index = i + 1;
			}
			ot.DataSectionOffset = (int)bw.BaseStream.Position;
			foreach (SourceFileEntry source in sources)
			{
				source.WriteData(bw);
			}
			foreach (CompileUnitEntry comp_unit in comp_units)
			{
				comp_unit.WriteData(bw);
			}
			foreach (MethodEntry method in methods)
			{
				method.WriteData(this, bw);
			}
			ot.DataSectionSize = (int)bw.BaseStream.Position - ot.DataSectionOffset;
			ot.MethodTableOffset = (int)bw.BaseStream.Position;
			for (int j = 0; j < methods.Count; j++)
			{
				methods[j].Write(bw);
			}
			ot.MethodTableSize = (int)bw.BaseStream.Position - ot.MethodTableOffset;
			ot.SourceTableOffset = (int)bw.BaseStream.Position;
			for (int k = 0; k < sources.Count; k++)
			{
				sources[k].Write(bw);
			}
			ot.SourceTableSize = (int)bw.BaseStream.Position - ot.SourceTableOffset;
			ot.CompileUnitTableOffset = (int)bw.BaseStream.Position;
			for (int l = 0; l < comp_units.Count; l++)
			{
				comp_units[l].Write(bw);
			}
			ot.CompileUnitTableSize = (int)bw.BaseStream.Position - ot.CompileUnitTableOffset;
			ot.AnonymousScopeCount = ((anonymous_scopes != null) ? anonymous_scopes.Count : 0);
			ot.AnonymousScopeTableOffset = (int)bw.BaseStream.Position;
			if (anonymous_scopes != null)
			{
				foreach (AnonymousScopeEntry value in anonymous_scopes.Values)
				{
					value.Write(bw);
				}
			}
			ot.AnonymousScopeTableSize = (int)bw.BaseStream.Position - ot.AnonymousScopeTableOffset;
			ot.TypeCount = last_type_index;
			ot.MethodCount = methods.Count;
			ot.SourceCount = sources.Count;
			ot.CompileUnitCount = comp_units.Count;
			ot.TotalFileSize = (int)bw.BaseStream.Position;
			bw.Seek((int)position, SeekOrigin.Begin);
			ot.Write(bw, MajorVersion, MinorVersion);
			bw.Seek(0, SeekOrigin.End);
		}

		public void CreateSymbolFile(Guid guid, FileStream fs)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			Write(new MyBinaryWriter(fs), guid);
		}

		private MonoSymbolFile(Stream stream)
		{
			reader = new MyBinaryReader(stream);
			try
			{
				long num = reader.ReadInt64();
				int num2 = reader.ReadInt32();
				int num3 = reader.ReadInt32();
				if (num != 5037318119232611860L)
				{
					throw new MonoSymbolFileException("Symbol file is not a valid");
				}
				if (num2 != 50)
				{
					throw new MonoSymbolFileException("Symbol file has version {0} but expected {1}", num2, 50);
				}
				if (num3 != 0)
				{
					throw new MonoSymbolFileException("Symbol file has version {0}.{1} but expected {2}.{3}", num2, num3, 50, 0);
				}
				MajorVersion = num2;
				MinorVersion = num3;
				guid = new Guid(reader.ReadBytes(16));
				ot = new OffsetTable(reader, num2, num3);
			}
			catch (Exception innerException)
			{
				throw new MonoSymbolFileException("Cannot read symbol file", innerException);
			}
			source_file_hash = new Dictionary<int, SourceFileEntry>();
			compile_unit_hash = new Dictionary<int, CompileUnitEntry>();
		}

		public static MonoSymbolFile ReadSymbolFile(Assembly assembly)
		{
			string mdbFilename = assembly.Location + ".mdb";
			Guid moduleVersionId = assembly.GetModules()[0].ModuleVersionId;
			return ReadSymbolFile(mdbFilename, moduleVersionId);
		}

		public static MonoSymbolFile ReadSymbolFile(string mdbFilename)
		{
			return ReadSymbolFile(new FileStream(mdbFilename, FileMode.Open, FileAccess.Read));
		}

		public static MonoSymbolFile ReadSymbolFile(string mdbFilename, Guid assemblyGuid)
		{
			MonoSymbolFile monoSymbolFile = ReadSymbolFile(mdbFilename);
			if (assemblyGuid != monoSymbolFile.guid)
			{
				throw new MonoSymbolFileException("Symbol file `{0}' does not match assembly", mdbFilename);
			}
			return monoSymbolFile;
		}

		public static MonoSymbolFile ReadSymbolFile(Stream stream)
		{
			return new MonoSymbolFile(stream);
		}

		public SourceFileEntry GetSourceFile(int index)
		{
			if (index < 1 || index > ot.SourceCount)
			{
				throw new ArgumentException();
			}
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (source_file_hash.TryGetValue(index, out var value))
				{
					return value;
				}
				long position = reader.BaseStream.Position;
				reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1);
				value = new SourceFileEntry(this, reader);
				source_file_hash.Add(index, value);
				reader.BaseStream.Position = position;
				return value;
			}
		}

		public CompileUnitEntry GetCompileUnit(int index)
		{
			if (index < 1 || index > ot.CompileUnitCount)
			{
				throw new ArgumentException();
			}
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (compile_unit_hash.TryGetValue(index, out var value))
				{
					return value;
				}
				long position = reader.BaseStream.Position;
				reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1);
				value = new CompileUnitEntry(this, reader);
				compile_unit_hash.Add(index, value);
				reader.BaseStream.Position = position;
				return value;
			}
		}

		private void read_methods()
		{
			lock (this)
			{
				if (method_token_hash == null)
				{
					method_token_hash = new Dictionary<int, MethodEntry>();
					method_list = new List<MethodEntry>();
					long position = reader.BaseStream.Position;
					reader.BaseStream.Position = ot.MethodTableOffset;
					for (int i = 0; i < MethodCount; i++)
					{
						MethodEntry methodEntry = new MethodEntry(this, reader, i + 1);
						method_token_hash.Add(methodEntry.Token, methodEntry);
						method_list.Add(methodEntry);
					}
					reader.BaseStream.Position = position;
				}
			}
		}

		public MethodEntry GetMethodByToken(int token)
		{
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				read_methods();
				method_token_hash.TryGetValue(token, out var value);
				return value;
			}
		}

		public MethodEntry GetMethod(int index)
		{
			if (index < 1 || index > ot.MethodCount)
			{
				throw new ArgumentException();
			}
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				read_methods();
				return method_list[index - 1];
			}
		}

		public int FindSource(string file_name)
		{
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (source_name_hash == null)
				{
					source_name_hash = new Dictionary<string, int>();
					for (int i = 0; i < ot.SourceCount; i++)
					{
						SourceFileEntry sourceFile = GetSourceFile(i + 1);
						source_name_hash.Add(sourceFile.FileName, i);
					}
				}
				if (!source_name_hash.TryGetValue(file_name, out var value))
				{
					return -1;
				}
				return value;
			}
		}

		public AnonymousScopeEntry GetAnonymousScope(int id)
		{
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (anonymous_scopes != null)
				{
					anonymous_scopes.TryGetValue(id, out var value);
					return value;
				}
				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>();
				reader.BaseStream.Position = ot.AnonymousScopeTableOffset;
				for (int i = 0; i < ot.AnonymousScopeCount; i++)
				{
					AnonymousScopeEntry value = new AnonymousScopeEntry(reader);
					anonymous_scopes.Add(value.ID, value);
				}
				return anonymous_scopes[id];
			}
		}

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

		protected virtual void Dispose(bool disposing)
		{
			if (disposing && reader != null)
			{
				reader.Close();
				reader = null;
			}
		}
	}
	public class OffsetTable
	{
		[Flags]
		public enum Flags
		{
			IsAspxSource = 1,
			WindowsFileNames = 2
		}

		public const int MajorVersion = 50;

		public const int MinorVersion = 0;

		public const long Magic = 5037318119232611860L;

		public int TotalFileSize;

		public int DataSectionOffset;

		public int DataSectionSize;

		public int CompileUnitCount;

		public int CompileUnitTableOffset;

		public int CompileUnitTableSize;

		public int SourceCount;

		public int SourceTableOffset;

		public int SourceTableSize;

		public int MethodCount;

		public int MethodTableOffset;

		public int MethodTableSize;

		public int TypeCount;

		public int AnonymousScopeCount;

		public int AnonymousScopeTableOffset;

		public int AnonymousScopeTableSize;

		public Flags FileFlags;

		public int LineNumberTable_LineBase = -1;

		public int LineNumberTable_LineRange = 8;

		public int LineNumberTable_OpcodeBase = 9;

		internal OffsetTable()
		{
			int platform = (int)Environment.OSVersion.Platform;
			if (platform != 4 && platform != 128)
			{
				FileFlags |= Flags.WindowsFileNames;
			}
		}

		internal OffsetTable(BinaryReader reader, int major_version, int minor_version)
		{
			TotalFileSize = reader.ReadInt32();
			DataSectionOffset = reader.ReadInt32();
			DataSectionSize = reader.ReadInt32();
			CompileUnitCount = reader.ReadInt32();
			CompileUnitTableOffset = reader.ReadInt32();
			CompileUnitTableSize = reader.ReadInt32();
			SourceCount = reader.ReadInt32();
			SourceTableOffset = reader.ReadInt32();
			SourceTableSize = reader.ReadInt32();
			MethodCount = reader.ReadInt32();
			MethodTableOffset = reader.ReadInt32();
			MethodTableSize = reader.ReadInt32();
			TypeCount = reader.ReadInt32();
			AnonymousScopeCount = reader.ReadInt32();
			AnonymousScopeTableOffset = reader.ReadInt32();
			AnonymousScopeTableSize = reader.ReadInt32();
			LineNumberTable_LineBase = reader.ReadInt32();
			LineNumberTable_LineRange = reader.ReadInt32();
			LineNumberTable_OpcodeBase = reader.ReadInt32();
			FileFlags = (Flags)reader.ReadInt32();
		}

		internal void Write(BinaryWriter bw, int major_version, int minor_version)
		{
			bw.Write(TotalFileSize);
			bw.Write(DataSectionOffset);
			bw.Write(DataSectionSize);
			bw.Write(CompileUnitCount);
			bw.Write(CompileUnitTableOffset);
			bw.Write(CompileUnitTableSize);
			bw.Write(SourceCount);
			bw.Write(SourceTableOffset);
			bw.Write(SourceTableSize);
			bw.Write(MethodCount);
			bw.Write(MethodTableOffset);
			bw.Write(MethodTableSize);
			bw.Write(TypeCount);
			bw.Write(AnonymousScopeCount);
			bw.Write(AnonymousScopeTableOffset);
			bw.Write(AnonymousScopeTableSize);
			bw.Write(LineNumberTable_LineBase);
			bw.Write(LineNumberTable_LineRange);
			bw.Write(LineNumberTable_OpcodeBase);
			bw.Write((int)FileFlags);
		}

		public override string ToString()
		{
			return $"OffsetTable [{TotalFileSize} - {DataSectionOffset}:{DataSectionSize} - {SourceCount}:{SourceTableOffset}:{SourceTableSize} - {MethodCount}:{MethodTableOffset}:{MethodTableSize} - {TypeCount}]";
		}
	}
	public class LineNumberEntry
	{
		public sealed class LocationComparer : IComparer<LineNumberEntry>
		{
			public static readonly LocationComparer Default = new LocationComparer();

			public int Compare(LineNumberEntry l1, LineNumberEntry l2)
			{
				if (l1.Row != l2.Row)
				{
					int row = l1.Row;
					return row.CompareTo(l2.Row);
				}
				return l1.Column.CompareTo(l2.Column);
			}
		}

		public readonly int Row;

		public int Column;

		public int EndRow;

		public int EndColumn;

		public readonly int File;

		public readonly int Offset;

		public readonly bool IsHidden;

		public static readonly LineNumberEntry Null = new LineNumberEntry(0, 0, 0, 0);

		public LineNumberEntry(int file, int row, int column, int offset)
			: this(file, row, column, offset, is_hidden: false)
		{
		}

		public LineNumberEntry(int file, int row, int offset)
			: this(file, row, -1, offset, is_hidden: false)
		{
		}

		public LineNumberEntry(int file, int row, int column, int offset, bool is_hidden)
			: this(file, row, column, -1, -1, offset, is_hidden)
		{
		}

		public LineNumberEntry(int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden)
		{
			File = file;
			Row = row;
			Column = column;
			EndRow = end_row;
			EndColumn = end_column;
			Offset = offset;
			IsHidden = is_hidden;
		}

		public override string ToString()
		{
			return $"[Line {File}:{Row},{Column}-{EndRow},{EndColumn}:{Offset}]";
		}
	}
	public class CodeBlockEntry
	{
		public enum Type
		{
			Lexical = 1,
			CompilerGenerated,
			IteratorBody,
			IteratorDispatcher
		}

		public int Index;

		public int Parent;

		public Type BlockType;

		public int StartOffset;

		public int EndOffset;

		public CodeBlockEntry(int index, int parent, Type type, int start_offset)
		{
			Index = index;
			Parent = parent;
			BlockType = type;
			StartOffset = start_offset;
		}

		internal CodeBlockEntry(int index, MyBinaryReader reader)
		{
			Index = index;
			int num = reader.ReadLeb128();
			BlockType = (Type)(num & 0x3F);
			Parent = reader.ReadLeb128();
			StartOffset = reader.ReadLeb128();
			EndOffset = reader.ReadLeb128();
			if (((uint)num & 0x40u) != 0)
			{
				int num2 = reader.ReadInt16();
				reader.BaseStream.Position += num2;
			}
		}

		public void Close(int end_offset)
		{
			EndOffset = end_offset;
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128((int)BlockType);
			bw.WriteLeb128(Parent);
			bw.WriteLeb128(StartOffset);
			bw.WriteLeb128(EndOffset);
		}

		public override string ToString()
		{
			return $"[CodeBlock {Index}:{Parent}:{BlockType}:{StartOffset}:{EndOffset}]";
		}
	}
	public struct LocalVariableEntry
	{
		public readonly int Index;

		public readonly string Name;

		public readonly int BlockIndex;

		public LocalVariableEntry(int index, string name, int block)
		{
			Index = index;
			Name = name;
			BlockIndex = block;
		}

		internal LocalVariableEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			Index = reader.ReadLeb128();
			Name = reader.ReadString();
			BlockIndex = reader.ReadLeb128();
		}

		internal void Write(MonoSymbolFile file, MyBinaryWriter bw)
		{
			bw.WriteLeb128(Index);
			bw.Write(Name);
			bw.WriteLeb128(BlockIndex);
		}

		public override string ToString()
		{
			return $"[LocalVariable {Name}:{Index}:{BlockIndex - 1}]";
		}
	}
	public struct CapturedVariable
	{
		public enum CapturedKind : byte
		{
			Local,
			Parameter,
			This
		}

		public readonly string Name;

		public readonly string CapturedName;

		public readonly CapturedKind Kind;

		public CapturedVariable(string name, string captured_name, CapturedKind kind)
		{
			Name = name;
			CapturedName = captured_name;
			Kind = kind;
		}

		internal CapturedVariable(MyBinaryReader reader)
		{
			Name = reader.ReadString();
			CapturedName = reader.ReadString();
			Kind = (CapturedKind)reader.ReadByte();
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.Write(Name);
			bw.Write(CapturedName);
			bw.Write((byte)Kind);
		}

		public override string ToString()
		{
			return $"[CapturedVariable {Name}:{CapturedName}:{Kind}]";
		}
	}
	public struct CapturedScope
	{
		public readonly int Scope;

		public readonly string CapturedName;

		public CapturedScope(int scope, string captured_name)
		{
			Scope = scope;
			CapturedName = captured_name;
		}

		internal CapturedScope(MyBinaryReader reader)
		{
			Scope = reader.ReadLeb128();
			CapturedName = reader.ReadString();
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128(Scope);
			bw.Write(CapturedName);
		}

		public override string ToString()
		{
			return $"[CapturedScope {Scope}:{CapturedName}]";
		}
	}
	public struct ScopeVariable
	{
		public readonly int Scope;

		public readonly int Index;

		public ScopeVariable(int scope, int index)
		{
			Scope = scope;
			Index = index;
		}

		internal ScopeVariable(MyBinaryReader reader)
		{
			Scope = reader.ReadLeb128();
			Index = reader.ReadLeb128();
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128(Scope);
			bw.WriteLeb128(Index);
		}

		public override string ToString()
		{
			return $"[ScopeVariable {Scope}:{Index}]";
		}
	}
	public class AnonymousScopeEntry
	{
		public readonly int ID;

		private List<CapturedVariable> captured_vars = new List<CapturedVariable>();

		private List<CapturedScope> captured_scopes = new List<CapturedScope>();

		public CapturedVariable[] CapturedVariables
		{
			get
			{
				CapturedVariable[] array = new CapturedVariable[captured_vars.Count];
				captured_vars.CopyTo(array, 0);
				return array;
			}
		}

		public CapturedScope[] CapturedScopes
		{
			get
			{
				CapturedScope[] array = new CapturedScope[captured_scopes.Count];
				captured_scopes.CopyTo(array, 0);
				return array;
			}
		}

		public AnonymousScopeEntry(int id)
		{
			ID = id;
		}

		internal AnonymousScopeEntry(MyBinaryReader reader)
		{
			ID = reader.ReadLeb128();
			int num = reader.ReadLeb128();
			for (int i = 0; i < num; i++)
			{
				captured_vars.Add(new CapturedVariable(reader));
			}
			int num2 = reader.ReadLeb128();
			for (int j = 0; j < num2; j++)
			{
				captured_scopes.Add(new CapturedScope(reader));
			}
		}

		internal void AddCapturedVariable(string name, string captured_name, CapturedVariable.CapturedKind kind)
		{
			captured_vars.Add(new CapturedVariable(name, captured_name, kind));
		}

		internal void AddCapturedScope(int scope, string captured_name)
		{
			captured_scopes.Add(new CapturedScope(scope, captured_name));
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128(ID);
			bw.WriteLeb128(captured_vars.Count);
			foreach (CapturedVariable captured_var in captured_vars)
			{
				captured_var.Write(bw);
			}
			bw.WriteLeb128(captured_scopes.Count);
			foreach (CapturedScope captured_scope in captured_scopes)
			{
				captured_scope.Write(bw);
			}
		}

		public override string ToString()
		{
			return $"[AnonymousScope {ID}]";
		}
	}
	public class CompileUnitEntry : ICompileUnit
	{
		public readonly int Index;

		private int DataOffset;

		private MonoSymbolFile file;

		private SourceFileEntry source;

		private List<SourceFileEntry> include_files;

		private List<NamespaceEntry> namespaces;

		private bool creating;

		public static int Size => 8;

		CompileUnitEntry ICompileUnit.Entry => this;

		public SourceFileEntry SourceFile
		{
			get
			{
				if (creating)
				{
					return source;
				}
				ReadData();
				return source;
			}
		}

		public NamespaceEntry[] Namespaces
		{
			get
			{
				ReadData();
				NamespaceEntry[] array = new NamespaceEntry[namespaces.Count];
				namespaces.CopyTo(array, 0);
				return array;
			}
		}

		public SourceFileEntry[] IncludeFiles
		{
			get
			{
				ReadData();
				if (include_files == null)
				{
					return new SourceFileEntry[0];
				}
				SourceFileEntry[] array = new SourceFileEntry[include_files.Count];
				include_files.CopyTo(array, 0);
				return array;
			}
		}

		public CompileUnitEntry(MonoSymbolFile file, SourceFileEntry source)
		{
			this.file = file;
			this.source = source;
			Index = file.AddCompileUnit(this);
			creating = true;
			namespaces = new List<NamespaceEntry>();
		}

		public void AddFile(SourceFileEntry file)
		{
			if (!creating)
			{
				throw new InvalidOperationException();
			}
			if (include_files == null)
			{
				include_files = new List<SourceFileEntry>();
			}
			include_files.Add(file);
		}

		public int DefineNamespace(string name, string[] using_clauses, int parent)
		{
			if (!creating)
			{
				throw new InvalidOperationException();
			}
			int nextNamespaceIndex = file.GetNextNamespaceIndex();
			NamespaceEntry item = new NamespaceEntry(name, nextNamespaceIndex, using_clauses, parent);
			namespaces.Add(item);
			return nextNamespaceIndex;
		}

		internal void WriteData(MyBinaryWriter bw)
		{
			DataOffset = (int)bw.BaseStream.Position;
			bw.WriteLeb128(source.Index);
			int value = ((include_files != null) ? include_files.Count : 0);
			bw.WriteLeb128(value);
			if (include_files != null)
			{
				foreach (SourceFileEntry include_file in include_files)
				{
					bw.WriteLeb128(include_file.Index);
				}
			}
			bw.WriteLeb128(namespaces.Count);
			foreach (NamespaceEntry @namespace in namespaces)
			{
				@namespace.Write(file, bw);
			}
		}

		internal void Write(BinaryWriter bw)
		{
			bw.Write(Index);
			bw.Write(DataOffset);
		}

		internal CompileUnitEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			this.file = file;
			Index = reader.ReadInt32();
			DataOffset = reader.ReadInt32();
		}

		public void ReadAll()
		{
			ReadData();
		}

		private void ReadData()
		{
			if (creating)
			{
				throw new InvalidOperationException();
			}
			lock (file)
			{
				if (namespaces != null)
				{
					return;
				}
				MyBinaryReader binaryReader = file.BinaryReader;
				int num = (int)binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = DataOffset;
				int index = binaryReader.ReadLeb128();
				source = file.GetSourceFile(index);
				int num2 = binaryReader.ReadLeb128();
				if (num2 > 0)
				{
					include_files = new List<SourceFileEntry>();
					for (int i = 0; i < num2; i++)
					{
						include_files.Add(file.GetSourceFile(binaryReader.ReadLeb128()));
					}
				}
				int num3 = binaryReader.ReadLeb128();
				namespaces = new List<NamespaceEntry>();
				for (int j = 0; j < num3; j++)
				{
					namespaces.Add(new NamespaceEntry(file, binaryReader));
				}
				binaryReader.BaseStream.Position = num;
			}
		}
	}
	public class SourceFileEntry
	{
		public readonly int Index;

		private int DataOffset;

		private MonoSymbolFile file;

		private string file_name;

		private byte[] guid;

		private byte[] hash;

		private bool creating;

		private bool auto_generated;

		private readonly string sourceFile;

		public static int Size => 8;

		public byte[] Checksum => hash;

		public string FileName
		{
			get
			{
				return file_name;
			}
			set
			{
				file_name = value;
			}
		}

		public bool AutoGenerated => auto_generated;

		public SourceFileEntry(MonoSymbolFile file, string file_name)
		{
			this.file = file;
			this.file_name = file_name;
			Index = file.AddSource(this);
			creating = true;
		}

		public SourceFileEntry(MonoSymbolFile file, string sourceFile, byte[] guid, byte[] checksum)
			: this(file, sourceFile, sourceFile, guid, checksum)
		{
		}

		public SourceFileEntry(MonoSymbolFile file, string fileName, string sourceFile, byte[] guid, byte[] checksum)
			: this(file, fileName)
		{
			this.guid = guid;
			hash = checksum;
			this.sourceFile = sourceFile;
		}

		internal void WriteData(MyBinaryWriter bw)
		{
			DataOffset = (int)bw.BaseStream.Position;
			bw.Write(file_name);
			if (guid == null)
			{
				guid = new byte[16];
			}
			if (hash == null)
			{
				try
				{
					using FileStream inputStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
					MD5 mD = MD5.Create();
					hash = mD.ComputeHash(inputStream);
				}
				catch
				{
					hash = new byte[16];
				}
			}
			bw.Write(guid);
			bw.Write(hash);
			bw.Write((byte)(auto_generated ? 1u : 0u));
		}

		internal void Write(BinaryWriter bw)
		{
			bw.Write(Index);
			bw.Write(DataOffset);
		}

		internal SourceFileEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			this.file = file;
			Index = reader.ReadInt32();
			DataOffset = reader.ReadInt32();
			int num = (int)reader.BaseStream.Position;
			reader.BaseStream.Position = DataOffset;
			sourceFile = (file_name = reader.ReadString());
			guid = reader.ReadBytes(16);
			hash = reader.ReadBytes(16);
			auto_generated = reader.ReadByte() == 1;
			reader.BaseStream.Position = num;
		}

		public void SetAutoGenerated()
		{
			if (!creating)
			{
				throw new InvalidOperationException();
			}
			auto_generated = true;
			file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource;
		}

		public bool CheckChecksum()
		{
			try
			{
				using FileStream inputStream = new FileStream(sourceFile, FileMode.Open);
				byte[] array = MD5.Create().ComputeHash(inputStream);
				for (int i = 0; i < 16; i++)
				{
					if (array[i] != hash[i])
					{
						return false;
					}
				}
				return true;
			}
			catch
			{
				return false;
			}
		}

		public override string ToString()
		{
			return $"SourceFileEntry ({Index}:{DataOffset})";
		}
	}
	public class LineNumberTable
	{
		protected LineNumberEntry[] _line_numbers;

		public readonly int LineBase;

		public readonly int LineRange;

		public readonly byte OpcodeBase;

		public readonly int MaxAddressIncrement;

		public const int Default_LineBase = -1;

		public const int Default_LineRange = 8;

		public const byte Default_OpcodeBase = 9;

		public const byte DW_LNS_copy = 1;

		public const byte DW_LNS_advance_pc = 2;

		public const byte DW_LNS_advance_line = 3;

		public const byte DW_LNS_set_file = 4;

		public const byte DW_LNS_const_add_pc = 8;

		public const byte DW_LNE_end_sequence = 1;

		public const byte DW_LNE_MONO_negate_is_hidden = 64;

		internal const byte DW_LNE_MONO__extensions_start = 64;

		internal const byte DW_LNE_MONO__extensions_end = 127;

		public LineNumberEntry[] LineNumbers => _line_numbers;

		protected LineNumberTable(MonoSymbolFile file)
		{
			LineBase = file.OffsetTable.LineNumberTable_LineBase;
			LineRange = file.OffsetTable.LineNumberTable_LineRange;
			OpcodeBase = (byte)file.OffsetTable.LineNumberTable_OpcodeBase;
			MaxAddressIncrement = (255 - OpcodeBase) / LineRange;
		}

		internal LineNumberTable(MonoSymbolFile file, LineNumberEntry[] lines)
			: this(file)
		{
			_line_numbers = lines;
		}

		internal void Write(MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo)
		{
			int num = (int)bw.BaseStream.Position;
			bool flag = false;
			int num2 = 1;
			int num3 = 0;
			int num4 = 1;
			for (int i = 0; i < LineNumbers.Length; i++)
			{
				int num5 = LineNumbers[i].Row - num2;
				int num6 = LineNumbers[i].Offset - num3;
				if (LineNumbers[i].File != num4)
				{
					bw.Write((byte)4);
					bw.WriteLeb128(LineNumbers[i].File);
					num4 = LineNumbers[i].File;
				}
				if (LineNumbers[i].IsHidden != flag)
				{
					bw.Write((byte)0);
					bw.Write((byte)1);
					bw.Write((byte)64);
					flag = LineNumbers[i].IsHidden;
				}
				if (num6 >= MaxAddressIncrement)
				{
					if (num6 < 2 * MaxAddressIncrement)
					{
						bw.Write((byte)8);
						num6 -= MaxAddressIncrement;
					}
					else
					{
						bw.Write((byte)2);
						bw.WriteLeb128(num6);
						num6 = 0;
					}
				}
				if (num5 < LineBase || num5 >= LineBase + LineRange)
				{
					bw.Write((byte)3);
					bw.WriteLeb128(num5);
					if (num6 != 0)
					{
						bw.Write((byte)2);
						bw.WriteLeb128(num6);
					}
					bw.Write((byte)1);
				}
				else
				{
					byte value = (byte)(num5 - LineBase + LineRange * num6 + OpcodeBase);
					bw.Write(value);
				}
				num2 = LineNumbers[i].Row;
				num3 = LineNumbers[i].Offset;
			}
			bw.Write((byte)0);
			bw.Write((byte)1);
			bw.Write((byte)1);
			if (hasColumnsInfo)
			{
				for (int j = 0; j < LineNumbers.Length; j++)
				{
					LineNumberEntry lineNumberEntry = LineNumbers[j];
					if (lineNumberEntry.Row >= 0)
					{
						bw.WriteLeb128(lineNumberEntry.Column);
					}
				}
			}
			if (hasEndInfo)
			{
				for (int k = 0; k < LineNumbers.Length; k++)
				{
					LineNumberEntry lineNumberEntry2 = LineNumbers[k];
					if (lineNumberEntry2.EndRow == -1 || lineNumberEntry2.EndColumn == -1 || lineNumberEntry2.Row > lineNumberEntry2.EndRow)
					{
						bw.WriteLeb128(16777215);
						continue;
					}
					bw.WriteLeb128(lineNumberEntry2.EndRow - lineNumberEntry2.Row);
					bw.WriteLeb128(lineNumberEntry2.EndColumn);
				}
			}
			file.ExtendedLineNumberSize += (int)bw.BaseStream.Position - num;
		}

		internal static LineNumberTable Read(MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo)
		{
			LineNumberTable lineNumberTable = new LineNumberTable(file);
			lineNumberTable.DoRead(file, br, readColumnsInfo, readEndInfo);
			return lineNumberTable;
		}

		private void DoRead(MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds)
		{
			List<LineNumberEntry> list = new List<LineNumberEntry>();
			bool flag = false;
			bool flag2 = false;
			int num = 1;
			int num2 = 0;
			int file2 = 1;
			while (true)
			{
				byte b = br.ReadByte();
				if (b == 0)
				{
					byte b2 = br.ReadByte();
					long position = br.BaseStream.Position + b2;
					b = br.ReadByte();
					switch (b)
					{
					case 1:
					{
						if (flag2)
						{
							list.Add(new LineNumberEntry(file2, num, -1, num2, flag));
						}
						_line_numbers = list.ToArray();
						if (includesColumns)
						{
							for (int i = 0; i < _line_numbers.Length; i++)
							{
								LineNumberEntry lineNumberEntry = _line_numbers[i];
								if (lineNumberEntry.Row >= 0)
								{
									lineNumberEntry.Column = br.ReadLeb128();
								}
							}
						}
						if (!includesEnds)
						{
							return;
						}
						for (int j = 0; j < _line_numbers.Length; j++)
						{
							LineNumberEntry lineNumberEntry2 = _line_numbers[j];
							int num3 = br.ReadLeb128();
							if (num3 == 16777215)
							{
								lineNumberEntry2.EndRow = -1;
								lineNumberEntry2.EndColumn = -1;
							}
							else
							{
								lineNumberEntry2.EndRow = lineNumberEntry2.Row + num3;
								lineNumberEntry2.EndColumn = br.ReadLeb128();
							}
						}
						return;
					}
					case 64:
						flag = !flag;
						flag2 = true;
						break;
					default:
						throw new MonoSymbolFileException("Unknown extended opcode {0:x}", b);
					case 65:
					case 66:
					case 67:
					case 68:
					case 69:
					case 70:
					case 71:
					case 72:
					case 73:
					case 74:
					case 75:
					case 76:
					case 77:
					case 78:
					case 79:
					case 80:
					case 81:
					case 82:
					case 83:
					case 84:
					case 85:
					case 86:
					case 87:
					case 88:
					case 89:
					case 90:
					case 91:
					case 92:
					case 93:
					case 94:
					case 95:
					case 96:
					case 97:
					case 98:
					case 99:
					case 100:
					case 101:
					case 102:
					case 103:
					case 104:
					case 105:
					case 106:
					case 107:
					case 108:
					case 109:
					case 110:
					case 111:
					case 112:
					case 113:
					case 114:
					case 115:
					case 116:
					case 117:
					case 118:
					case 119:
					case 120:
					case 121:
					case 122:
					case 123:
					case 124:
					case 125:
					case 126:
					case 127:
						break;
					}
					br.BaseStream.Position = position;
				}
				else if (b < OpcodeBase)
				{
					switch (b)
					{
					case 1:
						list.Add(new LineNumberEntry(file2, num, -1, num2, flag));
						flag2 = false;
						break;
					case 2:
						num2 += br.ReadLeb128();
						flag2 = true;
						break;
					case 3:
						num += br.ReadLeb128();
						flag2 = true;
						break;
					case 4:
						file2 = br.ReadLeb128();
						flag2 = true;
						break;
					case 8:
						num2 += MaxAddressIncrement;
						flag2 = true;
						break;
					default:
						throw new MonoSymbolFileException("Unknown standard opcode {0:x} in LNT", b);
					}
				}
				else
				{
					b -= OpcodeBase;
					num2 += b / LineRange;
					num += LineBase + b % LineRange;
					list.Add(new LineNumberEntry(file2, num, -1, num2, flag));
					flag2 = false;
				}
			}
		}

		public bool GetMethodBounds(out LineNumberEntry start, out LineNumberEntry end)
		{
			if (_line_numbers.Length > 1)
			{
				start = _line_numbers[0];
				end = _line_numbers[_line_numbers.Length - 1];
				return true;
			}
			start = LineNumberEntry.Null;
			end = LineNumberEntry.Null;
			return false;
		}
	}
	public class MethodEntry : IComparable
	{
		[Flags]
		public enum Flags
		{
			LocalNamesAmbiguous = 1,
			ColumnsInfoIncluded = 2,
			EndInfoIncluded = 4
		}

		public readonly int CompileUnitIndex;

		public readonly int Token;

		public readonly int NamespaceID;

		private int DataOffset;

		private int LocalVariableTableOffset;

		private int LineNumberTableOffset;

		private int CodeBlockTableOffset;

		private int ScopeVariableTableOffset;

		private int RealNameOffset;

		private Flags flags;

		private int index;

		public readonly CompileUnitEntry CompileUnit;

		private LocalVariableEntry[] locals;

		private CodeBlockEntry[] code_blocks;

		private ScopeVariable[] scope_vars;

		private LineNumberTable lnt;

		private string real_name;

		public readonly MonoSymbolFile SymbolFile;

		public const int Size = 12;

		public Flags MethodFlags => flags;

		public int Index
		{
			get
			{
				return index;
			}
			set
			{
				index = value;
			}
		}

		internal MethodEntry(MonoSymbolFile file, MyBinaryReader reader, int index)
		{
			SymbolFile = file;
			this.index = index;
			Token = reader.ReadInt32();
			DataOffset = reader.ReadInt32();
			LineNumberTableOffset = reader.ReadInt32();
			long position = reader.BaseStream.Position;
			reader.BaseStream.Position = DataOffset;
			CompileUnitIndex = reader.ReadLeb128();
			LocalVariableTableOffset = reader.ReadLeb128();
			NamespaceID = reader.ReadLeb128();
			CodeBlockTableOffset = reader.ReadLeb128();
			ScopeVariableTableOffset = reader.ReadLeb128();
			RealNameOffset = reader.ReadLeb128();
			flags = (Flags)reader.ReadLeb128();
			reader.BaseStream.Position = position;
			CompileUnit = file.GetCompileUnit(CompileUnitIndex);
		}

		internal MethodEntry(MonoSymbolFile file, CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, Flags flags, int namespace_id)
		{
			SymbolFile = file;
			this.real_name = real_name;
			this.locals = locals;
			this.code_blocks = code_blocks;
			this.scope_vars = scope_vars;
			this.flags = flags;
			index = -1;
			Token = token;
			CompileUnitIndex = comp_unit.Index;
			CompileUnit = comp_unit;
			NamespaceID = namespace_id;
			CheckLineNumberTable(lines);
			lnt = new LineNumberTable(file, lines);
			file.NumLineNumbers += lines.Length;
			int num = ((locals != null) ? locals.Length : 0);
			if (num <= 32)
			{
				for (int i = 0; i < num; i++)
				{
					string name = locals[i].Name;
					for (int j = i + 1; j < num; j++)
					{
						if (locals[j].Name == name)
						{
							flags |= Flags.LocalNamesAmbiguous;
							return;
						}
					}
				}
				return;
			}
			Dictionary<string, LocalVariableEntry> dictionary = new Dictionary<string, LocalVariableEntry>();
			for (int k = 0; k < locals.Length; k++)
			{
				LocalVariableEntry value = locals[k];
				if (dictionary.ContainsKey(value.Name))
				{
					flags |= Flags.LocalNamesAmbiguous;
					break;
				}
				dictionary.Add(value.Name, value);
			}
		}

		private static void CheckLineNumberTable(LineNumberEntry[] line_numbers)
		{
			int num = -1;
			int num2 = -1;
			if (line_numbers == null)
			{
				return;
			}
			foreach (LineNumberEntry lineNumberEntry in line_numbers)
			{
				if (lineNumberEntry.Equals(LineNumberEntry.Null))
				{
					throw new MonoSymbolFileException();
				}
				if (lineNumberEntry.Offset < num)
				{
					throw new MonoSymbolFileException();
				}
				if (lineNumberEntry.Offset > num)
				{
					num2 = lineNumberEntry.Row;
					num = lineNumberEntry.Offset;
				}
				else if (lineNumberEntry.Row > num2)
				{
					num2 = lineNumberEntry.Row;
				}
			}
		}

		internal void Write(MyBinaryWriter bw)
		{
			if (index <= 0 || DataOffset == 0)
			{
				throw new InvalidOperationException();
			}
			bw.Write(Token);
			bw.Write(DataOffset);
			bw.Write(LineNumberTableOffset);
		}

		internal void WriteData(MonoSymbolFile file, MyBinaryWriter bw)
		{
			if (index <= 0)
			{
				throw new InvalidOperationException();
			}
			LocalVariableTableOffset = (int)bw.BaseStream.Position;
			int num = ((locals != null) ? locals.Length : 0);
			bw.WriteLeb128(num);
			for (int i = 0; i < num; i++)
			{
				locals[i].Write(file, bw);
			}
			file.LocalCount += num;
			CodeBlockTableOffset = (int)bw.BaseStream.Position;
			int num2 = ((code_blocks != null) ? code_blocks.Length : 0);
			bw.WriteLeb128(num2);
			for (int j = 0; j < num2; j++)
			{
				code_blocks[j].Write(bw);
			}
			ScopeVariableTableOffset = (int)bw.BaseStream.Position;
			int num3 = ((scope_vars != null) ? scope_vars.Length : 0);
			bw.WriteLeb128(num3);
			for (int k = 0; k < num3; k++)
			{
				scope_vars[k].Write(bw);
			}
			if (real_name != null)
			{
				RealNameOffset = (int)bw.BaseStream.Position;
				bw.Write(real_name);
			}
			LineNumberEntry[] lineNumbers = lnt.LineNumbers;
			foreach (LineNumberEntry lineNumberEntry in lineNumbers)
			{
				if (lineNumberEntry.EndRow != -1 || lineNumberEntry.EndColumn != -1)
				{
					flags |= Flags.EndInfoIncluded;
				}
			}
			LineNumberTableOffset = (int)bw.BaseStream.Position;
			lnt.Write(file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
			DataOffset = (int)bw.BaseStream.Position;
			bw.WriteLeb128(CompileUnitIndex);
			bw.WriteLeb128(LocalVariableTableOffset);
			bw.WriteLeb128(NamespaceID);
			bw.WriteLeb128(CodeBlockTableOffset);
			bw.WriteLeb128(ScopeVariableTableOffset);
			bw.WriteLeb128(RealNameOffset);
			bw.WriteLeb128((int)flags);
		}

		public void ReadAll()
		{
			GetLineNumberTable();
			GetLocals();
			GetCodeBlocks();
			GetScopeVariables();
			GetRealName();
		}

		public LineNumberTable GetLineNumberTable()
		{
			lock (SymbolFile)
			{
				if (lnt != null)
				{
					return lnt;
				}
				if (LineNumberTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = LineNumberTableOffset;
				lnt = LineNumberTable.Read(SymbolFile, binaryReader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
				binaryReader.BaseStream.Position = position;
				return lnt;
			}
		}

		public LocalVariableEntry[] GetLocals()
		{
			lock (SymbolFile)
			{
				if (locals != null)
				{
					return locals;
				}
				if (LocalVariableTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = LocalVariableTableOffset;
				int num = binaryReader.ReadLeb128();
				locals = new LocalVariableEntry[num];
				for (int i = 0; i < num; i++)
				{
					locals[i] = new LocalVariableEntry(SymbolFile, binaryReader);
				}
				binaryReader.BaseStream.Position = position;
				return locals;
			}
		}

		public CodeBlockEntry[] GetCodeBlocks()
		{
			lock (SymbolFile)
			{
				if (code_blocks != null)
				{
					return code_blocks;
				}
				if (CodeBlockTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = CodeBlockTableOffset;
				int num = binaryReader.ReadLeb128();
				code_blocks = new CodeBlockEntry[num];
				for (int i = 0; i < num; i++)
				{
					code_blocks[i] = new CodeBlockEntry(i, binaryReader);
				}
				binaryReader.BaseStream.Position = position;
				return code_blocks;
			}
		}

		public ScopeVariable[] GetScopeVariables()
		{
			lock (SymbolFile)
			{
				if (scope_vars != null)
				{
					return scope_vars;
				}
				if (ScopeVariableTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = ScopeVariableTableOffset;
				int num = binaryReader.ReadLeb128();
				scope_vars = new ScopeVariable[num];
				for (int i = 0; i < num; i++)
				{
					scope_vars[i] = new ScopeVariable(binaryReader);
				}
				binaryReader.BaseStream.Position = position;
				return scope_vars;
			}
		}

		public string GetRealName()
		{
			lock (SymbolFile)
			{
				if (real_name != null)
				{
					return real_name;
				}
				if (RealNameOffset == 0)
				{
					return null;
				}
				real_name = SymbolFile.BinaryReader.ReadString(RealNameOffset);
				return real_name;
			}
		}

		public int CompareTo(object obj)
		{
			MethodEntry methodEntry = (MethodEntry)obj;
			if (methodEntry.Token < Token)
			{
				return 1;
			}
			if (methodEntry.Token > Token)
			{
				return -1;
			}
			return 0;
		}

		public override string ToString()
		{
			return $"[Method {index}:{Token:x}:{CompileUnitIndex}:{CompileUnit}]";
		}
	}
	public struct NamespaceEntry
	{
		public readonly string Name;

		public readonly int Index;

		public readonly int Parent;

		public readonly string[] UsingClauses;

		public NamespaceEntry(string name, int index, string[] using_clauses, int parent)
		{
			Name = name;
			Index = index;
			Parent = parent;
			UsingClauses = ((using_clauses != null) ? using_clauses : new string[0]);
		}

		internal NamespaceEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			Name = reader.ReadString();
			Index = reader.ReadLeb128();
			Parent = reader.ReadLeb128();
			int num = reader.ReadLeb128();
			UsingClauses = new string[num];
			for (int i = 0; i < num; i++)
			{
				UsingClauses[i] = reader.ReadString();
			}
		}

		internal void Write(MonoSymbolFile file, MyBinaryWriter bw)
		{
			bw.Write(Name);
			bw.WriteLeb128(Index);
			bw.WriteLeb128(Parent);
			bw.WriteLeb128(UsingClauses.Length);
			string[] usingClauses = UsingClauses;
			foreach (string value in usingClauses)
			{
				bw.Write(value);
			}
		}

		public override string ToString()
		{
			return $"[Namespace {Name}:{Index}:{Parent}]";
		}
	}
	public class MonoSymbolWriter
	{
		private List<SourceMethodBuilder> methods;

		private List<SourceFileEntry> sources;

		private List<CompileUnitEntry> comp_units;

		protected readonly MonoSymbolFile file;

		private string filename;

		private SourceMethodBuilder current_method;

		private Stack<SourceMethodBuilder> current_method_stack = new Stack<SourceMethodBuilder>();

		public MonoSymbolFile SymbolFile => file;

		public MonoSymbolWriter(string filename)
		{
			methods = new List<SourceMethodBuilder>();
			sources = new List<SourceFileEntry>();
			comp_units = new List<CompileUnitEntry>();
			file = new MonoSymbolFile();
			this.filename = filename + ".mdb";
		}

		public void CloseNamespace()
		{
		}

		public void DefineLocalVariable(int index, string name)
		{
			if (current_method != null)
			{
				current_method.AddLocal(index, name);
			}
		}

		public void DefineCapturedLocal(int scope_id, string name, string captured_name)
		{
			file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Local);
		}

		public void DefineCapturedParameter(int scope_id, string name, string captured_name)
		{
			file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Parameter);
		}

		public void DefineCapturedThis(int scope_id, string captured_name)
		{
			file.DefineCapturedVariable(scope_id, "this", captured_name, CapturedVariable.CapturedKind.This);
		}

		public void DefineCapturedScope(int scope_id, int id, string captured_name)
		{
			file.DefineCapturedScope(scope_id, id, captured_name);
		}

		public void DefineScopeVariable(int scope, int index)
		{
			if (current_method != null)
			{
				current_method.AddScopeVariable(scope, index);
			}
		}

		public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden)
		{
			if (current_method != null)
			{
				current_method.MarkSequencePoint(offset, file, line, column, is_hidden);
			}
		}

		public SourceMethodBuilder OpenMethod(ICompileUnit file, int ns_id, IMethodDef method)
		{
			SourceMethodBuilder result = new SourceMethodBuilder(file, ns_id, method);
			current_method_stack.Push(current_method);
			current_method = result;
			methods.Add(current_method);
			return result;
		}

		public void CloseMethod()
		{
			current_method = current_method_stack.Pop();
		}

		public SourceFileEntry DefineDocument(string url)
		{
			SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url);
			sources.Add(sourceFileEntry);
			return sourceFileEntry;
		}

		public SourceFileEntry DefineDocument(string url, byte[] guid, byte[] checksum)
		{
			SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url, guid, checksum);
			sources.Add(sourceFileEntry);
			return sourceFileEntry;
		}

		public CompileUnitEntry DefineCompilationUnit(SourceFileEntry source)
		{
			CompileUnitEntry compileUnitEntry = new CompileUnitEntry(file, source);
			comp_units.Add(compileUnitEntry);
			return compileUnitEntry;
		}

		public int DefineNamespace(string name, CompileUnitEntry unit, string[] using_clauses, int parent)
		{
			if (unit == null || using_clauses == null)
			{
				throw new NullReferenceException();
			}
			return unit.DefineNamespace(name, using_clauses, parent);
		}

		public int OpenScope(int start_offset)
		{
			if (current_method == null)
			{
				return 0;
			}
			current_method.StartBlock(CodeBlockEntry.Type.Lexical, start_offset);
			return 0;
		}

		public void CloseScope(int end_offset)
		{
			if (current_method != null)
			{
				current_method.EndBlock(end_offset);
			}
		}

		public void OpenCompilerGeneratedBlock(int start_offset)
		{
			if (current_method != null)
			{
				current_method.StartBlock(CodeBlockEntry.Type.CompilerGenerated, start_offset);
			}
		}

		public void CloseCompilerGeneratedBlock(int end_offset)
		{
			if (current_method != null)
			{
				current_method.EndBlock(end_offset);
			}
		}

		public void StartIteratorBody(int start_offset)
		{
			current_method.StartBlock(CodeBlockEntry.Type.IteratorBody, start_offset);
		}

		public void EndIteratorBody(int end_offset)
		{
			current_method.EndBlock(end_offset);
		}

		public void StartIteratorDispatcher(int start_offset)
		{
			current_method.StartBlock(CodeBlockEntry.Type.IteratorDispatcher, start_offset);
		}

		public void EndIteratorDispatcher(int end_offset)
		{
			current_method.EndBlock(end_offset);
		}

		public void DefineAnonymousScope(int id)
		{
			file.DefineAnonymousScope(id);
		}

		public void WriteSymbolFile(Guid guid)
		{
			foreach (SourceMethodBuilder method in methods)
			{
				method.DefineMethod(file);
			}
			try
			{
				File.Delete(filename);
			}
			catch
			{
			}
			using FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
			file.CreateSymbolFile(guid, fs);
		}
	}
	public class SourceMethodBuilder
	{
		private List<LocalVariableEntry> _locals;

		private List<CodeBlockEntry> _blocks;

		private List<ScopeVariable> _scope_vars;

		private Stack<CodeBlockEntry> _block_stack;

		private readonly List<LineNumberEntry> method_lines;

		private readonly ICompileUnit _comp_unit;

		private readonly int ns_id;

		private readonly IMethodDef method;

		public CodeBlockEntry[] Blocks
		{
			get
			{
				if (_blocks == null)
				{
					return new CodeBlockEntry[0];
				}
				CodeBlockEntry[] array = new CodeBlockEntry[_blocks.Count];
				_blocks.CopyTo(array, 0);
				return array;
			}
		}

		public CodeBlockEntry CurrentBlock
		{
			get
			{
				if (_block_stack != null && _block_stack.Count > 0)
				{
					return _block_stack.Peek();
				}
				return null;
			}
		}

		public LocalVariableEntry[] Locals
		{
			get
			{
				if (_locals == null)
				{
					return new LocalVariableEntry[0];
				}
				return _locals.ToArray();
			}
		}

		public ICompileUnit SourceFile => _comp_unit;

		public ScopeVariable[] ScopeVariables
		{
			get
			{
				if (_scope_vars == null)
				{
					return new ScopeVariable[0];
				}
				return _scope_vars.ToArray();
			}
		}

		public SourceMethodBuilder(ICompileUnit comp_unit)
		{
			_comp_unit = comp_unit;
			method_lines = new List<LineNumberEntry>();
		}

		public SourceMethodBuilder(ICompileUnit comp_unit, int ns_id, IMethodDef method)
			: this(comp_unit)
		{
			this.ns_id = ns_id;
			this.method = method;
		}

		public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden)
		{
			MarkSequencePoint(offset, file, line, column, -1, -1, is_hidden);
		}

		public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden)
		{
			LineNumberEntry lineNumberEntry = new LineNumberEntry(file?.Index ?? 0, line, column, end_line, end_column, offset, is_hidden);
			if (method_lines.Count > 0)
			{
				LineNumberEntry lineNumberEntry2 = method_lines[method_lines.Count - 1];
				if (lineNumberEntry2.Offset == offset)
				{
					if (LineNumberEntry.LocationComparer.Default.Compare(lineNumberEntry, lineNumberEntry2) > 0)
					{
						method_lines[method_lines.Count - 1] = lineNumberEntry;
					}
					return;
				}
			}
			method_lines.Add(lineNumberEntry);
		}

		public void StartBlock(CodeBlockEntry.Type type, int start_offset)
		{
			StartBlock(type, start_offset, (_blocks == null) ? 1 : (_blocks.Count + 1));
		}

		public void StartBlock(CodeBlockEntry.Type type, int start_offset, int scopeIndex)
		{
			if (_block_stack == null)
			{
				_block_stack = new Stack<CodeBlockEntry>();
			}
			if (_blocks == null)
			{
				_blocks = new List<CodeBlockEntry>();
			}
			int parent = ((CurrentBlock != null) ? CurrentBlock.Index : (-1));
			CodeBlockEntry item = new CodeBlockEntry(scopeIndex, parent, type, start_offset);
			_block_stack.Push(item);
			_blocks.Add(item);
		}

		public void EndBlock(int end_offset)
		{
			_block_stack.Pop().Close(end_offset);
		}

		public void AddLocal(int index, string name)
		{
			if (_locals == null)
			{
				_locals = new List<LocalVariableEntry>();
			}
			int block = ((CurrentBlock != null) ? CurrentBlock.Index : 0);
			_locals.Add(new LocalVariableEntry(index, name, block));
		}

		public void AddScopeVariable(int scope, int index)
		{
			if (_scope_vars == null)
			{
				_scope_vars = new List<ScopeVariable>();
			}
			_scope_vars.Add(new ScopeVariable(scope, index));
		}

		public void DefineMethod(MonoSymbolFile file)
		{
			DefineMethod(file, method.Token);
		}

		public void DefineMethod(MonoSymbolFile file, int token)
		{
			CodeBlockEntry[] array = Blocks;
			if (array.Length != 0)
			{
				List<CodeBlockEntry> list = new List<CodeBlockEntry>(array.Length);
				int num = 0;
				for (int i = 0; i < array.Length; i++)
				{
					num = Math.Max(num, array[i].Index);
				}
				for (int j = 0; j < num; j++)
				{
					int num2 = j + 1;
					if (j < array.Length && array[j].Index == num2)
					{
						list.Add(array[j]);
						continue;
					}
					bool flag = false;
					for (int k = 0; k < array.Length; k++)
					{
						if (array[k].Index == num2)
						{
							list.Add(array[k]);
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						list.Add(new CodeBlockEntry(num2, -1, CodeBlockEntry.Type.CompilerGenerated, 0));
					}
				}
				array = list.ToArray();
			}
			MethodEntry entry = new MethodEntry(file, _comp_unit.Entry, token, ScopeVariables, Locals, method_lines.ToArray(), array, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id);
			file.AddMethod(entry);
		}
	}
	public class SymbolWriterImpl : ISymbolWriter
	{
		private MonoSymbolWriter msw;

		private int nextLocalIndex;

		private int currentToken;

		private string methodName;

		private Stack namespaceStack = new Stack();

		private bool methodOpened;

		private Hashtable documents = new Hashtable();

		private Guid guid;

		public SymbolWriterImpl(Guid guid)
		{
			this.guid = guid;
		}

		public void Close()
		{
			msw.WriteSymbolFile(guid);
		}

		public void CloseMethod()
		{
			if (methodOpened)
			{
				methodOpened = false;
				nextLocalIndex = 0;
				msw.CloseMethod();
			}
		}

		public void CloseNamespace()
		{
			namespaceStack.Pop();
			msw.CloseNamespace();
		}

		public void CloseScope(int endOffset)
		{
			msw.CloseScope(endOffset);
		}

		public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType)
		{
			SymbolDocumentWriterImpl symbolDocumentWriterImpl = (SymbolDocumentWriterImpl)documents[url];
			if (symbolDocumentWriterImpl == null)
			{
				SourceFileEntry source = msw.DefineDocument(url);
				symbolDocumentWriterImpl = new SymbolDocumentWriterImpl(msw.DefineCompilationUnit(source));
				documents[url] = symbolDocumentWriterImpl;
			}
			return symbolDocumentWriterImpl;
		}

		public void DefineField(SymbolToken parent, string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3)
		{
		}

		public void DefineGlobalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3)
		{
		}

		public void DefineLocalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset)
		{
			msw.DefineLocalVariable(nextLocalIndex++, name);
		}

		public void DefineParameter(string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3)
		{
		}

		public void DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns)
		{
			SourceFileEntry file = ((SymbolDocumentWriterImpl)document)?.Entry.SourceFile;
			for (int i = 0; i < offsets.Length; i++)
			{
				if (i <= 0 || offsets[i] != offsets[i - 1] || lines[i] != lines[i - 1] || columns[i] != columns[i - 1])
				{
					msw.MarkSequencePoint(offsets[i], file, lines[i], columns[i], is_hidden: false);
				}
			}
		}

		public void Initialize(IntPtr emitter, string filename, bool fFullBuild)
		{
			msw = new MonoSymbolWriter(filename);
		}

		public void OpenMethod(SymbolToken method)
		{
			currentToken = method.GetToken();
		}

		public void OpenNamespace(string name)
		{
			NamespaceInfo namespaceInfo = new NamespaceInfo();
			namespaceInfo.NamespaceID = -1;
			namespaceInfo.Name = name;
			namespaceStack.Push(namespaceInfo);
		}

		public int OpenScope(int startOffset)
		{
			return msw.OpenScope(startOffset);
		}

		public void SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn)
		{
			int currentNamespace = GetCurrentNamespace(startDoc);
			SourceMethodImpl method = new SourceMethodImpl(methodName, currentToken, currentNamespace);
			msw.OpenMethod(((ICompileUnit)startDoc).Entry, currentNamespace, method);
			methodOpened = true;
		}

		public void SetScopeRange(int scopeID, int startOffset, int endOffset)
		{
		}

		public void SetSymAttribute(SymbolToken parent, string name, byte[] data)
		{
			if (name == "__name")
			{
				methodName = Encoding.UTF8.GetString(data);
			}
		}

		public void SetUnderlyingWriter(IntPtr underlyingWriter)
		{
		}

		public void SetUserEntryPoint(SymbolToken entryMethod)
		{
		}

		public void UsingNamespace(string fullName)
		{
			if (namespaceStack.Count == 0)
			{
				OpenNamespace("");
			}
			NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek();
			if (namespaceInfo.NamespaceID != -1)
			{
				NamespaceInfo namespaceInfo2 = namespaceInfo;
				CloseNamespace();
				OpenNamespace(namespaceInfo2.Name);
				namespaceInfo = (NamespaceInfo)namespaceStack.Peek();
				namespaceInfo.UsingClauses = namespaceInfo2.UsingClauses;
			}
			namespaceInfo.UsingClauses.Add(fullName);
		}

		private int GetCurrentNamespace(ISymbolDocumentWriter doc)
		{
			if (namespaceStack.Count == 0)
			{
				OpenNamespace("");
			}
			NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek();
			if (namespaceInfo.NamespaceID == -1)
			{
				string[] using_clauses = (string[])namespaceInfo.UsingClauses.ToArray(typeof(string));
				int parent = 0;
				if (namespaceStack.Count > 1)
				{
					namespaceStack.Pop();
					parent = ((NamespaceInfo)namespaceStack.Peek()).NamespaceID;
					namespaceStack.Push(namespaceInfo);
				}
				namespaceInfo.NamespaceID = msw.DefineNamespace(namespaceInfo.Name, ((ICompileUnit)doc).Entry, using_clauses, parent);
			}
			return namespaceInfo.NamespaceID;
		}
	}
	internal class SymbolDocumentWriterImpl : ISymbolDocumentWriter, ISourceFile, ICompileUnit
	{
		private CompileUnitEntry comp_unit;

		SourceFileEntry ISourceFile.Entry => comp_unit.SourceFile;

		public CompileUnitEntry Entry => comp_unit;

		public SymbolDocumentWriterImpl(CompileUnitEntry comp_unit)
		{
			this.comp_unit = comp_unit;
		}

		public void SetCheckSum(Guid algorithmId, byte[] checkSum)
		{
		}

		public void SetSource(byte[] source)
		{
		}
	}
	internal class SourceMethodImpl : IMethodDef
	{
		private string name;

		private int token;

		private int namespaceID;

		public string Name => name;

		public int NamespaceID => namespaceID;

		public int Token => token;

		public SourceMethodImpl(string name, int token, int namespaceID)
		{
			this.name = name;
			this.token = token;
			this.namespaceID = namespaceID;
		}
	}
	internal class NamespaceInfo
	{
		public string Name;

		public int NamespaceID;

		public ArrayList UsingClauses = new ArrayList();
	}
}
namespace Mono.Cecil.Mdb
{
	public sealed class MdbReaderProvider : ISymbolReaderProvider
	{
		public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
		{
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(Mixin.GetMdbFileName(fileName)));
		}

		public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
		{
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(symbolStream));
		}
	}
	public sealed class MdbReader : ISymbolReader, IDisposable
	{
		private readonly ModuleDefinition module;

		private readonly MonoSymbolFile symbol_file;

		private readonly Dictionary<string, Document> documents;

		public MdbReader(ModuleDefinition module, MonoSymbolFile symFile)
		{
			this.module = module;
			symbol_file = symFile;
			documents = new Dictionary<string, Document>();
		}

		public ISymbolWriterProvider GetWriterProvider()
		{
			return (ISymbolWriterProvider)(object)new MdbWriterProvider();
		}

		public bool ProcessDebugHeader(ImageDebugHeader header)
		{
			return symbol_file.Guid == module.Mvid;
		}

		public MethodDebugInformation Read(MethodDefinition method)
		{
			//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_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			MetadataToken metadataToken = ((MemberReference)method).MetadataToken;
			MethodEntry methodByToken = symbol_file.GetMethodByToken(((MetadataToken)(ref metadataToken)).ToInt32());
			if (methodByToken == null)
			{
				return null;
			}
			MethodDebugInformation val = new MethodDebugInformation(method);
			val.code_size = ReadCodeSize(method);
			ScopeDebugInformation[] scopes = ReadScopes(methodByToken, val);
			ReadLineNumbers(methodByToken, val);
			ReadLocalVariables(methodByToken, scopes);
			return val;
		}

		private static int ReadCodeSize(MethodDefinition method)
		{
			return ((MemberReference)method).Module.Read<MethodDefinition, int>(method, (Func<MethodDefinition, MetadataReader, int>)((MethodDefinition m, MetadataReader reader) => reader.ReadCodeSize(m)));
		}

		private static void ReadLocalVariables(MethodEntry entry, ScopeDebugInformation[] scopes)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			LocalVariableEntry[] locals = entry.GetLocals();
			for (int i = 0; i < locals.Length; i++)
			{
				LocalVariableEntry localVariableEntry = locals[i];
				VariableDebugInformation val = new VariableDebugInformation(localVariableEntry.Index, localVariableEntry.Name);
				int blockIndex = localVariableEntry.BlockIndex;
				if (blockIndex >= 0 && blockIndex < scopes.Length)
				{
					ScopeDebugInformation val2 = scopes[blockIndex];
					if (val2 != null)
					{
						val2.Variables.Add(val);
					}
				}
			}
		}

		private void ReadLineNumbers(MethodEntry entry, MethodDebugInformation info)
		{
			LineNumberTable lineNumberTable = entry.GetLineNumberTable();
			info.sequence_points = new Collection<SequencePoint>(lineNumberTable.LineNumbers.Length);
			for (int i = 0; i < lineNumberTable.LineNumbers.Length; i++)
			{
				LineNumberEntry lineNumberEntry = lineNumberTable.LineNumbers[i];
				if (i <= 0 || lineNumberTable.LineNumbers[i - 1].Offset != lineNumberEntry.Offset)
				{
					info.sequence_points.Add(LineToSequencePoint(lineNumberEntry));
				}
			}
		}

		private Document GetDocument(SourceFileEntry file)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			string fileName = file.FileName;
			if (documents.TryGetValue(fileName, out var value))
			{
				return value;
			}
			value = new Document(fileName)
			{
				Hash = file.Checksum
			};
			documents.Add(fileName, value);
			return value;
		}

		private static ScopeDebugInformation[] ReadScopes(MethodEntry entry, MethodDebugInformation info)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0039: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_006d: 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)
			CodeBlockEntry[] codeBlocks = entry.GetCodeBlocks();
			ScopeDebugInformation[] array = (ScopeDebugInformation[])(object)new ScopeDebugInformation[codeBlocks.Length + 1];
			ScopeDebugInformation val = new ScopeDebugInformation
			{
				Start = new InstructionOffset(0),
				End = new InstructionOffset(info.code_size)
			};
			ScopeDebugInformation scope = val;
			array[0] = val;
			info.scope = scope;
			CodeBlockEntry[] array2 = codeBlocks;
			foreach (CodeBlockEntry codeBlockEntry in array2)
			{
				if (codeBlockEntry.BlockType == CodeBlockEntry.Type.Lexical || codeBlockEntry.BlockType == CodeBlockEntry.Type.CompilerGenerated)
				{
					ScopeDebugInformation val2 = new ScopeDebugInformation();
					val2.Start = new InstructionOffset(codeBlockEntry.StartOffset);
					val2.End = new InstructionOffset(codeBlockEntry.EndOffset);
					array[codeBlockEntry.Index + 1] = val2;
					if (!AddScope(info.scope.Scopes, val2))
					{
						info.scope.Scopes.Add(val2);
					}
				}
			}
			return array;
		}

		private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope)
		{
			//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_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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)
			Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ScopeDebugInformation current = enumerator.Current;
					if (current.HasScopes && AddScope(current.Scopes, scope))
					{
						return true;
					}
					InstructionOffset val = scope.Start;
					int offset = ((InstructionOffset)(ref val)).Offset;
					val = current.Start;
					if (offset >= ((InstructionOffset)(ref val)).Offset)
					{
						val = scope.End;
						int offset2 = ((InstructionOffset)(ref val)).Offset;
						val = current.End;
						if (offset2 <= ((InstructionOffset)(ref val)).Offset)
						{
							current.Scopes.Add(scope);
							return true;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return false;
		}

		private SequencePoint LineToSequencePoint(LineNumberEntry line)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			SourceFileEntry sourceFile = symbol_file.GetSourceFile(line.File);
			return new SequencePoint(line.Offset, GetDocument(sourceFile))
			{
				StartLine = line.Row,
				EndLine = line.EndRow,
				StartColumn = line.Column,
				EndColumn = line.EndColumn
			};
		}

		public void Dispose()
		{
			symbol_file.Dispose();
		}
	}
	internal static class MethodEntryExtensions
	{
		public static bool HasColumnInfo(this MethodEntry entry)
		{
			return (entry.MethodFlags & MethodEntry.Flags.ColumnsInfoIncluded) != 0;
		}

		public static bool HasEndInfo(this MethodEntry entry)
		{
			return (entry.MethodFlags & MethodEntry.Flags.EndInfoIncluded) != 0;
		}
	}
	public sealed class MdbWriterProvider : ISymbolWriterProvider
	{
		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName)
		{
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolWriter)(object)new MdbWriter(module.Mvid, fileName);
		}

		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream)
		{
			throw new NotImplementedException();
		}
	}
	public sealed class MdbWriter : ISymbolWriter, IDisposable
	{
		private class SourceFile : ISourceFile
		{
			private readonly CompileUnitEntry compilation_unit;

			private readonly SourceFileEntry entry;

			public SourceFileEntry Entry => entry;

			public CompileUnitEntry CompilationUnit => compilation_unit;

			public SourceFile(CompileUnitEntry comp_unit, SourceFileEntry entry)
			{
				compilation_unit = comp_unit;
				this.entry = entry;
			}
		}

		private class SourceMethod : IMethodDef
		{
			private readonly MethodDefinition method;

			public string Name => ((MemberReference)method).Name;

			public int Token
			{
				get
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_000b: Unknown result type (might be due to invalid IL or missing references)
					MetadataToken metadataToken = ((MemberReference)method).MetadataToken;
					return ((MetadataToken)(ref metadataToken)).ToInt32();
				}
			}

			public SourceMethod(MethodDefinition method)
			{
				this.method = method;
			}
		}

		private readonly Guid mvid;

		private readonly MonoSymbolWriter writer;

		private readonly Dictionary<string, SourceFile> source_files;

		public MdbWriter(Guid mvid, string assembly)
		{
			this.mvid = mvid;
			writer = new MonoSymbolWriter(assembly);
			source_files = new Dictionary<string, SourceFile>();
		}

		public ISymbolReaderProvider GetReaderProvider()
		{
			return (ISymbolReaderProvider)(object)new MdbReaderProvider();
		}

		private SourceFile GetSourceFile(Document document)
		{
			string url = document.Url;
			if (source_files.TryGetValue(url, out var value))
			{
				return value;
			}
			SourceFileEntry sourceFileEntry = writer.DefineDocument(url, null, (document.Hash != null && document.Hash.Length == 16) ? document.Hash : null);
			value = new SourceFile(writer.DefineCompilationUnit(sourceFileEntry), sourceFileEntry);
			source_files.Add(url, value);
			return value;
		}

		private void Populate(Collection<SequencePoint> sequencePoints, int[] offsets, int[] startRows, int[] endRows, int[] startCols, int[] endCols, out SourceFile file)
		{
			SourceFile sourceFile = null;
			for (int i = 0; i < sequencePoints.Count; i++)
			{
				SequencePoint val = sequencePoints[i];
				offsets[i] = val.Offset;
				if (sourceFile == null)
				{
					sourceFile = GetSourceFile(val.Document);
				}
				startRows[i] = val.StartLine;
				endRows[i] = val.EndLine;
				startCols[i] = val.StartColumn;
				endCols[i] = val.EndColumn;
			}
			file = sourceFile;
		}

		public void Write(MethodDebugInformation info)
		{
			SourceMethod method = new SourceMethod(info.method);
			Collection<SequencePoint> sequencePoints = info.SequencePoints;
			int count = sequencePoints.Count;
			if (count != 0)
			{
				int[] array = new int[count];
				int[] array2 = new int[count];
				int[] array3 = new int[count];
				int[] array4 = new int[count];
				int[] array5 = new int[count];
				Populate(sequencePoints, array, array2, array3, array4, array5, out var file);
				SourceMethodBuilder sourceMethodBuilder = writer.OpenMethod(file.CompilationUnit, 0, method);
				for (int i = 0; i < count; i++)
				{
					sourceMethodBuilder.MarkSequencePoint(array[i], file.CompilationUnit.SourceFile, array2[i], array4[i], array3[i], array5[i], is_hidden: false);
				}
				if (info.scope != null)
				{
					WriteRootScope(info.scope, info);
				}
				writer.CloseMethod();
			}
		}

		private void WriteRootScope(ScopeDebugInformation scope, MethodDebugInformation info)
		{
			WriteScopeVariables(scope);
			if (scope.HasScopes)
			{
				WriteScopes(scope.Scopes, info);
			}
		}

		private void WriteScope(ScopeDebugInformation scope, MethodDebugInformation info)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			MonoSymbolWriter monoSymbolWriter = writer;
			InstructionOffset val = scope.Start;
			monoSymbolWriter.OpenScope(((InstructionOffset)(ref val)).Offset);
			WriteScopeVariables(scope);
			if (scope.HasScopes)
			{
				WriteScopes(scope.Scopes, info);
			}
			MonoSymbolWriter monoSymbolWriter2 = writer;
			val = scope.End;
			int end_offset;
			if (!((InstructionOffset)(ref val)).IsEndOfMethod)
			{
				val = scope.End;
				end_offset = ((InstructionOffset)(ref val)).Offset;
			}
			else
			{
				end_offset = info.code_size;
			}
			monoSymbolWriter2.CloseScope(end_offset);
		}

		private void WriteScopes(Collection<ScopeDebugInformation> scopes, MethodDebugInformation info)
		{
			for (int i = 0; i < scopes.Count; i++)
			{
				WriteScope(scopes[i], info);
			}
		}

		private void WriteScopeVariables(ScopeDebugInformation scope)
		{
			//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)
			if (!scope.HasVariables)
			{
				return;
			}
			Enumerator<VariableDebugInformation> enumerator = scope.variables.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					VariableDebugInformation current = enumerator.Current;
					if (!string.IsNullOrEmpty(current.Name))
					{
						writer.DefineLocalVariable(current.Index, current.Name);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public ImageDebugHeader GetDebugHeader()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			return new ImageDebugHeader();
		}

		public void Dispose()
		{
			writer.WriteSymbolFile(mvid);
		}
	}
}

BepInEx/core/Mono.Cecil.Pdb.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using Microsoft.Cci;
using Microsoft.Cci.Pdb;
using Mono.Cecil.Cil;
using Mono.Cecil.PE;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil.Pdb")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyVersion("0.10.4.0")]
namespace Mono.Cecil.Pdb
{
	[ComImport]
	[Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface ISymUnmanagedDocumentWriter
	{
	}
	[ComImport]
	[Guid("0B97726E-9E6D-4f05-9A26-424022093CAA")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface ISymUnmanagedWriter2
	{
		void DefineDocument([In][MarshalAs(UnmanagedType.LPWStr)] string url, [In] ref Guid langauge, [In] ref Guid languageVendor, [In] ref Guid documentType, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedDocumentWriter pRetVal);

		void SetUserEntryPoint([In] int methodToken);

		void OpenMethod([In] int methodToken);

		void CloseMethod();

		void OpenScope([In] int startOffset, out int pRetVal);

		void CloseScope([In] int endOffset);

		void SetScopeRange_Placeholder();

		void DefineLocalVariable_Placeholder();

		void DefineParameter_Placeholder();

		void DefineField_Placeholder();

		void DefineGlobalVariable_Placeholder();

		void Close();

		void SetSymAttribute(uint parent, string name, uint data, IntPtr signature);

		void OpenNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string name);

		void CloseNamespace();

		void UsingNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string fullName);

		void SetMethodSourceRange_Placeholder();

		void Initialize([In][MarshalAs(UnmanagedType.IUnknown)] object emitter, [In][MarshalAs(UnmanagedType.LPWStr)] string filename, [In] IStream pIStream, [In] bool fFullBuild);

		void GetDebugInfo(out ImageDebugDirectory pIDD, [In] int cData, out int pcData, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data);

		void DefineSequencePoints([In][MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document, [In] int spCount, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns);

		void RemapToken_Placeholder();

		void Initialize2_Placeholder();

		void DefineConstant_Placeholder();

		void Abort_Placeholder();

		void DefineLocalVariable2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In] int attributes, [In] int sigToken, [In] int addrKind, [In] int addr1, [In] int addr2, [In] int addr3, [In] int startOffset, [In] int endOffset);

		void DefineGlobalVariable2_Placeholder();

		void DefineConstant2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In][MarshalAs(UnmanagedType.Struct)] object variant, [In] int sigToken);
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")]
	internal interface IMetaDataEmit
	{
		void SetModuleProps(string szName);

		void Save(string szFile, uint dwSaveFlags);

		void SaveToStream(IntPtr pIStream, uint dwSaveFlags);

		uint GetSaveSize(uint fSave);

		uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements);

		uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser);

		void SetHandler([In][MarshalAs(UnmanagedType.IUnknown)] object pUnk);

		uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags);

		void DefineMethodImpl(uint td, uint tkBody, uint tkDecl);

		uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName);

		uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit);

		uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob);

		uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent);

		uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods);

		void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize);

		void DeleteClassLayout(uint td);

		void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType);

		void DeleteFieldMarshal(uint tk);

		uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission);

		void SetRVA(uint md, uint ulRVA);

		uint GetTokenFromSig(IntPtr pvSig, uint cbSig);

		uint DefineModuleRef(string szName);

		void SetParent(uint mr, uint tk);

		uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig);

		void SaveToMemory(IntPtr pbData, uint cbData);

		uint DefineUserString(string szString, uint cchString);

		void DeleteToken(uint tkObj);

		void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags);

		void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements);

		void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods);

		uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission);

		void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);

		void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);

		void DeletePinvokeMap(uint tk);

		uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute);

		void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute);

		uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods);

		uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods);

		void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs);

		void ApplyEditAndContinue([MarshalAs(UnmanagedType.IUnknown)] object pImport);

		uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax);

		void SetMethodImplFlags(uint md, uint dwImplFlags);

		void SetFieldRVA(uint fd, uint ulRVA);

		void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs(UnmanagedType.IUnknown)] object pHandler);

		void MergeEnd();
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44")]
	internal interface IMetaDataImport
	{
		[PreserveSig]
		void CloseEnum(uint hEnum);

		uint CountEnum(uint hEnum);

		void ResetEnum(uint hEnum, uint ulPos);

		uint EnumTypeDefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeDefs, uint cMax);

		uint EnumInterfaceImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rImpls, uint cMax);

		uint EnumTypeRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeRefs, uint cMax);

		uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass);

		Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName);

		uint GetModuleFromScope();

		uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags);

		uint GetInterfaceImplProps(uint iiImpl, out uint pClass);

		uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName);

		uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope);

		uint EnumMembers(ref uint phEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMembers, uint cMax);

		uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMembers, uint cMax);

		uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax);

		uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethods, uint cMax);

		uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax);

		uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rFields, uint cMax);

		uint EnumParams(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rParams, uint cMax);

		uint EnumMemberRefs(ref uint phEnum, uint tkParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMemberRefs, uint cMax);

		uint EnumMethodImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodDecl, uint cMax);

		uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rPermission, uint cMax);

		uint FindMember(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint FindMethod(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint FindField(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint FindMemberRef(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA);

		uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob);

		uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax);

		uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax);

		uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint cMax);

		uint EnumMethodSemantics(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rEventProp, uint cMax);

		uint GetMethodSemantics(uint mb, uint tkEventProp);

		uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset);

		uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType);

		uint GetRVA(uint tk, out uint pulCodeRVA);

		uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission);

		uint GetSigFromToken(uint mdSig, out IntPtr ppvSig);

		uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName);

		uint EnumModuleRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rModuleRefs, uint cmax);

		uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig);

		uint GetNameFromToken(uint tk);

		uint EnumUnresolvedMethods(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rMethods, uint cMax);

		uint GetUserString(uint stk, StringBuilder szString, uint cchString);

		uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName);

		uint EnumSignatures(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rSignatures, uint cmax);

		uint EnumTypeSpecs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeSpecs, uint cmax);

		uint EnumUserStrings(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rStrings, uint cmax);

		[PreserveSig]
		int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam);

		uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rCustomAttributes, uint cMax);

		uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob);

		uint FindTypeRef(uint tkResolutionScope, string szName);

		uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue);

		uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue);

		uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint cMax);

		uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue);

		uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData);

		[PreserveSig]
		[return: MarshalAs(UnmanagedType.Bool)]
		bool IsValidToken(uint tk);

		uint GetNestedClassProps(uint tdNestedClass);

		uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig);

		int IsGlobal(uint pd);
	}
	internal class ModuleMetadata : IMetaDataEmit, IMetaDataImport
	{
		private readonly ModuleDefinition module;

		private Dictionary<uint, TypeDefinition> types;

		private Dictionary<uint, MethodDefinition> methods;

		public ModuleMetadata(ModuleDefinition module)
		{
			this.module = module;
		}

		private bool TryGetType(uint token, out TypeDefinition type)
		{
			if (types == null)
			{
				InitializeMetadata(module);
			}
			return types.TryGetValue(token, out type);
		}

		private bool TryGetMethod(uint token, out MethodDefinition method)
		{
			if (methods == null)
			{
				InitializeMetadata(module);
			}
			return methods.TryGetValue(token, out method);
		}

		private void InitializeMetadata(ModuleDefinition module)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			types = new Dictionary<uint, TypeDefinition>();
			methods = new Dictionary<uint, MethodDefinition>();
			foreach (TypeDefinition type in module.GetTypes())
			{
				Dictionary<uint, TypeDefinition> dictionary = types;
				MetadataToken metadataToken = ((MemberReference)type).MetadataToken;
				dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), type);
				InitializeMethods(type);
			}
		}

		private void InitializeMethods(TypeDefinition type)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					Dictionary<uint, MethodDefinition> dictionary = methods;
					MetadataToken metadataToken = ((MemberReference)current).MetadataToken;
					dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void SetModuleProps(string szName)
		{
			throw new NotImplementedException();
		}

		public void Save(string szFile, uint dwSaveFlags)
		{
			throw new NotImplementedException();
		}

		public void SaveToStream(IntPtr pIStream, uint dwSaveFlags)
		{
			throw new NotImplementedException();
		}

		public uint GetSaveSize(uint fSave)
		{
			throw new NotImplementedException();
		}

		public uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
		{
			throw new NotImplementedException();
		}

		public uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser)
		{
			throw new NotImplementedException();
		}

		public void SetHandler(object pUnk)
		{
			throw new NotImplementedException();
		}

		public uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags)
		{
			throw new NotImplementedException();
		}

		public void DefineMethodImpl(uint td, uint tkBody, uint tkDecl)
		{
			throw new NotImplementedException();
		}

		public uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName)
		{
			throw new NotImplementedException();
		}

		public uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit)
		{
			throw new NotImplementedException();
		}

		public uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent)
		{
			throw new NotImplementedException();
		}

		public uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize)
		{
			throw new NotImplementedException();
		}

		public void DeleteClassLayout(uint td)
		{
			throw new NotImplementedException();
		}

		public void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType)
		{
			throw new NotImplementedException();
		}

		public void DeleteFieldMarshal(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
		{
			throw new NotImplementedException();
		}

		public void SetRVA(uint md, uint ulRVA)
		{
			throw new NotImplementedException();
		}

		public uint GetTokenFromSig(IntPtr pvSig, uint cbSig)
		{
			throw new NotImplementedException();
		}

		public uint DefineModuleRef(string szName)
		{
			throw new NotImplementedException();
		}

		public void SetParent(uint mr, uint tk)
		{
			throw new NotImplementedException();
		}

		public uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig)
		{
			throw new NotImplementedException();
		}

		public void SaveToMemory(IntPtr pbData, uint cbData)
		{
			throw new NotImplementedException();
		}

		public uint DefineUserString(string szString, uint cchString)
		{
			throw new NotImplementedException();
		}

		public void DeleteToken(uint tkObj)
		{
			throw new NotImplementedException();
		}

		public void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags)
		{
			throw new NotImplementedException();
		}

		public void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
		{
			throw new NotImplementedException();
		}

		public void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
		{
			throw new NotImplementedException();
		}

		public void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
		{
			throw new NotImplementedException();
		}

		public void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
		{
			throw new NotImplementedException();
		}

		public void DeletePinvokeMap(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute)
		{
			throw new NotImplementedException();
		}

		public void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute)
		{
			throw new NotImplementedException();
		}

		public uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs)
		{
			throw new NotImplementedException();
		}

		public void ApplyEditAndContinue(object pImport)
		{
			throw new NotImplementedException();
		}

		public uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax)
		{
			throw new NotImplementedException();
		}

		public void SetMethodImplFlags(uint md, uint dwImplFlags)
		{
			throw new NotImplementedException();
		}

		public void SetFieldRVA(uint fd, uint ulRVA)
		{
			throw new NotImplementedException();
		}

		public void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, object pHandler)
		{
			throw new NotImplementedException();
		}

		public void MergeEnd()
		{
			throw new NotImplementedException();
		}

		public void CloseEnum(uint hEnum)
		{
			throw new NotImplementedException();
		}

		public uint CountEnum(uint hEnum)
		{
			throw new NotImplementedException();
		}

		public void ResetEnum(uint hEnum, uint ulPos)
		{
			throw new NotImplementedException();
		}

		public uint EnumTypeDefs(ref uint phEnum, uint[] rTypeDefs, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumInterfaceImpls(ref uint phEnum, uint td, uint[] rImpls, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumTypeRefs(ref uint phEnum, uint[] rTypeRefs, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass)
		{
			throw new NotImplementedException();
		}

		public Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName)
		{
			throw new NotImplementedException();
		}

		public uint GetModuleFromScope()
		{
			throw new NotImplementedException();
		}

		public uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected I4, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetType(td, out var type))
			{
				Marshal.WriteInt16(szTypeDef, 0);
				pchTypeDef = 1u;
				return 0u;
			}
			WriteString(((TypeReference)type).IsNested ? ((MemberReference)type).Name : ((MemberReference)type).FullName, szTypeDef, cchTypeDef, out pchTypeDef);
			WriteIntPtr(pdwTypeDefFlags, (uint)(int)type.Attributes);
			if (type.BaseType == null)
			{
				return 0u;
			}
			MetadataToken metadataToken = ((MemberReference)type.BaseType).MetadataToken;
			return ((MetadataToken)(ref metadataToken)).ToUInt32();
		}

		private static void WriteIntPtr(IntPtr ptr, uint value)
		{
			if (!(ptr == IntPtr.Zero))
			{
				Marshal.WriteInt32(ptr, (int)value);
			}
		}

		private static void WriteString(string str, IntPtr buffer, uint bufferSize, out uint chars)
		{
			uint num = ((str.Length + 1 >= bufferSize) ? (bufferSize - 1) : ((uint)str.Length));
			chars = num + 1;
			int num2 = 0;
			for (int i = 0; i < num; i++)
			{
				Marshal.WriteInt16(buffer, num2, str[i]);
				num2 += 2;
			}
			Marshal.WriteInt16(buffer, num2, 0);
		}

		public uint GetInterfaceImplProps(uint iiImpl, out uint pClass)
		{
			throw new NotImplementedException();
		}

		public uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName)
		{
			throw new NotImplementedException();
		}

		public uint ResolveTypeRef(uint tr, ref Guid riid, out object ppIScope)
		{
			throw new NotImplementedException();
		}

		public uint EnumMembers(ref uint phEnum, uint cl, uint[] rMembers, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, uint[] rMembers, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, uint[] rMethods, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, uint[] rFields, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumParams(ref uint phEnum, uint mb, uint[] rParams, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMemberRefs(ref uint phEnum, uint tkParent, uint[] rMemberRefs, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethodImpls(ref uint phEnum, uint td, uint[] rMethodBody, uint[] rMethodDecl, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, uint[] rPermission, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint FindMember(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindMethod(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindField(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindMemberRef(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected I4, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected I4, but got Unknown
			if (!TryGetMethod(mb, out var method))
			{
				Marshal.WriteInt16(szMethod, 0);
				pchMethod = 1u;
				pClass = 0u;
				return 0u;
			}
			MetadataToken metadataToken = ((MemberReference)method.DeclaringType).MetadataToken;
			pClass = ((MetadataToken)(ref metadataToken)).ToUInt32();
			WriteString(((MemberReference)method).Name, szMethod, cchMethod, out pchMethod);
			WriteIntPtr(pdwAttr, (uint)(int)method.Attributes);
			WriteIntPtr(pulCodeRVA, (uint)method.RVA);
			return (uint)(int)method.ImplAttributes;
		}

		public uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, uint[] rmdOtherMethod, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethodSemantics(ref uint phEnum, uint mb, uint[] rEventProp, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetMethodSemantics(uint mb, uint tkEventProp)
		{
			throw new NotImplementedException();
		}

		public uint GetClassLayout(uint td, out uint pdwPackSize, IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset)
		{
			throw new NotImplementedException();
		}

		public uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType)
		{
			throw new NotImplementedException();
		}

		public uint GetRVA(uint tk, out uint pulCodeRVA)
		{
			throw new NotImplementedException();
		}

		public uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission)
		{
			throw new NotImplementedException();
		}

		public uint GetSigFromToken(uint mdSig, out IntPtr ppvSig)
		{
			throw new NotImplementedException();
		}

		public uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName)
		{
			throw new NotImplementedException();
		}

		public uint EnumModuleRefs(ref uint phEnum, uint[] rModuleRefs, uint cmax)
		{
			throw new NotImplementedException();
		}

		public uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig)
		{
			throw new NotImplementedException();
		}

		public uint GetNameFromToken(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint EnumUnresolvedMethods(ref uint phEnum, uint[] rMethods, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetUserString(uint stk, StringBuilder szString, uint cchString)
		{
			throw new NotImplementedException();
		}

		public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName)
		{
			throw new NotImplementedException();
		}

		public uint EnumSignatures(ref uint phEnum, uint[] rSignatures, uint cmax)
		{
			throw new NotImplementedException();
		}

		public uint EnumTypeSpecs(ref uint phEnum, uint[] rTypeSpecs, uint cmax)
		{
			throw new NotImplementedException();
		}

		public uint EnumUserStrings(ref uint phEnum, uint[] rStrings, uint cmax)
		{
			throw new NotImplementedException();
		}

		public int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam)
		{
			throw new NotImplementedException();
		}

		public uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, uint[] rCustomAttributes, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindTypeRef(uint tkResolutionScope, string szName)
		{
			throw new NotImplementedException();
		}

		public uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
		{
			throw new NotImplementedException();
		}

		public uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
		{
			throw new NotImplementedException();
		}

		public uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, uint[] rmdOtherMethod, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
		{
			throw new NotImplementedException();
		}

		public uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData)
		{
			throw new NotImplementedException();
		}

		public bool IsValidToken(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint GetNestedClassProps(uint tdNestedClass)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetType(tdNestedClass, out var type))
			{
				return 0u;
			}
			if (!((TypeReference)type).IsNested)
			{
				return 0u;
			}
			MetadataToken metadataToken = ((MemberReference)type.DeclaringType).MetadataToken;
			return ((MetadataToken)(ref metadataToken)).ToUInt32();
		}

		public uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig)
		{
			throw new NotImplementedException();
		}

		public int IsGlobal(uint pd)
		{
			throw new NotImplementedException();
		}
	}
	public class NativePdbReader : ISymbolReader, IDisposable
	{
		private int age;

		private Guid guid;

		private readonly Disposable<Stream> pdb_file;

		private readonly Dictionary<string, Document> documents = new Dictionary<string, Document>();

		private readonly Dictionary<uint, PdbFunction> functions = new Dictionary<uint, PdbFunction>();

		private readonly Dictionary<PdbScope, ImportDebugInformation> imports = new Dictionary<PdbScope, ImportDebugInformation>();

		internal NativePdbReader(Disposable<Stream> file)
		{
			//IL_0028: 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)
			pdb_file = file;
		}

		public ISymbolWriterProvider GetWriterProvider()
		{
			return (ISymbolWriterProvider)(object)new NativePdbWriterProvider();
		}

		public bool ProcessDebugHeader(ImageDebugHeader header)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Invalid comparison between Unknown and I4
			if (!header.HasEntries)
			{
				return false;
			}
			ImageDebugHeaderEntry codeViewEntry = Mixin.GetCodeViewEntry(header);
			if (codeViewEntry == null)
			{
				return false;
			}
			if ((int)codeViewEntry.Directory.Type != 2)
			{
				return false;
			}
			byte[] data = codeViewEntry.Data;
			if (data.Length < 24)
			{
				return false;
			}
			if (ReadInt32(data, 0) != 1396986706)
			{
				return false;
			}
			byte[] array = new byte[16];
			Buffer.BlockCopy(data, 4, array, 0, 16);
			guid = new Guid(array);
			age = ReadInt32(data, 20);
			return PopulateFunctions();
		}

		private static int ReadInt32(byte[] bytes, int start)
		{
			return bytes[start] | (bytes[start + 1] << 8) | (bytes[start + 2] << 16) | (bytes[start + 3] << 24);
		}

		private bool PopulateFunctions()
		{
			//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_0008: Unknown result type (might be due to invalid IL or missing references)
			Disposable<Stream> val = pdb_file;
			try
			{
				Dictionary<uint, PdbTokenLine> tokenToSourceMapping;
				string sourceServerData;
				int num;
				Guid guid;
				PdbFunction[] array = PdbFile.LoadFunctions(pdb_file.value, out tokenToSourceMapping, out sourceServerData, out num, out guid);
				if (this.guid != guid)
				{
					return false;
				}
				PdbFunction[] array2 = array;
				foreach (PdbFunction pdbFunction in array2)
				{
					functions.Add(pdbFunction.token, pdbFunction);
				}
			}
			finally
			{
				((IDisposable)val).Dispose();
			}
			return true;
		}

		public MethodDebugInformation Read(MethodDefinition method)
		{
			//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_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Expected O, but got Unknown
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Expected O, but got Unknown
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			MetadataToken metadataToken = ((MemberReference)method).MetadataToken;
			if (!functions.TryGetValue(((MetadataToken)(ref metadataToken)).ToUInt32(), out var value))
			{
				return null;
			}
			MethodDebugInformation val = new MethodDebugInformation(method);
			ReadSequencePoints(value, val);
			val.scope = (ScopeDebugInformation)((!Mixin.IsNullOrEmpty<PdbScope>(value.scopes)) ? ((object)ReadScopeAndLocals(value.scopes[0], val)) : ((object)new ScopeDebugInformation
			{
				Start = new InstructionOffset(0),
				End = new InstructionOffset((int)value.length)
			}));
			uint tokenOfMethodWhoseUsingInfoAppliesToThisMethod = value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod;
			MetadataToken metadataToken2 = ((MemberReference)method).MetadataToken;
			if (tokenOfMethodWhoseUsingInfoAppliesToThisMethod != ((MetadataToken)(ref metadataToken2)).ToUInt32() && value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod != 0)
			{
				val.scope.import = GetImport(value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod, ((MemberReference)method).Module);
			}
			if (value.scopes.Length > 1)
			{
				for (int i = 1; i < value.scopes.Length; i++)
				{
					ScopeDebugInformation val2 = ReadScopeAndLocals(value.scopes[i], val);
					if (!AddScope(val.scope.Scopes, val2))
					{
						val.scope.Scopes.Add(val2);
					}
				}
			}
			if (value.iteratorScopes != null)
			{
				StateMachineScopeDebugInformation val3 = new StateMachineScopeDebugInformation();
				foreach (ILocalScope iteratorScope in value.iteratorScopes)
				{
					val3.Scopes.Add(new StateMachineScope((int)iteratorScope.Offset, (int)(iteratorScope.Offset + iteratorScope.Length + 1)));
				}
				((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val3);
			}
			if (value.synchronizationInformation != null)
			{
				AsyncMethodBodyDebugInformation val4 = new AsyncMethodBodyDebugInformation((int)value.synchronizationInformation.GeneratedCatchHandlerOffset);
				PdbSynchronizationPoint[] synchronizationPoints = value.synchronizationInformation.synchronizationPoints;
				foreach (PdbSynchronizationPoint pdbSynchronizationPoint in synchronizationPoints)
				{
					val4.Yields.Add(new InstructionOffset((int)pdbSynchronizationPoint.SynchronizeOffset));
					val4.Resumes.Add(new InstructionOffset((int)pdbSynchronizationPoint.ContinuationOffset));
					val4.ResumeMethods.Add(method);
				}
				((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val4);
				val.StateMachineKickOffMethod = (MethodDefinition)((MemberReference)method).Module.LookupToken((int)value.synchronizationInformation.kickoffMethodToken);
			}
			return val;
		}

		private Collection<ScopeDebugInformation> ReadScopeAndLocals(PdbScope[] scopes, MethodDebugInformation info)
		{
			Collection<ScopeDebugInformation> val = new Collection<ScopeDebugInformation>(scopes.Length);
			foreach (PdbScope pdbScope in scopes)
			{
				if (pdbScope != null)
				{
					val.Add(ReadScopeAndLocals(pdbScope, info));
				}
			}
			return val;
		}

		private ScopeDebugInformation ReadScopeAndLocals(PdbScope scope, MethodDebugInformation info)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			ScopeDebugInformation val = new ScopeDebugInformation();
			val.Start = new InstructionOffset((int)scope.offset);
			val.End = new InstructionOffset((int)(scope.offset + scope.length));
			if (!Mixin.IsNullOrEmpty<PdbSlot>(scope.slots))
			{
				val.variables = new Collection<VariableDebugInformation>(scope.slots.Length);
				PdbSlot[] slots = scope.slots;
				foreach (PdbSlot pdbSlot in slots)
				{
					if ((pdbSlot.flags & 1) == 0)
					{
						VariableDebugInformation val2 = new VariableDebugInformation((int)pdbSlot.slot, pdbSlot.name);
						if ((pdbSlot.flags & 4u) != 0)
						{
							val2.IsDebuggerHidden = true;
						}
						val.variables.Add(val2);
					}
				}
			}
			if (!Mixin.IsNullOrEmpty<PdbConstant>(scope.constants))
			{
				val.constants = new Collection<ConstantDebugInformation>(scope.constants.Length);
				PdbConstant[] constants = scope.constants;
				foreach (PdbConstant pdbConstant in constants)
				{
					TypeReference val3 = ((MemberReference)info.Method).Module.Read<PdbConstant, TypeReference>(pdbConstant, (Func<PdbConstant, MetadataReader, TypeReference>)((PdbConstant c, MetadataReader r) => r.ReadConstantSignature(new MetadataToken(c.token))));
					object obj = pdbConstant.value;
					if (val3 != null && !val3.IsValueType && obj is int && (int)obj == 0)
					{
						obj = null;
					}
					val.constants.Add(new ConstantDebugInformation(pdbConstant.name, val3, obj));
				}
			}
			if (!Mixin.IsNullOrEmpty<string>(scope.usedNamespaces))
			{
				if (imports.TryGetValue(scope, out var value))
				{
					val.import = value;
				}
				else
				{
					value = GetImport(scope, ((MemberReference)info.Method).Module);
					imports.Add(scope, value);
					val.import = value;
				}
			}
			val.scopes = ReadScopeAndLocals(scope.scopes, info);
			return val;
		}

		private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope)
		{
			//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_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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)
			Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ScopeDebugInformation current = enumerator.Current;
					if (current.HasScopes && AddScope(current.Scopes, scope))
					{
						return true;
					}
					InstructionOffset val = scope.Start;
					int offset = ((InstructionOffset)(ref val)).Offset;
					val = current.Start;
					if (offset >= ((InstructionOffset)(ref val)).Offset)
					{
						val = scope.End;
						int offset2 = ((InstructionOffset)(ref val)).Offset;
						val = current.End;
						if (offset2 <= ((InstructionOffset)(ref val)).Offset)
						{
							current.Scopes.Add(scope);
							return true;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return false;
		}

		private ImportDebugInformation GetImport(uint token, ModuleDefinition module)
		{
			if (!functions.TryGetValue(token, out var value))
			{
				return null;
			}
			if (value.scopes.Length != 1)
			{
				return null;
			}
			PdbScope pdbScope = value.scopes[0];
			if (imports.TryGetValue(pdbScope, out var value2))
			{
				return value2;
			}
			value2 = GetImport(pdbScope, module);
			imports.Add(pdbScope, value2);
			return value2;
		}

		private static ImportDebugInformation GetImport(PdbScope scope, ModuleDefinition module)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			if (Mixin.IsNullOrEmpty<string>(scope.usedNamespaces))
			{
				return null;
			}
			ImportDebugInformation val = new ImportDebugInformation();
			string[] usedNamespaces = scope.usedNamespaces;
			foreach (string text in usedNamespaces)
			{
				if (string.IsNullOrEmpty(text))
				{
					continue;
				}
				ImportTarget val2 = null;
				string text2 = text.Substring(1);
				switch (text[0])
				{
				case 'U':
					val2 = new ImportTarget((ImportTargetKind)1)
					{
						@namespace = text2
					};
					break;
				case 'T':
				{
					TypeReference val4 = TypeParser.ParseType(module, text2, false);
					if (val4 != null)
					{
						val2 = new ImportTarget((ImportTargetKind)3)
						{
							type = val4
						};
					}
					break;
				}
				case 'A':
				{
					int num = text.IndexOf(' ');
					if (num < 0)
					{
						val2 = new ImportTarget((ImportTargetKind)1)
						{
							@namespace = text
						};
						break;
					}
					string alias = text.Substring(1, num - 1);
					string text3 = text.Substring(num + 2);
					switch (text[num + 1])
					{
					case 'U':
						val2 = new ImportTarget((ImportTargetKind)7)
						{
							alias = alias,
							@namespace = text3
						};
						break;
					case 'T':
					{
						TypeReference val3 = TypeParser.ParseType(module, text3, false);
						if (val3 != null)
						{
							val2 = new ImportTarget((ImportTargetKind)9)
							{
								alias = alias,
								type = val3
							};
						}
						break;
					}
					}
					break;
				}
				case '*':
					val2 = new ImportTarget((ImportTargetKind)1)
					{
						@namespace = text2
					};
					break;
				case '@':
					if (!text2.StartsWith("P:"))
					{
						continue;
					}
					val2 = new ImportTarget((ImportTargetKind)1)
					{
						@namespace = text2.Substring(2)
					};
					break;
				}
				if (val2 != null)
				{
					val.Targets.Add(val2);
				}
			}
			return val;
		}

		private void ReadSequencePoints(PdbFunction function, MethodDebugInformation info)
		{
			if (function.lines != null)
			{
				info.sequence_points = new Collection<SequencePoint>();
				PdbLines[] lines = function.lines;
				foreach (PdbLines lines2 in lines)
				{
					ReadLines(lines2, info);
				}
			}
		}

		private void ReadLines(PdbLines lines, MethodDebugInformation info)
		{
			Document document = GetDocument(lines.file);
			PdbLine[] lines2 = lines.lines;
			for (int i = 0; i < lines2.Length; i++)
			{
				ReadLine(lines2[i], document, info);
			}
		}

		private static void ReadLine(PdbLine line, Document document, MethodDebugInformation info)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			SequencePoint val = new SequencePoint((int)line.offset, document);
			val.StartLine = (int)line.lineBegin;
			val.StartColumn = line.colBegin;
			val.EndLine = (int)line.lineEnd;
			val.EndColumn = line.colEnd;
			info.sequence_points.Add(val);
		}

		private Document GetDocument(PdbSource source)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			string name = source.name;
			if (documents.TryGetValue(name, out var value))
			{
				return value;
			}
			value = new Document(name)
			{
				Language = PdbGuidMapping.ToLanguage(source.language),
				LanguageVendor = PdbGuidMapping.ToVendor(source.vendor),
				Type = PdbGuidMapping.ToType(source.doctype)
			};
			documents.Add(name, value);
			return value;
		}

		public void Dispose()
		{
			//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)
			pdb_file.Dispose();
		}
	}
	public class NativePdbWriter : ISymbolWriter, IDisposable
	{
		private readonly ModuleDefinition module;

		private readonly MetadataBuilder metadata;

		private readonly SymWriter writer;

		private readonly Dictionary<string, SymDocumentWriter> documents;

		private readonly Dictionary<ImportDebugInformation, MetadataToken> import_info_to_parent;

		internal NativePdbWriter(ModuleDefinition module, SymWriter writer)
		{
			this.module = module;
			metadata = module.metadata_builder;
			this.writer = writer;
			documents = new Dictionary<string, SymDocumentWriter>();
			import_info_to_parent = new Dictionary<ImportDebugInformation, MetadataToken>();
		}

		public ISymbolReaderProvider GetReaderProvider()
		{
			return (ISymbolReaderProvider)(object)new NativePdbReaderProvider();
		}

		public ImageDebugHeader GetDebugHeader()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			ImageDebugDirectory idd;
			byte[] debugInfo = writer.GetDebugInfo(out idd);
			idd.TimeDateStamp = (int)module.timestamp;
			return new ImageDebugHeader(new ImageDebugHeaderEntry(idd, debugInfo));
		}

		public void Write(MethodDebugInformation info)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			MetadataToken metadataToken = ((MemberReference)info.method).MetadataToken;
			int methodToken = ((MetadataToken)(ref metadataToken)).ToInt32();
			if (info.HasSequencePoints || info.scope != null || ((DebugInformation)info).HasCustomDebugInformations || info.StateMachineKickOffMethod != null)
			{
				writer.OpenMethod(methodToken);
				if (!Mixin.IsNullOrEmpty<SequencePoint>(info.sequence_points))
				{
					DefineSequencePoints(info.sequence_points);
				}
				MetadataToken import_parent = default(MetadataToken);
				if (info.scope != null)
				{
					DefineScope(info.scope, info, out import_parent);
				}
				DefineCustomMetadata(info, import_parent);
				writer.CloseMethod();
			}
		}

		private void DefineCustomMetadata(MethodDebugInformation info, MetadataToken import_parent)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			CustomMetadataWriter customMetadataWriter = new CustomMetadataWriter(writer);
			if (((MetadataToken)(ref import_parent)).RID != 0)
			{
				customMetadataWriter.WriteForwardInfo(import_parent);
			}
			else if (info.scope != null && info.scope.Import != null && info.scope.Import.HasTargets)
			{
				customMetadataWriter.WriteUsingInfo(info.scope.Import);
			}
			if (info.Method.HasCustomAttributes)
			{
				Enumerator<CustomAttribute> enumerator = info.Method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						TypeReference attributeType = current.AttributeType;
						if (Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "IteratorStateMachineAttribute") || Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute"))
						{
							CustomAttributeArgument val = current.ConstructorArguments[0];
							object value = ((CustomAttributeArgument)(ref val)).Value;
							TypeReference val2 = (TypeReference)((value is TypeReference) ? value : null);
							if (val2 != null)
							{
								customMetadataWriter.WriteForwardIterator(val2);
							}
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			if (((DebugInformation)info).HasCustomDebugInformations)
			{
				CustomDebugInformation? obj = ((IEnumerable<CustomDebugInformation>)((DebugInformation)info).CustomDebugInformations).FirstOrDefault((Func<CustomDebugInformation, bool>)((CustomDebugInformation cdi) => (int)cdi.Kind == 1));
				StateMachineScopeDebugInformation val3 = (StateMachineScopeDebugInformation)(object)((obj is StateMachineScopeDebugInformation) ? obj : null);
				if (val3 != null)
				{
					customMetadataWriter.WriteIteratorScopes(val3, info);
				}
			}
			customMetadataWriter.WriteCustomMetadata();
			DefineAsyncCustomMetadata(info);
		}

		private void DefineAsyncCustomMetadata(MethodDebugInformation info)
		{
			//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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			if (!((DebugInformation)info).HasCustomDebugInformations)
			{
				return;
			}
			Enumerator<CustomDebugInformation> enumerator = ((DebugInformation)info).CustomDebugInformations.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomDebugInformation current = enumerator.Current;
					AsyncMethodBodyDebugInformation val = (AsyncMethodBodyDebugInformation)(object)((current is AsyncMethodBodyDebugInformation) ? current : null);
					if (val == null)
					{
						continue;
					}
					using MemoryStream memoryStream = new MemoryStream();
					BinaryStreamWriter val2 = new BinaryStreamWriter((Stream)memoryStream);
					int num;
					MetadataToken metadataToken;
					if (info.StateMachineKickOffMethod == null)
					{
						num = 0;
					}
					else
					{
						metadataToken = ((MemberReference)info.StateMachineKickOffMethod).MetadataToken;
						num = (int)((MetadataToken)(ref metadataToken)).ToUInt32();
					}
					val2.WriteUInt32((uint)num);
					InstructionOffset val3 = val.CatchHandler;
					val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset);
					val2.WriteUInt32((uint)val.Resumes.Count);
					for (int i = 0; i < val.Resumes.Count; i++)
					{
						val3 = val.Yields[i];
						val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset);
						metadataToken = ((MemberReference)val.resume_methods[i]).MetadataToken;
						val2.WriteUInt32(((MetadataToken)(ref metadataToken)).ToUInt32());
						val3 = val.Resumes[i];
						val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset);
					}
					writer.DefineCustomMetadata("asyncMethodInfo", memoryStream.ToArray());
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		private void DefineScope(ScopeDebugInformation scope, MethodDebugInformation info, out MetadataToken import_parent)
		{
			//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_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Invalid comparison between Unknown and I4
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Invalid comparison between Unknown and I4
			//IL_01a0: 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_00cc: Invalid comparison between Unknown and I4
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Invalid comparison between Unknown and I4
			InstructionOffset val = scope.Start;
			int offset = ((InstructionOffset)(ref val)).Offset;
			val = scope.End;
			int num;
			if (!((InstructionOffset)(ref val)).IsEndOfMethod)
			{
				val = scope.End;
				num = ((InstructionOffset)(ref val)).Offset;
			}
			else
			{
				num = info.code_size;
			}
			int num2 = num;
			import_parent = new MetadataToken(0u);
			writer.OpenScope(offset);
			if (scope.Import != null && scope.Import.HasTargets && !import_info_to_parent.TryGetValue(info.scope.Import, out import_parent))
			{
				Enumerator<ImportTarget> enumerator = scope.Import.Targets.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						ImportTarget current = enumerator.Current;
						ImportTargetKind kind = current.Kind;
						if ((int)kind <= 3)
						{
							if ((int)kind != 1)
							{
								if ((int)kind == 3)
								{
									writer.UsingNamespace("T" + TypeParser.ToParseable(current.type, true));
								}
							}
							else
							{
								writer.UsingNamespace("U" + current.@namespace);
							}
						}
						else if ((int)kind != 7)
						{
							if ((int)kind == 9)
							{
								writer.UsingNamespace("A" + current.Alias + " T" + TypeParser.ToParseable(current.type, true));
							}
						}
						else
						{
							writer.UsingNamespace("A" + current.Alias + " U" + current.@namespace);
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				import_info_to_parent.Add(info.scope.Import, ((MemberReference)info.method).MetadataToken);
			}
			int local_var_token = ((MetadataToken)(ref info.local_var_token)).ToInt32();
			if (!Mixin.IsNullOrEmpty<VariableDebugInformation>(scope.variables))
			{
				for (int i = 0; i < scope.variables.Count; i++)
				{
					VariableDebugInformation variable = scope.variables[i];
					DefineLocalVariable(variable, local_var_token, offset, num2);
				}
			}
			if (!Mixin.IsNullOrEmpty<ConstantDebugInformation>(scope.constants))
			{
				for (int j = 0; j < scope.constants.Count; j++)
				{
					ConstantDebugInformation constant = scope.constants[j];
					DefineConstant(constant);
				}
			}
			if (!Mixin.IsNullOrEmpty<ScopeDebugInformation>(scope.scopes))
			{
				for (int k = 0; k < scope.scopes.Count; k++)
				{
					DefineScope(scope.scopes[k], info, out var _);
				}
			}
			writer.CloseScope(num2);
		}

		private void DefineSequencePoints(Collection<SequencePoint> sequence_points)
		{
			for (int i = 0; i < sequence_points.Count; i++)
			{
				SequencePoint val = sequence_points[i];
				writer.DefineSequencePoints(GetDocument(val.Document), new int[1] { val.Offset }, new int[1] { val.StartLine }, new int[1] { val.StartColumn }, new int[1] { val.EndLine }, new int[1] { val.EndColumn });
			}
		}

		private void DefineLocalVariable(VariableDebugInformation variable, int local_var_token, int start_offset, int end_offset)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			writer.DefineLocalVariable2(variable.Name, variable.Attributes, local_var_token, variable.Index, 0, 0, start_offset, end_offset);
		}

		private void DefineConstant(ConstantDebugInformation constant)
		{
			uint num = metadata.AddStandAloneSignature(metadata.GetConstantTypeBlobIndex(constant.ConstantType));
			MetadataToken val = default(MetadataToken);
			((MetadataToken)(ref val))..ctor((TokenType)285212672, num);
			writer.DefineConstant2(constant.Name, constant.Value, ((MetadataToken)(ref val)).ToInt32());
		}

		private SymDocumentWriter GetDocument(Document document)
		{
			if (document == null)
			{
				return null;
			}
			if (documents.TryGetValue(document.Url, out var value))
			{
				return value;
			}
			value = writer.DefineDocument(document.Url, document.LanguageGuid, document.LanguageVendorGuid, document.TypeGuid);
			documents[document.Url] = value;
			return value;
		}

		public void Dispose()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			MethodDefinition entryPoint = module.EntryPoint;
			if (entryPoint != null)
			{
				SymWriter symWriter = writer;
				MetadataToken metadataToken = ((MemberReference)entryPoint).MetadataToken;
				symWriter.SetUserEntryPoint(((MetadataToken)(ref metadataToken)).ToInt32());
			}
			writer.Close();
		}
	}
	internal enum CustomMetadataType : byte
	{
		UsingInfo = 0,
		ForwardInfo = 1,
		IteratorScopes = 3,
		ForwardIterator = 4
	}
	internal class CustomMetadataWriter : IDisposable
	{
		private readonly SymWriter sym_writer;

		private readonly MemoryStream stream;

		private readonly BinaryStreamWriter writer;

		private int count;

		private const byte version = 4;

		public CustomMetadataWriter(SymWriter sym_writer)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			this.sym_writer = sym_writer;
			stream = new MemoryStream();
			writer = new BinaryStreamWriter((Stream)stream);
			writer.WriteByte((byte)4);
			writer.WriteByte((byte)0);
			writer.Align(4);
		}

		public void WriteUsingInfo(ImportDebugInformation import_info)
		{
			Write(CustomMetadataType.UsingInfo, delegate
			{
				writer.WriteUInt16((ushort)1);
				writer.WriteUInt16((ushort)import_info.Targets.Count);
			});
		}

		public void WriteForwardInfo(MetadataToken import_parent)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Write(CustomMetadataType.ForwardInfo, delegate
			{
				writer.WriteUInt32(((MetadataToken)(ref import_parent)).ToUInt32());
			});
		}

		public void WriteIteratorScopes(StateMachineScopeDebugInformation state_machine, MethodDebugInformation debug_info)
		{
			Write(CustomMetadataType.IteratorScopes, delegate
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				Collection<StateMachineScope> scopes = state_machine.Scopes;
				writer.WriteInt32(scopes.Count);
				Enumerator<StateMachineScope> enumerator = scopes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						StateMachineScope current = enumerator.Current;
						InstructionOffset val = current.Start;
						int offset = ((InstructionOffset)(ref val)).Offset;
						val = current.End;
						int num;
						if (!((InstructionOffset)(ref val)).IsEndOfMethod)
						{
							val = current.End;
							num = ((InstructionOffset)(ref val)).Offset;
						}
						else
						{
							num = debug_info.code_size;
						}
						int num2 = num;
						writer.WriteInt32(offset);
						writer.WriteInt32(num2 - 1);
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			});
		}

		public void WriteForwardIterator(TypeReference type)
		{
			Write(CustomMetadataType.ForwardIterator, delegate
			{
				writer.WriteBytes(Encoding.Unicode.GetBytes(((MemberReference)type).Name));
			});
		}

		private void Write(CustomMetadataType type, Action write)
		{
			count++;
			writer.WriteByte((byte)4);
			writer.WriteByte((byte)type);
			writer.Align(4);
			int position = writer.Position;
			writer.WriteUInt32(0u);
			write();
			writer.Align(4);
			int position2 = writer.Position;
			int num = position2 - position + 4;
			writer.Position = position;
			writer.WriteInt32(num);
			writer.Position = position2;
		}

		public void WriteCustomMetadata()
		{
			if (count != 0)
			{
				((BinaryWriter)(object)writer).BaseStream.Position = 1L;
				writer.WriteByte((byte)count);
				((BinaryWriter)(object)writer).Flush();
				sym_writer.DefineCustomMetadata("MD2", stream.ToArray());
			}
		}

		public void Dispose()
		{
			stream.Dispose();
		}
	}
	public sealed class NativePdbReaderProvider : ISymbolReaderProvider
	{
		public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolReader)(object)new NativePdbReader(Disposable.Owned<Stream>((Stream)File.OpenRead(Mixin.GetPdbFileName(fileName))));
		}

		public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			return (ISymbolReader)(object)new NativePdbReader(Disposable.NotOwned<Stream>(symbolStream));
		}
	}
	public sealed class PdbReaderProvider : ISymbolReaderProvider
	{
		public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			if (module.HasDebugHeader && Mixin.GetEmbeddedPortablePdbEntry(module.GetDebugHeader()) != null)
			{
				return new EmbeddedPortablePdbReaderProvider().GetSymbolReader(module, fileName);
			}
			if (!Mixin.IsPortablePdb(Mixin.GetPdbFileName(fileName)))
			{
				return new NativePdbReaderProvider().GetSymbolReader(module, fileName);
			}
			return new PortablePdbReaderProvider().GetSymbolReader(module, fileName);
		}

		public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			Mixin.CheckReadSeek(symbolStream);
			if (!Mixin.IsPortablePdb(symbolStream))
			{
				return new NativePdbReaderProvider().GetSymbolReader(module, symbolStream);
			}
			return new PortablePdbReaderProvider().GetSymbolReader(module, symbolStream);
		}
	}
	public sealed class NativePdbWriterProvider : ISymbolWriterProvider
	{
		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName)
		{
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolWriter)(object)new NativePdbWriter(module, CreateWriter(module, Mixin.GetPdbFileName(fileName)));
		}

		private static SymWriter CreateWriter(ModuleDefinition module, string pdb)
		{
			SymWriter symWriter = new SymWriter();
			if (File.Exists(pdb))
			{
				File.Delete(pdb);
			}
			symWriter.Initialize(new ModuleMetadata(module), pdb, fFullBuild: true);
			return symWriter;
		}

		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream)
		{
			throw new NotImplementedException();
		}
	}
	public sealed class PdbWriterProvider : ISymbolWriterProvider
	{
		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			if (HasPortablePdbSymbols(module))
			{
				return new PortablePdbWriterProvider().GetSymbolWriter(module, fileName);
			}
			return new NativePdbWriterProvider().GetSymbolWriter(module, fileName);
		}

		private static bool HasPortablePdbSymbols(ModuleDefinition module)
		{
			if (module.symbol_reader != null)
			{
				return module.symbol_reader is PortablePdbReader;
			}
			return false;
		}

		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			Mixin.CheckReadSeek(symbolStream);
			if (HasPortablePdbSymbols(module))
			{
				return new PortablePdbWriterProvider().GetSymbolWriter(module, symbolStream);
			}
			return new NativePdbWriterProvider().GetSymbolWriter(module, symbolStream);
		}
	}
	internal class SymDocumentWriter
	{
		private readonly ISymUnmanagedDocumentWriter m_unmanagedDocumentWriter;

		public SymDocumentWriter(ISymUnmanagedDocumentWriter unmanagedDocumentWriter)
		{
			m_unmanagedDocumentWriter = unmanagedDocumentWriter;
		}

		public ISymUnmanagedDocumentWriter GetUnmanaged()
		{
			return m_unmanagedDocumentWriter;
		}
	}
	internal class SymWriter
	{
		private static Guid s_symUnmangedWriterIID = new Guid("0b97726e-9e6d-4f05-9a26-424022093caa");

		private static Guid s_CorSymWriter_SxS_ClassID = new Guid("108296c1-281e-11d3-bd22-0000f80849bd");

		private readonly ISymUnmanagedWriter2 m_writer;

		private readonly Collection<ISymUnmanagedDocumentWriter> documents;

		[DllImport("ole32.dll")]
		private static extern int CoCreateInstance([In] ref Guid rclsid, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] uint dwClsContext, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppv);

		public SymWriter()
		{
			CoCreateInstance(ref s_CorSymWriter_SxS_ClassID, null, 1u, ref s_symUnmangedWriterIID, out var ppv);
			m_writer = (ISymUnmanagedWriter2)ppv;
			documents = new Collection<ISymUnmanagedDocumentWriter>();
		}

		public byte[] GetDebugInfo(out ImageDebugDirectory idd)
		{
			m_writer.GetDebugInfo(out idd, 0, out var pcData, null);
			byte[] array = new byte[pcData];
			m_writer.GetDebugInfo(out idd, pcData, out pcData, array);
			return array;
		}

		public void DefineLocalVariable2(string name, VariableAttributes attributes, int sigToken, int addr1, int addr2, int addr3, int startOffset, int endOffset)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected I4, but got Unknown
			m_writer.DefineLocalVariable2(name, (int)attributes, sigToken, 1, addr1, addr2, addr3, startOffset, endOffset);
		}

		public void DefineConstant2(string name, object value, int sigToken)
		{
			if (value == null)
			{
				m_writer.DefineConstant2(name, 0, sigToken);
			}
			else
			{
				m_writer.DefineConstant2(name, value, sigToken);
			}
		}

		public void Close()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			m_writer.Close();
			Marshal.ReleaseComObject(m_writer);
			Enumerator<ISymUnmanagedDocumentWriter> enumerator = documents.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Marshal.ReleaseComObject(enumerator.Current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void CloseMethod()
		{
			m_writer.CloseMethod();
		}

		public void CloseNamespace()
		{
			m_writer.CloseNamespace();
		}

		public void CloseScope(int endOffset)
		{
			m_writer.CloseScope(endOffset);
		}

		public SymDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType)
		{
			m_writer.DefineDocument(url, ref language, ref languageVendor, ref documentType, out var pRetVal);
			documents.Add(pRetVal);
			return new SymDocumentWriter(pRetVal);
		}

		public void DefineSequencePoints(SymDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns)
		{
			m_writer.DefineSequencePoints(document.GetUnmanaged(), offsets.Length, offsets, lines, columns, endLines, endColumns);
		}

		public void Initialize(object emitter, string filename, bool fFullBuild)
		{
			m_writer.Initialize(emitter, filename, null, fFullBuild);
		}

		public void SetUserEntryPoint(int methodToken)
		{
			m_writer.SetUserEntryPoint(methodToken);
		}

		public void OpenMethod(int methodToken)
		{
			m_writer.OpenMethod(methodToken);
		}

		public void OpenNamespace(string name)
		{
			m_writer.OpenNamespace(name);
		}

		public int OpenScope(int startOffset)
		{
			m_writer.OpenScope(startOffset, out var pRetVal);
			return pRetVal;
		}

		public void UsingNamespace(string fullName)
		{
			m_writer.UsingNamespace(fullName);
		}

		public void DefineCustomMetadata(string name, byte[] metadata)
		{
			GCHandle gCHandle = GCHandle.Alloc(metadata, GCHandleType.Pinned);
			m_writer.SetSymAttribute(0u, name, (uint)metadata.Length, gCHandle.AddrOfPinnedObject());
			gCHandle.Free();
		}
	}
}
namespace Microsoft.Cci
{
	public interface ILocalScope
	{
		uint Offset { get; }

		uint Length { get; }
	}
	public interface INamespaceScope
	{
		IEnumerable<IUsedNamespace> UsedNamespaces { get; }
	}
	public interface IUsedNamespace
	{
		IName Alias { get; }

		IName NamespaceName { get; }
	}
	public interface IName
	{
		int UniqueKey { get; }

		int UniqueKeyIgnoringCase { get; }

		string Value { get; }
	}
	internal sealed class PdbIteratorScope : ILocalScope
	{
		private uint offset;

		private uint length;

		public uint Offset => offset;

		public uint Length => length;

		internal PdbIteratorScope(uint offset, uint length)
		{
			this.offset = offset;
			this.length = length;
		}
	}
}
namespace Microsoft.Cci.Pdb
{
	internal class BitAccess
	{
		private byte[] buffer;

		private int offset;

		internal byte[] Buffer => buffer;

		internal int Position
		{
			get
			{
				return offset;
			}
			set
			{
				offset = value;
			}
		}

		internal BitAccess(int capacity)
		{
			buffer = new byte[capacity];
		}

		internal void FillBuffer(Stream stream, int capacity)
		{
			MinCapacity(capacity);
			stream.Read(buffer, 0, capacity);
			offset = 0;
		}

		internal void Append(Stream stream, int count)
		{
			int num = offset + count;
			if (buffer.Length < num)
			{
				byte[] destinationArray = new byte[num];
				Array.Copy(buffer, destinationArray, buffer.Length);
				buffer = destinationArray;
			}
			stream.Read(buffer, offset, count);
			offset += count;
		}

		internal void MinCapacity(int capacity)
		{
			if (buffer.Length < capacity)
			{
				buffer = new byte[capacity];
			}
			offset = 0;
		}

		internal void Align(int alignment)
		{
			while (offset % alignment != 0)
			{
				offset++;
			}
		}

		internal void ReadInt16(out short value)
		{
			value = (short)((buffer[offset] & 0xFF) | (buffer[offset + 1] << 8));
			offset += 2;
		}

		internal void ReadInt8(out sbyte value)
		{
			value = (sbyte)buffer[offset];
			offset++;
		}

		internal void ReadInt32(out int value)
		{
			value = (buffer[offset] & 0xFF) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24);
			offset += 4;
		}

		internal void ReadInt64(out long value)
		{
			value = ((long)buffer[offset] & 0xFFL) | (long)((ulong)buffer[offset + 1] << 8) | (long)((ulong)buffer[offset + 2] << 16) | (long)((ulong)buffer[offset + 3] << 24) | (long)((ulong)buffer[offset + 4] << 32) | (long)((ulong)buffer[offset + 5] << 40) | (long)((ulong)buffer[offset + 6] << 48) | (long)((ulong)buffer[offset + 7] << 56);
			offset += 8;
		}

		internal void ReadUInt16(out ushort value)
		{
			value = (ushort)((buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8));
			offset += 2;
		}

		internal void ReadUInt8(out byte value)
		{
			value = (byte)(buffer[offset] & 0xFFu);
			offset++;
		}

		internal void ReadUInt32(out uint value)
		{
			value = (buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8) | (uint)(buffer[offset + 2] << 16) | (uint)(buffer[offset + 3] << 24);
			offset += 4;
		}

		internal void ReadUInt64(out ulong value)
		{
			value = ((ulong)buffer[offset] & 0xFFuL) | ((ulong)buffer[offset + 1] << 8) | ((ulong)buffer[offset + 2] << 16) | ((ulong)buffer[offset + 3] << 24) | ((ulong)buffer[offset + 4] << 32) | ((ulong)buffer[offset + 5] << 40) | ((ulong)buffer[offset + 6] << 48) | ((ulong)buffer[offset + 7] << 56);
			offset += 8;
		}

		internal void ReadInt32(int[] values)
		{
			for (int i = 0; i < values.Length; i++)
			{
				ReadInt32(out values[i]);
			}
		}

		internal void ReadUInt32(uint[] values)
		{
			for (int i = 0; i < values.Length; i++)
			{
				ReadUInt32(out values[i]);
			}
		}

		internal void ReadBytes(byte[] bytes)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				bytes[i] = buffer[offset++];
			}
		}

		internal float ReadFloat()
		{
			float result = BitConverter.ToSingle(buffer, offset);
			offset += 4;
			return result;
		}

		internal double ReadDouble()
		{
			double result = BitConverter.ToDouble(buffer, offset);
			offset += 8;
			return result;
		}

		internal decimal ReadDecimal()
		{
			int[] array = new int[4];
			ReadInt32(array);
			return new decimal(array[2], array[3], array[1], array[0] < 0, (byte)((array[0] & 0xFF0000) >> 16));
		}

		internal void ReadBString(out string value)
		{
			ReadUInt16(out var value2);
			value = Encoding.UTF8.GetString(buffer, offset, value2);
			offset += value2;
		}

		internal string ReadBString(int len)
		{
			string @string = Encoding.UTF8.GetString(buffer, offset, len);
			offset += len;
			return @string;
		}

		internal void ReadCString(out string value)
		{
			int i;
			for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++)
			{
			}
			value = Encoding.UTF8.GetString(buffer, offset, i);
			offset += i + 1;
		}

		internal void SkipCString(out string value)
		{
			int i;
			for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++)
			{
			}
			offset += i + 1;
			value = null;
		}

		internal void ReadGuid(out Guid guid)
		{
			ReadUInt32(out var value);
			ReadUInt16(out var value2);
			ReadUInt16(out var value3);
			ReadUInt8(out var value4);
			ReadUInt8(out var value5);
			ReadUInt8(out var value6);
			ReadUInt8(out var value7);
			ReadUInt8(out var value8);
			ReadUInt8(out var value9);
			ReadUInt8(out var value10);
			ReadUInt8(out var value11);
			guid = new Guid(value, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11);
		}

		internal string ReadString()
		{
			int i;
			for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i += 2)
			{
			}
			string @string = Encoding.Unicode.GetString(buffer, offset, i);
			offset += i + 2;
			return @string;
		}
	}
	internal struct BitSet
	{
		private int size;

		private uint[] words;

		internal bool IsEmpty => size == 0;

		internal BitSet(BitAccess bits)
		{
			bits.ReadInt32(out size);
			words = new uint[size];
			bits.ReadUInt32(words);
		}

		internal bool IsSet(int index)
		{
			int num = index / 32;
			if (num >= size)
			{
				return false;
			}
			return (words[num] & GetBit(index)) != 0;
		}

		private static uint GetBit(int index)
		{
			return (uint)(1 << index % 32);
		}
	}
	internal struct FLOAT10
	{
		internal byte Data_0;

		internal byte Data_1;

		internal byte Data_2;

		internal byte Data_3;

		internal byte Data_4;

		internal byte Data_5;

		internal byte Data_6;

		internal byte Data_7;

		internal byte Data_8;

		internal byte Data_9;
	}
	internal enum CV_SIGNATURE
	{
		C6 = 0,
		C7 = 1,
		C11 = 2,
		C13 = 4,
		RESERVERD = 5
	}
	internal enum CV_prmode
	{
		CV_TM_DIRECT = 0,
		CV_TM_NPTR32 = 4,
		CV_TM_NPTR64 = 6,
		CV_TM_NPTR128 = 7
	}
	internal enum CV_type
	{
		CV_SPECIAL = 0,
		CV_SIGNED = 1,
		CV_UNSIGNED = 2,
		CV_BOOLEAN = 3,
		CV_REAL = 4,
		CV_COMPLEX = 5,
		CV_SPECIAL2 = 6,
		CV_INT = 7,
		CV_CVRESERVED = 15
	}
	internal enum CV_special
	{
		CV_SP_NOTYPE,
		CV_SP_ABS,
		CV_SP_SEGMENT,
		CV_SP_VOID,
		CV_SP_CURRENCY,
		CV_SP_NBASICSTR,
		CV_SP_FBASICSTR,
		CV_SP_NOTTRANS,
		CV_SP_HRESULT
	}
	internal enum CV_special2
	{
		CV_S2_BIT,
		CV_S2_PASCHAR
	}
	internal enum CV_integral
	{
		CV_IN_1BYTE,
		CV_IN_2BYTE,
		CV_IN_4BYTE,
		CV_IN_8BYTE,
		CV_IN_16BYTE
	}
	internal enum CV_real
	{
		CV_RC_REAL32,
		CV_RC_REAL64,
		CV_RC_REAL80,
		CV_RC_REAL128
	}
	internal enum CV_int
	{
		CV_RI_CHAR = 0,
		CV_RI_INT1 = 0,
		CV_RI_WCHAR = 1,
		CV_RI_UINT1 = 1,
		CV_RI_INT2 = 2,
		CV_RI_UINT2 = 3,
		CV_RI_INT4 = 4,
		CV_RI_UINT4 = 5,
		CV_RI_INT8 = 6,
		CV_RI_UINT8 = 7,
		CV_RI_INT16 = 8,
		CV_RI_UINT16 = 9
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal struct CV_PRIMITIVE_TYPE
	{
		private const uint CV_MMASK = 1792u;

		private const uint CV_TMASK = 240u;

		private const uint CV_SMASK = 15u;

		private const int CV_MSHIFT = 8;

		private const int CV_TSHIFT = 4;

		private const int CV_SSHIFT = 0;

		private const uint CV_FIRST_NONPRIM = 4096u;
	}
	internal enum TYPE_ENUM
	{
		T_NOTYPE = 0,
		T_ABS = 1,
		T_SEGMENT = 2,
		T_VOID = 3,
		T_HRESULT = 8,
		T_32PHRESULT = 1032,
		T_64PHRESULT = 1544,
		T_PVOID = 259,
		T_PFVOID = 515,
		T_PHVOID = 771,
		T_32PVOID = 1027,
		T_64PVOID = 1539,
		T_CURRENCY = 4,
		T_NOTTRANS = 7,
		T_BIT = 96,
		T_PASCHAR = 97,
		T_CHAR = 16,
		T_32PCHAR = 1040,
		T_64PCHAR = 1552,
		T_UCHAR = 32,
		T_32PUCHAR = 1056,
		T_64PUCHAR = 1568,
		T_RCHAR = 112,
		T_32PRCHAR = 1136,
		T_64PRCHAR = 1648,
		T_WCHAR = 113,
		T_32PWCHAR = 1137,
		T_64PWCHAR = 1649,
		T_INT1 = 104,
		T_32PINT1 = 1128,
		T_64PINT1 = 1640,
		T_UINT1 = 105,
		T_32PUINT1 = 1129,
		T_64PUINT1 = 1641,
		T_SHORT = 17,
		T_32PSHORT = 1041,
		T_64PSHORT = 1553,
		T_USHORT = 33,
		T_32PUSHORT = 1057,
		T_64PUSHORT = 1569,
		T_INT2 = 114,
		T_32PINT2 = 1138,
		T_64PINT2 = 1650,
		T_UINT2 = 115,
		T_32PUINT2 = 1139,
		T_64PUINT2 = 1651,
		T_LONG = 18,
		T_ULONG = 34,
		T_32PLONG = 1042,
		T_32PULONG = 1058,
		T_64PLONG = 1554,
		T_64PULONG = 1570,
		T_INT4 = 116,
		T_32PINT4 = 1140,
		T_64PINT4 = 1652,
		T_UINT4 = 117,
		T_32PUINT4 = 1141,
		T_64PUINT4 = 1653,
		T_QUAD = 19,
		T_32PQUAD = 1043,
		T_64PQUAD = 1555,
		T_UQUAD = 35,
		T_32PUQUAD = 1059,
		T_64PUQUAD = 1571,
		T_INT8 = 118,
		T_32PINT8 = 1142,
		T_64PINT8 = 1654,
		T_UINT8 = 119,
		T_32PUINT8 = 1143,
		T_64PUINT8 = 1655,
		T_OCT = 20,
		T_32POCT = 1044,
		T_64POCT = 1556,
		T_UOCT = 36,
		T_32PUOCT = 1060,
		T_64PUOCT = 1572,
		T_INT16 = 120,
		T_32PINT16 = 1144,
		T_64PINT16 = 1656,
		T_UINT16 = 121,
		T_32PUINT16 = 1145,
		T_64PUINT16 = 1657,
		T_REAL32 = 64,
		T_32PREAL32 = 1088,
		T_64PREAL32 = 1600,
		T_REAL64 = 65,
		T_32PREAL64 = 1089,
		T_64PREAL64 = 1601,
		T_REAL80 = 66,
		T_32PREAL80 = 1090,
		T_64PREAL80 = 1602,
		T_REAL128 = 67,
		T_32PREAL128 = 1091,
		T_64PREAL128 = 1603,
		T_CPLX32 = 80,
		T_32PCPLX32 = 1104,
		T_64PCPLX32 = 1616,
		T_CPLX64 = 81,
		T_32PCPLX64 = 1105,
		T_64PCPLX64 = 1617,
		T_CPLX80 = 82,
		T_32PCPLX80 = 1106,
		T_64PCPLX80 = 1618,
		T_CPLX128 = 83,
		T_32PCPLX128 = 1107,
		T_64PCPLX128 = 1619,
		T_BOOL08 = 48,
		T_32PBOOL08 = 1072,
		T_64PBOOL08 = 1584,
		T_BOOL16 = 49,
		T_32PBOOL16 = 1073,
		T_64PBOOL16 = 1585,
		T_BOOL32 = 50,
		T_32PBOOL32 = 1074,
		T_64PBOOL32 = 1586,
		T_BOOL64 = 51,
		T_32PBOOL64 = 1075,
		T_64PBOOL64 = 1587
	}
	internal enum LEAF
	{
		LF_VTSHAPE = 10,
		LF_COBOL1 = 12,
		LF_LABEL = 14,
		LF_NULL = 15,
		LF_NOTTRAN = 16,
		LF_ENDPRECOMP = 20,
		LF_TYPESERVER_ST = 22,
		LF_LIST = 515,
		LF_REFSYM = 524,
		LF_ENUMERATE_ST = 1027,
		LF_TI16_MAX = 4096,
		LF_MODIFIER = 4097,
		LF_POINTER = 4098,
		LF_ARRAY_ST = 4099,
		LF_CLASS_ST = 4100,
		LF_STRUCTURE_ST = 4101,
		LF_UNION_ST = 4102,
		LF_ENUM_ST = 4103,
		LF_PROCEDURE = 4104,
		LF_MFUNCTION = 4105,
		LF_COBOL0 = 4106,
		LF_BARRAY = 4107,
		LF_DIMARRAY_ST = 4108,
		LF_VFTPATH = 4109,
		LF_PRECOMP_ST = 4110,
		LF_OEM = 4111,
		LF_ALIAS_ST = 4112,
		LF_OEM2 = 4113,
		LF_SKIP = 4608,
		LF_ARGLIST = 4609,
		LF_DEFARG_ST = 4610,
		LF_FIELDLIST = 4611,
		LF_DERIVED = 4612,
		LF_BITFIELD = 4613,
		LF_METHODLIST = 4614,
		LF_DIMCONU = 4615,
		LF_DIMCONLU = 4616,
		LF_DIMVARU = 4617,
		LF_DIMVARLU = 4618,
		LF_BCLASS = 5120,
		LF_VBCLASS = 5121,
		LF_IVBCLASS = 5122,
		LF_FRIENDFCN_ST = 5123,
		LF_INDEX = 5124,
		LF_MEMBER_ST = 5125,
		LF_STMEMBER_ST = 5126,
		LF_METHOD_ST = 5127,
		LF_NESTTYPE_ST = 5128,
		LF_VFUNCTAB = 5129,
		LF_FRIENDCLS = 5130,
		LF_ONEMETHOD_ST = 5131,
		LF_VFUNCOFF = 5132,
		LF_NESTTYPEEX_ST = 5133,
		LF_MEMBERMODIFY_ST = 5134,
		LF_MANAGED_ST = 5135,
		LF_ST_MAX = 5376,
		LF_TYPESERVER = 5377,
		LF_ENUMERATE = 5378,
		LF_ARRAY = 5379,
		LF_CLASS = 5380,
		LF_STRUCTURE = 5381,
		LF_UNION = 5382,
		LF_ENUM = 5383,
		LF_DIMARRAY = 5384,
		LF_PRECOMP = 5385,
		LF_ALIAS = 5386,
		LF_DEFARG = 5387,
		LF_FRIENDFCN = 5388,
		LF_MEMBER = 5389,
		LF_STMEMBER = 5390,
		LF_METHOD = 5391,
		LF_NESTTYPE = 5392,
		LF_ONEMETHOD = 5393,
		LF_NESTTYPEEX = 5394,
		LF_MEMBERMODIFY = 5395,
		LF_MANAGED = 5396,
		LF_TYPESERVER2 = 5397,
		LF_NUMERIC = 32768,
		LF_CHAR = 32768,
		LF_SHORT = 32769,
		LF_USHORT = 32770,
		LF_LONG = 32771,
		LF_ULONG = 32772,
		LF_REAL32 = 32773,
		LF_REAL64 = 32774,
		LF_REAL80 = 32775,
		LF_REAL128 = 32776,
		LF_QUADWORD = 32777,
		LF_UQUADWORD = 32778,
		LF_COMPLEX32 = 32780,
		LF_COMPLEX64 = 32781,
		LF_COMPLEX80 = 32782,
		LF_COMPLEX128 = 32783,
		LF_VARSTRING = 32784,
		LF_OCTWORD = 32791,
		LF_UOCTWORD = 32792,
		LF_DECIMAL = 32793,
		LF_DATE = 32794,
		LF_UTF8STRING = 32795,
		LF_PAD0 = 240,
		LF_PAD1 = 241,
		LF_PAD2 = 242,
		LF_PAD3 = 243,
		LF_PAD4 = 244,
		LF_PAD5 = 245,
		LF_PAD6 = 246,
		LF_PAD7 = 247,
		LF_PAD8 = 248,
		LF_PAD9 = 249,
		LF_PAD10 = 250,
		LF_PAD11 = 251,
		LF_PAD12 = 252,
		LF_PAD13 = 253,
		LF_PAD14 = 254,
		LF_PAD15 = 255
	}
	internal enum CV_ptrtype
	{
		CV_PTR_BASE_SEG = 3,
		CV_PTR_BASE_VAL = 4,
		CV_PTR_BASE_SEGVAL = 5,
		CV_PTR_BASE_ADDR = 6,
		CV_PTR_BASE_SEGADDR = 7,
		CV_PTR_BASE_TYPE = 8,
		CV_PTR_BASE_SELF = 9,
		CV_PTR_NEAR32 = 10,
		CV_PTR_64 = 12,
		CV_PTR_UNUSEDPTR = 13
	}
	internal enum CV_ptrmode
	{
		CV_PTR_MODE_PTR,
		CV_PTR_MODE_REF,
		CV_PTR_MODE_PMEM,
		CV_PTR_MODE_PMFUNC,
		CV_PTR_MODE_RESERVED
	}
	internal enum CV_pmtype
	{
		CV_PMTYPE_Undef,
		CV_PMTYPE_D_Single,
		CV_PMTYPE_D_Multiple,
		CV_PMTYPE_D_Virtual,
		CV_PMTYPE_D_General,
		CV_PMTYPE_F_Single,
		CV_PMTYPE_F_Multiple,
		CV_PMTYPE_F_Virtual,
		CV_PMTYPE_F_General
	}
	internal enum CV_methodprop
	{
		CV_MTvanilla,
		CV_MTvirtual,
		CV_MTstatic,
		CV_MTfriend,
		CV_MTintro,
		CV_MTpurevirt,
		CV_MTpureintro
	}
	internal enum CV_VTS_desc
	{
		CV_VTS_near,
		CV_VTS_far,
		CV_VTS_thin,
		CV_VTS_outer,
		CV_VTS_meta,
		CV_VTS_near32,
		CV_VTS_far32,
		CV_VTS_unused
	}
	internal enum CV_LABEL_TYPE
	{
		CV_LABEL_NEAR = 0,
		CV_LABEL_FAR = 4
	}
	[Flags]
	internal enum CV_modifier : ushort
	{
		MOD_const = 1,
		MOD_volatile = 2,
		MOD_unaligned = 4
	}
	[Flags]
	internal enum CV_prop : ushort
	{
		packed = 1,
		ctor = 2,
		ovlops = 4,
		isnested = 8,
		cnested = 0x10,
		opassign = 0x20,
		opcast = 0x40,
		fwdref = 0x80,
		scoped = 0x100
	}
	[Flags]
	internal enum CV_fldattr
	{
		access = 3,
		mprop = 0x1C,
		pseudo = 0x20,
		noinherit = 0x40,
		noconstruct = 0x80,
		compgenx = 0x100
	}
	internal struct TYPTYPE
	{
		internal ushort len;

		internal ushort leaf;
	}
	internal struct CV_PDMR32_NVVFCN
	{
		internal int mdisp;
	}
	internal struct CV_PDMR32_VBASE
	{
		internal int mdisp;

		internal int pdisp;

		internal int vdisp;
	}
	internal struct CV_PMFR32_NVSA
	{
		internal uint off;
	}
	internal struct CV_PMFR32_NVMA
	{
		internal uint off;

		internal int disp;
	}
	internal struct CV_PMFR32_VBASE
	{
		internal uint off;

		internal int mdisp;

		internal int pdisp;

		internal int vdisp;
	}
	internal struct LeafModifier
	{
		internal uint type;

		internal CV_modifier attr;
	}
	[Flags]
	internal enum LeafPointerAttr : uint
	{
		ptrtype = 0x1Fu,
		ptrmode = 0xE0u,
		isflat32 = 0x100u,
		isvolatile = 0x200u,
		isconst = 0x400u,
		isunaligned = 0x800u,
		isrestrict = 0x1000u
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal struct LeafPointer
	{
		internal struct LeafPointerBody
		{
			internal uint utype;

			internal LeafPointerAttr attr;
		}
	}
	internal struct LeafArray
	{
		internal uint elemtype;

		internal uint idxtype;

		internal byte[] data;

		internal string name;
	}
	internal struct LeafClass
	{
		internal ushort count;

		internal ushort property;

		internal uint field;

		internal uint derived;

		internal uint vshape;

		internal byte[] data;

		internal string name;
	}
	internal struct LeafUnion
	{
		internal ushort count;

		internal ushort property;

		internal uint field;

		internal byte[] data;

		internal string name;
	}
	internal struct LeafAlias
	{
		internal uint utype;

		internal string name;
	}
	internal struct LeafManaged
	{
		internal string name;
	}
	internal struct LeafEnum
	{
		internal ushort count;

		internal ushort property;

		internal uint utype;

		internal uint field;

		internal string name;
	}
	internal struct LeafProc
	{
		internal uint rvtype;

		internal byte calltype;

		internal byte reserved;

		internal ushort parmcount;

		internal uint arglist;
	}
	internal struct LeafMFunc
	{
		internal uint rvtype;

		internal uint classtype;

		internal uint thistype;

		internal byte calltype;

		internal byte reserved;

		internal ushort parmcount;

		internal uint arglist;

		internal int thisadjust;
	}
	internal struct LeafVTShape
	{
		internal ushort count;

		internal byte[] desc;
	}
	internal struct LeafCobol0
	{
		internal uint type;

		internal byte[] data;
	}
	internal struct LeafCobol1
	{
		internal byte[] data;
	}
	internal struct LeafBArray
	{
		internal uint utype;
	}
	internal struct LeafLabel
	{
		internal ushort mode;
	}
	internal struct LeafDimArray
	{
		internal uint utype;

		internal uint diminfo;

		internal string name;
	}
	internal struct LeafVFTPath
	{
		internal uint count;

		internal uint[] bases;
	}
	internal struct LeafPreComp
	{
		internal uint start;

		internal uint count;

		internal uint signature;

		internal string name;
	}
	internal struct LeafEndPreComp
	{
		internal uint signature;
	}
	internal struct LeafOEM
	{
		internal ushort cvOEM;

		internal ushort recOEM;

		internal uint count;

		internal uint[] index;
	}
	internal enum OEM_ID
	{
		OEM_MS_FORTRAN90 = 61584,
		OEM_ODI = 16,
		OEM_THOMSON_SOFTWARE = 21587,
		OEM_ODI_REC_BASELIST = 0
	}
	internal struct LeafOEM2
	{
		internal Guid idOem;

		internal uint count;

		internal uint[] index;
	}
	internal struct LeafTypeServer
	{
		internal uint signature;

		internal uint age;

		internal string name;
	}
	internal struct LeafTypeServer2
	{
		internal Guid sig70;

		internal uint age;

		internal string name;
	}
	internal struct LeafSkip
	{
		internal uint type;

		internal byte[] data;
	}
	internal struct LeafArgList
	{
		internal uint count;

		internal uint[] arg;
	}
	internal struct LeafDerived
	{
		internal uint count;

		internal uint[] drvdcls;
	}
	internal struct LeafDefArg
	{
		internal uint type;

		internal byte[] expr;
	}
	internal struct LeafList
	{
		internal byte[] data;
	}
	internal struct LeafFieldList
	{
		internal char[] data;
	}
	internal struct mlMethod
	{
		internal ushort attr;

		internal ushort pad0;

		internal uint index;

		internal uint[] vbaseoff;
	}
	internal struct LeafMethodList
	{
		internal byte[] mList;
	}
	internal struct LeafBitfield
	{
		internal uint type;

		internal byte length;

		internal byte position;
	}
	internal struct LeafDimCon
	{
		internal uint typ;

		internal ushort rank;

		internal byte[] dim;
	}
	internal struct LeafDimVar
	{
		internal uint rank;

		internal uint typ;

		internal uint[] dim;
	}
	internal struct LeafRefSym
	{
		internal byte[] Sym;
	}
	internal struct LeafChar
	{
		internal sbyte val;
	}
	internal struct LeafShort
	{
		internal short val;
	}
	internal struct LeafUShort
	{
		internal ushort val;
	}
	internal struct LeafLong
	{
		internal int val;
	}
	internal struct LeafULong
	{
		internal uint val;
	}
	internal struct LeafQuad
	{
		internal long val;
	}
	internal struct LeafUQuad
	{
		internal ulong val;
	}
	internal struct LeafOct
	{
		internal ulong val0;

		internal ulong val1;
	}
	internal struct LeafUOct
	{
		internal ulong val0;

		internal ulong val1;
	}
	internal struct LeafReal32
	{
		internal float val;
	}
	internal struct LeafReal64
	{
		internal double val;
	}
	internal struct LeafReal80
	{
		internal FLOAT10 val;
	}
	internal struct LeafReal128
	{
		internal ulong val0;

		internal ulong val1;
	}
	internal struct LeafCmplx32
	{
		internal float val_real;

		internal float val_imag;
	}
	internal struct LeafCmplx64
	{
		internal double val_real;

		internal double val_imag;
	}
	internal struct LeafCmplx80
	{
		internal FLOAT10 val_real;

		internal FLOAT10 val_imag;
	}
	internal struct LeafCmplx128
	{
		internal ulong val0_real;

		internal ulong val1_real;

		internal ulong val0_imag;

		internal ulong val1_imag;
	}
	internal struct LeafVarString
	{
		internal ushort len;

		internal byte[] value;
	}
	internal struct LeafIndex
	{
		internal ushort pad0;

		internal uint index;
	}
	internal struct LeafBClass
	{
		internal ushort attr;

		internal uint index;

		internal byte[] offset;
	}
	internal struct LeafVBClass
	{
		internal ushort attr;

		internal uint index;

		internal uint vbptr;

		internal byte[] vbpoff;
	}
	internal struct LeafFriendCls
	{
		internal ushort pad0;

		internal uint index;
	}
	internal struct LeafFriendFcn
	{
		internal ushort pad0;

		internal uint index;

		internal string name;
	}
	internal struct LeafMember
	{
		internal ushort attr;

		internal uint index;

		internal byte[] offset;

		internal string name;
	}
	internal struct LeafSTMember
	{
		internal ushort attr;

		internal uint index;

		internal string name;
	}
	internal struct LeafVFuncTab
	{
		internal ushort pad0;

		internal uint type;
	}
	internal struct LeafVFuncOff
	{
		internal ushort pad0;

		internal uint type;

		internal int offset;
	}
	internal struct LeafMethod
	{
		internal ushort count;

		internal uint mList;

		internal string name;
	}
	internal struct LeafOneMethod
	{
		internal ushort attr;

		internal uint index;

		internal uint[] vbaseoff;

		internal string name;
	}
	internal struct LeafEnumerate
	{
		internal ushort attr;

		internal byte[] value;

		internal string name;
	}
	internal struct LeafNestType
	{
		internal ushort pad0;

		internal uint index;

		internal string name;
	}
	internal struct LeafNestTypeEx
	{
		internal ushort attr;

		internal uint index;

		internal string name;
	}
	internal struct LeafMemberModify
	{
		internal ushort

BepInEx/core/Mono.Cecil.Rocks.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Mono.Cecil.Cil;
using Mono.Cecil.PE;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil.Rocks")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyVersion("0.10.4.0")]
namespace Mono.Cecil.Rocks;

public class DocCommentId
{
	private StringBuilder id;

	private DocCommentId()
	{
		id = new StringBuilder();
	}

	private void WriteField(FieldDefinition field)
	{
		WriteDefinition('F', (IMemberDefinition)(object)field);
	}

	private void WriteEvent(EventDefinition @event)
	{
		WriteDefinition('E', (IMemberDefinition)(object)@event);
	}

	private void WriteType(TypeDefinition type)
	{
		id.Append('T').Append(':');
		WriteTypeFullName((TypeReference)(object)type);
	}

	private void WriteMethod(MethodDefinition method)
	{
		WriteDefinition('M', (IMemberDefinition)(object)method);
		if (((MethodReference)method).HasGenericParameters)
		{
			id.Append('`').Append('`');
			id.Append(((MethodReference)method).GenericParameters.Count);
		}
		if (((MethodReference)method).HasParameters)
		{
			WriteParameters((IList<ParameterDefinition>)((MethodReference)method).Parameters);
		}
		if (IsConversionOperator(method))
		{
			WriteReturnType(method);
		}
	}

	private static bool IsConversionOperator(MethodDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (self.IsSpecialName)
		{
			if (!(((MemberReference)self).Name == "op_Explicit"))
			{
				return ((MemberReference)self).Name == "op_Implicit";
			}
			return true;
		}
		return false;
	}

	private void WriteReturnType(MethodDefinition method)
	{
		id.Append('~');
		WriteTypeSignature(((MethodReference)method).ReturnType);
	}

	private void WriteProperty(PropertyDefinition property)
	{
		WriteDefinition('P', (IMemberDefinition)(object)property);
		if (property.HasParameters)
		{
			WriteParameters((IList<ParameterDefinition>)((PropertyReference)property).Parameters);
		}
	}

	private void WriteParameters(IList<ParameterDefinition> parameters)
	{
		id.Append('(');
		WriteList(parameters, delegate(ParameterDefinition p)
		{
			WriteTypeSignature(((ParameterReference)p).ParameterType);
		});
		id.Append(')');
	}

	private void WriteTypeSignature(TypeReference type)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Expected I4, but got Unknown
		//IL_010c: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Expected O, but got Unknown
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Expected O, but got Unknown
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected I4, but got Unknown
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Expected O, but got Unknown
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Expected O, but got Unknown
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Expected O, but got Unknown
		MetadataType metadataType = type.MetadataType;
		switch (metadataType - 15)
		{
		default:
			switch (metadataType - 27)
			{
			case 0:
				WriteFunctionPointerTypeSignature((FunctionPointerType)type);
				return;
			case 3:
				id.Append('`').Append('`');
				id.Append(((GenericParameter)type).Position);
				return;
			case 5:
				WriteModiferTypeSignature((IModifierType)(OptionalModifierType)type, '!');
				return;
			case 4:
				WriteModiferTypeSignature((IModifierType)(RequiredModifierType)type, '|');
				return;
			}
			break;
		case 5:
			WriteArrayTypeSignature((ArrayType)type);
			return;
		case 1:
			WriteTypeSignature(((TypeSpecification)(ByReferenceType)type).ElementType);
			id.Append('@');
			return;
		case 6:
			WriteGenericInstanceTypeSignature((GenericInstanceType)type);
			return;
		case 4:
			id.Append('`');
			id.Append(((GenericParameter)type).Position);
			return;
		case 0:
			WriteTypeSignature(((TypeSpecification)(PointerType)type).ElementType);
			id.Append('*');
			return;
		case 2:
		case 3:
			break;
		}
		WriteTypeFullName(type);
	}

	private void WriteGenericInstanceTypeSignature(GenericInstanceType type)
	{
		if (Mixin.IsTypeSpecification(((TypeSpecification)type).ElementType))
		{
			throw new NotSupportedException();
		}
		WriteTypeFullName(((TypeSpecification)type).ElementType, stripGenericArity: true);
		id.Append('{');
		WriteList((IList<TypeReference>)type.GenericArguments, WriteTypeSignature);
		id.Append('}');
	}

	private void WriteList<T>(IList<T> list, Action<T> action)
	{
		for (int i = 0; i < list.Count; i++)
		{
			if (i > 0)
			{
				id.Append(',');
			}
			action(list[i]);
		}
	}

	private void WriteModiferTypeSignature(IModifierType type, char id)
	{
		WriteTypeSignature(type.ElementType);
		this.id.Append(id);
		WriteTypeSignature(type.ModifierType);
	}

	private void WriteFunctionPointerTypeSignature(FunctionPointerType type)
	{
		id.Append("=FUNC:");
		WriteTypeSignature(type.ReturnType);
		if (type.HasParameters)
		{
			WriteParameters((IList<ParameterDefinition>)type.Parameters);
		}
	}

	private void WriteArrayTypeSignature(ArrayType type)
	{
		WriteTypeSignature(((TypeSpecification)type).ElementType);
		if (type.IsVector)
		{
			id.Append("[]");
			return;
		}
		id.Append("[");
		WriteList((IList<ArrayDimension>)type.Dimensions, delegate(ArrayDimension dimension)
		{
			if (((ArrayDimension)(ref dimension)).LowerBound.HasValue)
			{
				id.Append(((ArrayDimension)(ref dimension)).LowerBound.Value);
			}
			id.Append(':');
			if (((ArrayDimension)(ref dimension)).UpperBound.HasValue)
			{
				id.Append(((ArrayDimension)(ref dimension)).UpperBound.Value - (((ArrayDimension)(ref dimension)).LowerBound.GetValueOrDefault() + 1));
			}
		});
		id.Append("]");
	}

	private void WriteDefinition(char id, IMemberDefinition member)
	{
		this.id.Append(id).Append(':');
		WriteTypeFullName((TypeReference)(object)member.DeclaringType);
		this.id.Append('.');
		WriteItemName(member.Name);
	}

	private void WriteTypeFullName(TypeReference type, bool stripGenericArity = false)
	{
		if (((MemberReference)type).DeclaringType != null)
		{
			WriteTypeFullName(((MemberReference)type).DeclaringType);
			id.Append('.');
		}
		if (!string.IsNullOrEmpty(type.Namespace))
		{
			id.Append(type.Namespace);
			id.Append('.');
		}
		string text = ((MemberReference)type).Name;
		if (stripGenericArity)
		{
			int num = text.LastIndexOf('`');
			if (num > 0)
			{
				text = text.Substring(0, num);
			}
		}
		id.Append(text);
	}

	private void WriteItemName(string name)
	{
		id.Append(name.Replace('.', '#').Replace('<', '{').Replace('>', '}'));
	}

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

	public static string GetDocCommentId(IMemberDefinition member)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Invalid comparison between Unknown and I4
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Invalid comparison between Unknown and I4
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Invalid comparison between Unknown and I4
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Expected O, but got Unknown
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Invalid comparison between Unknown and I4
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Expected O, but got Unknown
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Invalid comparison between Unknown and I4
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Expected O, but got Unknown
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Invalid comparison between Unknown and I4
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Expected O, but got Unknown
		if (member == null)
		{
			throw new ArgumentNullException("member");
		}
		DocCommentId docCommentId = new DocCommentId();
		MetadataToken metadataToken = ((IMetadataTokenProvider)member).MetadataToken;
		TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType;
		if ((int)tokenType <= 67108864)
		{
			if ((int)tokenType != 33554432)
			{
				if ((int)tokenType != 67108864)
				{
					goto IL_009d;
				}
				docCommentId.WriteField((FieldDefinition)member);
			}
			else
			{
				docCommentId.WriteType((TypeDefinition)member);
			}
		}
		else if ((int)tokenType != 100663296)
		{
			if ((int)tokenType != 335544320)
			{
				if ((int)tokenType != 385875968)
				{
					goto IL_009d;
				}
				docCommentId.WriteProperty((PropertyDefinition)member);
			}
			else
			{
				docCommentId.WriteEvent((EventDefinition)member);
			}
		}
		else
		{
			docCommentId.WriteMethod((MethodDefinition)member);
		}
		return docCommentId.ToString();
		IL_009d:
		throw new NotSupportedException(member.FullName);
	}
}
internal static class Functional
{
	public static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)
	{
		Func<A, R> g = null;
		g = f((A a) => g(a));
		return g;
	}

	public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource element)
	{
		if (source == null)
		{
			throw new ArgumentNullException("source");
		}
		return PrependIterator(source, element);
	}

	private static IEnumerable<TSource> PrependIterator<TSource>(IEnumerable<TSource> source, TSource element)
	{
		yield return element;
		foreach (TSource item in source)
		{
			yield return item;
		}
	}
}
public interface IILVisitor
{
	void OnInlineNone(OpCode opcode);

	void OnInlineSByte(OpCode opcode, sbyte value);

	void OnInlineByte(OpCode opcode, byte value);

	void OnInlineInt32(OpCode opcode, int value);

	void OnInlineInt64(OpCode opcode, long value);

	void OnInlineSingle(OpCode opcode, float value);

	void OnInlineDouble(OpCode opcode, double value);

	void OnInlineString(OpCode opcode, string value);

	void OnInlineBranch(OpCode opcode, int offset);

	void OnInlineSwitch(OpCode opcode, int[] offsets);

	void OnInlineVariable(OpCode opcode, VariableDefinition variable);

	void OnInlineArgument(OpCode opcode, ParameterDefinition parameter);

	void OnInlineSignature(OpCode opcode, CallSite callSite);

	void OnInlineType(OpCode opcode, TypeReference type);

	void OnInlineField(OpCode opcode, FieldReference field);

	void OnInlineMethod(OpCode opcode, MethodReference method);
}
public static class ILParser
{
	private class ParseContext
	{
		public CodeReader Code { get; set; }

		public int Position { get; set; }

		public MetadataReader Metadata { get; set; }

		public Collection<VariableDefinition> Variables { get; set; }

		public IILVisitor Visitor { get; set; }
	}

	public static void Parse(MethodDefinition method, IILVisitor visitor)
	{
		if (method == null)
		{
			throw new ArgumentNullException("method");
		}
		if (visitor == null)
		{
			throw new ArgumentNullException("visitor");
		}
		if (!method.HasBody || !((MemberReference)method).HasImage)
		{
			throw new ArgumentException();
		}
		((MemberReference)method).Module.Read<MethodDefinition, bool>(method, (Func<MethodDefinition, MetadataReader, bool>)delegate(MethodDefinition m, MetadataReader _)
		{
			ParseMethod(m, visitor);
			return true;
		});
	}

	private static void ParseMethod(MethodDefinition method, IILVisitor visitor)
	{
		ParseContext parseContext = CreateContext(method, visitor);
		CodeReader code = parseContext.Code;
		byte b = ((BinaryReader)(object)code).ReadByte();
		switch (b & 3)
		{
		case 2:
			ParseCode(b >> 2, parseContext);
			break;
		case 3:
			((BinaryStreamReader)code).Advance(-1);
			ParseFatMethod(parseContext);
			break;
		default:
			throw new NotSupportedException();
		}
		code.MoveBackTo(parseContext.Position);
	}

	private static ParseContext CreateContext(MethodDefinition method, IILVisitor visitor)
	{
		CodeReader val = ((MemberReference)method).Module.Read<MethodDefinition, CodeReader>(method, (Func<MethodDefinition, MetadataReader, CodeReader>)((MethodDefinition _, MetadataReader reader) => reader.code));
		int position = val.MoveTo(method);
		return new ParseContext
		{
			Code = val,
			Position = position,
			Metadata = val.reader,
			Visitor = visitor
		};
	}

	private static void ParseFatMethod(ParseContext context)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		CodeReader code = context.Code;
		((BinaryStreamReader)code).Advance(4);
		int code_size = ((BinaryReader)(object)code).ReadInt32();
		MetadataToken val = code.ReadToken();
		if (val != MetadataToken.Zero)
		{
			context.Variables = (Collection<VariableDefinition>)(object)code.ReadVariables(val);
		}
		ParseCode(code_size, context);
	}

	private static void ParseCode(int code_size, ParseContext context)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: 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_00b4: Expected I4, but got Unknown
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_0240: Unknown result type (might be due to invalid IL or missing references)
		//IL_024e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0253: Unknown result type (might be due to invalid IL or missing references)
		//IL_0257: Unknown result type (might be due to invalid IL or missing references)
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_025e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0265: Invalid comparison between Unknown and I4
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0226: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0183: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01db: Unknown result type (might be due to invalid IL or missing references)
		//IL_0287: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Invalid comparison between Unknown and I4
		//IL_0267: Unknown result type (might be due to invalid IL or missing references)
		//IL_026e: Invalid comparison between Unknown and I4
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ab: Invalid comparison between Unknown and I4
		//IL_0290: Unknown result type (might be due to invalid IL or missing references)
		//IL_0297: Invalid comparison between Unknown and I4
		//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c7: Expected O, but got Unknown
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_0277: Invalid comparison between Unknown and I4
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b4: Invalid comparison between Unknown and I4
		//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d8: Expected O, but got Unknown
		//IL_0299: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a0: Invalid comparison between Unknown and I4
		//IL_0279: Unknown result type (might be due to invalid IL or missing references)
		//IL_0280: Invalid comparison between Unknown and I4
		//IL_02db: Unknown result type (might be due to invalid IL or missing references)
		//IL_02df: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e9: Expected O, but got Unknown
		//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0312: Unknown result type (might be due to invalid IL or missing references)
		CodeReader code = context.Code;
		MetadataReader metadata = context.Metadata;
		IILVisitor visitor = context.Visitor;
		int num = ((BinaryStreamReader)code).Position + code_size;
		while (((BinaryStreamReader)code).Position < num)
		{
			byte b = ((BinaryReader)(object)code).ReadByte();
			OpCode val = ((b != 254) ? OpCodes.OneByteOpCode[b] : OpCodes.TwoBytesOpCode[((BinaryReader)(object)code).ReadByte()]);
			OperandType operandType = ((OpCode)(ref val)).OperandType;
			IMetadataTokenProvider val2;
			switch ((int)operandType)
			{
			case 5:
				visitor.OnInlineNone(val);
				break;
			case 10:
			{
				int num2 = ((BinaryReader)(object)code).ReadInt32();
				int[] array = new int[num2];
				for (int i = 0; i < num2; i++)
				{
					array[i] = ((BinaryReader)(object)code).ReadInt32();
				}
				visitor.OnInlineSwitch(val, array);
				break;
			}
			case 15:
				visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadSByte());
				break;
			case 0:
				visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadInt32());
				break;
			case 16:
				if (val == OpCodes.Ldc_I4_S)
				{
					visitor.OnInlineSByte(val, ((BinaryReader)(object)code).ReadSByte());
				}
				else
				{
					visitor.OnInlineByte(val, ((BinaryReader)(object)code).ReadByte());
				}
				break;
			case 2:
				visitor.OnInlineInt32(val, ((BinaryReader)(object)code).ReadInt32());
				break;
			case 3:
				visitor.OnInlineInt64(val, ((BinaryReader)(object)code).ReadInt64());
				break;
			case 17:
				visitor.OnInlineSingle(val, ((BinaryReader)(object)code).ReadSingle());
				break;
			case 7:
				visitor.OnInlineDouble(val, ((BinaryReader)(object)code).ReadDouble());
				break;
			case 8:
				visitor.OnInlineSignature(val, code.GetCallSite(code.ReadToken()));
				break;
			case 9:
				visitor.OnInlineString(val, code.GetString(code.ReadToken()));
				break;
			case 19:
				visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadByte()));
				break;
			case 14:
				visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadInt16()));
				break;
			case 18:
				visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadByte()));
				break;
			case 13:
				visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadInt16()));
				break;
			case 1:
			case 4:
			case 11:
			case 12:
				{
					val2 = metadata.LookupToken(code.ReadToken());
					MetadataToken metadataToken = val2.MetadataToken;
					TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType;
					if ((int)tokenType <= 67108864)
					{
						if ((int)tokenType != 16777216 && (int)tokenType != 33554432)
						{
							if ((int)tokenType == 67108864)
							{
								visitor.OnInlineField(val, (FieldReference)val2);
							}
							break;
						}
						goto IL_02b8;
					}
					if ((int)tokenType <= 167772160)
					{
						if ((int)tokenType != 100663296)
						{
							if ((int)tokenType != 167772160)
							{
								break;
							}
							FieldReference val3 = (FieldReference)(object)((val2 is FieldReference) ? val2 : null);
							if (val3 != null)
							{
								visitor.OnInlineField(val, val3);
								break;
							}
							MethodReference val4 = (MethodReference)(object)((val2 is MethodReference) ? val2 : null);
							if (val4 != null)
							{
								visitor.OnInlineMethod(val, val4);
								break;
							}
							throw new InvalidOperationException();
						}
					}
					else
					{
						if ((int)tokenType == 452984832)
						{
							goto IL_02b8;
						}
						if ((int)tokenType != 721420288)
						{
							break;
						}
					}
					visitor.OnInlineMethod(val, (MethodReference)val2);
					break;
				}
				IL_02b8:
				visitor.OnInlineType(val, (TypeReference)val2);
				break;
			}
		}
	}

	private static VariableDefinition GetVariable(ParseContext context, int index)
	{
		return context.Variables[index];
	}
}
public static class MethodBodyRocks
{
	public static void SimplifyMacros(this MethodBody self)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Invalid comparison between Unknown and I4
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Expected I4, but got Unknown
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0203: Unknown result type (might be due to invalid IL or missing references)
		//IL_021f: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0257: Unknown result type (might be due to invalid IL or missing references)
		//IL_0273: Unknown result type (might be due to invalid IL or missing references)
		//IL_0283: Unknown result type (might be due to invalid IL or missing references)
		//IL_0293: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0315: Unknown result type (might be due to invalid IL or missing references)
		//IL_032b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0341: Unknown result type (might be due to invalid IL or missing references)
		//IL_0357: Unknown result type (might be due to invalid IL or missing references)
		//IL_036d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0383: Unknown result type (might be due to invalid IL or missing references)
		//IL_0399: Unknown result type (might be due to invalid IL or missing references)
		//IL_03af: Unknown result type (might be due to invalid IL or missing references)
		//IL_03cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_03df: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_040f: Unknown result type (might be due to invalid IL or missing references)
		//IL_041c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0429: Unknown result type (might be due to invalid IL or missing references)
		//IL_0436: Unknown result type (might be due to invalid IL or missing references)
		//IL_0443: Unknown result type (might be due to invalid IL or missing references)
		//IL_0450: Unknown result type (might be due to invalid IL or missing references)
		//IL_045d: Unknown result type (might be due to invalid IL or missing references)
		//IL_046a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0477: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Invalid comparison between Unknown and I4
		//IL_0484: Unknown result type (might be due to invalid IL or missing references)
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				OpCode opCode = current.OpCode;
				if ((int)((OpCode)(ref opCode)).OpCodeType != 1)
				{
					continue;
				}
				opCode = current.OpCode;
				Code code = ((OpCode)(ref opCode)).Code;
				switch (code - 2)
				{
				case 0:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 0));
					continue;
				case 1:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 1));
					continue;
				case 2:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 2));
					continue;
				case 3:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 3));
					continue;
				case 4:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[0]);
					continue;
				case 5:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[1]);
					continue;
				case 6:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[2]);
					continue;
				case 7:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[3]);
					continue;
				case 8:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[0]);
					continue;
				case 9:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[1]);
					continue;
				case 10:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[2]);
					continue;
				case 11:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[3]);
					continue;
				case 12:
					current.OpCode = OpCodes.Ldarg;
					continue;
				case 13:
					current.OpCode = OpCodes.Ldarga;
					continue;
				case 14:
					current.OpCode = OpCodes.Starg;
					continue;
				case 15:
					current.OpCode = OpCodes.Ldloc;
					continue;
				case 16:
					current.OpCode = OpCodes.Ldloca;
					continue;
				case 17:
					current.OpCode = OpCodes.Stloc;
					continue;
				case 19:
					ExpandMacro(current, OpCodes.Ldc_I4, -1);
					continue;
				case 20:
					ExpandMacro(current, OpCodes.Ldc_I4, 0);
					continue;
				case 21:
					ExpandMacro(current, OpCodes.Ldc_I4, 1);
					continue;
				case 22:
					ExpandMacro(current, OpCodes.Ldc_I4, 2);
					continue;
				case 23:
					ExpandMacro(current, OpCodes.Ldc_I4, 3);
					continue;
				case 24:
					ExpandMacro(current, OpCodes.Ldc_I4, 4);
					continue;
				case 25:
					ExpandMacro(current, OpCodes.Ldc_I4, 5);
					continue;
				case 26:
					ExpandMacro(current, OpCodes.Ldc_I4, 6);
					continue;
				case 27:
					ExpandMacro(current, OpCodes.Ldc_I4, 7);
					continue;
				case 28:
					ExpandMacro(current, OpCodes.Ldc_I4, 8);
					continue;
				case 29:
					ExpandMacro(current, OpCodes.Ldc_I4, (int)(sbyte)current.Operand);
					continue;
				case 40:
					current.OpCode = OpCodes.Br;
					continue;
				case 41:
					current.OpCode = OpCodes.Brfalse;
					continue;
				case 42:
					current.OpCode = OpCodes.Brtrue;
					continue;
				case 43:
					current.OpCode = OpCodes.Beq;
					continue;
				case 44:
					current.OpCode = OpCodes.Bge;
					continue;
				case 45:
					current.OpCode = OpCodes.Bgt;
					continue;
				case 46:
					current.OpCode = OpCodes.Ble;
					continue;
				case 47:
					current.OpCode = OpCodes.Blt;
					continue;
				case 48:
					current.OpCode = OpCodes.Bne_Un;
					continue;
				case 49:
					current.OpCode = OpCodes.Bge_Un;
					continue;
				case 50:
					current.OpCode = OpCodes.Bgt_Un;
					continue;
				case 51:
					current.OpCode = OpCodes.Ble_Un;
					continue;
				case 52:
					current.OpCode = OpCodes.Blt_Un;
					continue;
				case 18:
				case 30:
				case 31:
				case 32:
				case 33:
				case 34:
				case 35:
				case 36:
				case 37:
				case 38:
				case 39:
					continue;
				}
				if ((int)code == 188)
				{
					current.OpCode = OpCodes.Leave;
				}
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static void ExpandMacro(Instruction instruction, OpCode opcode, object operand)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		instruction.OpCode = opcode;
		instruction.Operand = operand;
	}

	private static void MakeMacro(Instruction instruction, OpCode opcode)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		instruction.OpCode = opcode;
		instruction.Operand = null;
	}

	public static void Optimize(this MethodBody self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		self.OptimizeLongs();
		self.OptimizeMacros();
	}

	private static void OptimizeLongs(this MethodBody self)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Invalid comparison between Unknown and I4
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < self.Instructions.Count; i++)
		{
			Instruction val = self.Instructions[i];
			OpCode opCode = val.OpCode;
			if ((int)((OpCode)(ref opCode)).Code == 33)
			{
				long num = (long)val.Operand;
				if (num < int.MaxValue && num > int.MinValue)
				{
					ExpandMacro(val, OpCodes.Ldc_I4, (int)num);
					self.Instructions.Insert(++i, Instruction.Create(OpCodes.Conv_I8));
				}
			}
		}
	}

	public static void OptimizeMacros(this MethodBody self)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Invalid comparison between Unknown and I4
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Expected I4, but got Unknown
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_030a: Unknown result type (might be due to invalid IL or missing references)
		//IL_031a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0327: Unknown result type (might be due to invalid IL or missing references)
		//IL_0334: Unknown result type (might be due to invalid IL or missing references)
		//IL_0341: Unknown result type (might be due to invalid IL or missing references)
		//IL_034e: Unknown result type (might be due to invalid IL or missing references)
		//IL_035b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0368: Unknown result type (might be due to invalid IL or missing references)
		//IL_0375: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_0168: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0202: Unknown result type (might be due to invalid IL or missing references)
		//IL_0391: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_0271: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_021d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		MethodDefinition method = self.Method;
		Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				OpCode opCode = current.OpCode;
				Code code = ((OpCode)(ref opCode)).Code;
				if ((int)code != 32)
				{
					switch (code - 199)
					{
					case 0:
					{
						int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index;
						if (index == -1 && current.Operand == self.ThisParameter)
						{
							index = 0;
						}
						else if (((MethodReference)method).HasThis)
						{
							index++;
						}
						switch (index)
						{
						case 0:
							MakeMacro(current, OpCodes.Ldarg_0);
							break;
						case 1:
							MakeMacro(current, OpCodes.Ldarg_1);
							break;
						case 2:
							MakeMacro(current, OpCodes.Ldarg_2);
							break;
						case 3:
							MakeMacro(current, OpCodes.Ldarg_3);
							break;
						default:
							if (index < 256)
							{
								ExpandMacro(current, OpCodes.Ldarg_S, current.Operand);
							}
							break;
						}
						break;
					}
					case 3:
					{
						int index = ((VariableReference)(VariableDefinition)current.Operand).Index;
						switch (index)
						{
						case 0:
							MakeMacro(current, OpCodes.Ldloc_0);
							break;
						case 1:
							MakeMacro(current, OpCodes.Ldloc_1);
							break;
						case 2:
							MakeMacro(current, OpCodes.Ldloc_2);
							break;
						case 3:
							MakeMacro(current, OpCodes.Ldloc_3);
							break;
						default:
							if (index < 256)
							{
								ExpandMacro(current, OpCodes.Ldloc_S, current.Operand);
							}
							break;
						}
						break;
					}
					case 5:
					{
						int index = ((VariableReference)(VariableDefinition)current.Operand).Index;
						switch (index)
						{
						case 0:
							MakeMacro(current, OpCodes.Stloc_0);
							break;
						case 1:
							MakeMacro(current, OpCodes.Stloc_1);
							break;
						case 2:
							MakeMacro(current, OpCodes.Stloc_2);
							break;
						case 3:
							MakeMacro(current, OpCodes.Stloc_3);
							break;
						default:
							if (index < 256)
							{
								ExpandMacro(current, OpCodes.Stloc_S, current.Operand);
							}
							break;
						}
						break;
					}
					case 1:
					{
						int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index;
						if (index == -1 && current.Operand == self.ThisParameter)
						{
							index = 0;
						}
						else if (((MethodReference)method).HasThis)
						{
							index++;
						}
						if (index < 256)
						{
							ExpandMacro(current, OpCodes.Ldarga_S, current.Operand);
						}
						break;
					}
					case 4:
						if (((VariableReference)(VariableDefinition)current.Operand).Index < 256)
						{
							ExpandMacro(current, OpCodes.Ldloca_S, current.Operand);
						}
						break;
					}
					continue;
				}
				int num = (int)current.Operand;
				switch (num)
				{
				case -1:
					MakeMacro(current, OpCodes.Ldc_I4_M1);
					continue;
				case 0:
					MakeMacro(current, OpCodes.Ldc_I4_0);
					continue;
				case 1:
					MakeMacro(current, OpCodes.Ldc_I4_1);
					continue;
				case 2:
					MakeMacro(current, OpCodes.Ldc_I4_2);
					continue;
				case 3:
					MakeMacro(current, OpCodes.Ldc_I4_3);
					continue;
				case 4:
					MakeMacro(current, OpCodes.Ldc_I4_4);
					continue;
				case 5:
					MakeMacro(current, OpCodes.Ldc_I4_5);
					continue;
				case 6:
					MakeMacro(current, OpCodes.Ldc_I4_6);
					continue;
				case 7:
					MakeMacro(current, OpCodes.Ldc_I4_7);
					continue;
				case 8:
					MakeMacro(current, OpCodes.Ldc_I4_8);
					continue;
				}
				if (num >= -128 && num < 128)
				{
					ExpandMacro(current, OpCodes.Ldc_I4_S, (sbyte)num);
				}
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
		OptimizeBranches(self);
	}

	private static void OptimizeBranches(MethodBody body)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		ComputeOffsets(body);
		Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				OpCode opCode = current.OpCode;
				if ((int)((OpCode)(ref opCode)).OperandType == 0 && OptimizeBranch(current))
				{
					ComputeOffsets(body);
				}
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static bool OptimizeBranch(Instruction instruction)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Expected I4, but got Unknown
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Invalid comparison between Unknown and I4
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		int offset = ((Instruction)instruction.Operand).Offset;
		int offset2 = instruction.Offset;
		OpCode opCode = instruction.OpCode;
		int num = offset - (offset2 + ((OpCode)(ref opCode)).Size + 4);
		if (num < -128 || num > 127)
		{
			return false;
		}
		opCode = instruction.OpCode;
		Code code = ((OpCode)(ref opCode)).Code;
		switch (code - 55)
		{
		default:
			if ((int)code == 187)
			{
				instruction.OpCode = OpCodes.Leave_S;
			}
			break;
		case 0:
			instruction.OpCode = OpCodes.Br_S;
			break;
		case 1:
			instruction.OpCode = OpCodes.Brfalse_S;
			break;
		case 2:
			instruction.OpCode = OpCodes.Brtrue_S;
			break;
		case 3:
			instruction.OpCode = OpCodes.Beq_S;
			break;
		case 4:
			instruction.OpCode = OpCodes.Bge_S;
			break;
		case 5:
			instruction.OpCode = OpCodes.Bgt_S;
			break;
		case 6:
			instruction.OpCode = OpCodes.Ble_S;
			break;
		case 7:
			instruction.OpCode = OpCodes.Blt_S;
			break;
		case 8:
			instruction.OpCode = OpCodes.Bne_Un_S;
			break;
		case 9:
			instruction.OpCode = OpCodes.Bge_Un_S;
			break;
		case 10:
			instruction.OpCode = OpCodes.Bgt_Un_S;
			break;
		case 11:
			instruction.OpCode = OpCodes.Ble_Un_S;
			break;
		case 12:
			instruction.OpCode = OpCodes.Blt_Un_S;
			break;
		}
		return true;
	}

	private static void ComputeOffsets(MethodBody body)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		int num = 0;
		Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				current.Offset = num;
				num += current.GetSize();
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}
}
public static class MethodDefinitionRocks
{
	public static MethodDefinition GetBaseMethod(this MethodDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.IsVirtual)
		{
			return self;
		}
		if (self.IsNewSlot)
		{
			return self;
		}
		for (TypeDefinition val = ResolveBaseType(self.DeclaringType); val != null; val = ResolveBaseType(val))
		{
			MethodDefinition matchingMethod = GetMatchingMethod(val, self);
			if (matchingMethod != null)
			{
				return matchingMethod;
			}
		}
		return self;
	}

	public static MethodDefinition GetOriginalBaseMethod(this MethodDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		while (true)
		{
			MethodDefinition baseMethod = self.GetBaseMethod();
			if (baseMethod == self)
			{
				break;
			}
			self = baseMethod;
		}
		return self;
	}

	private static TypeDefinition ResolveBaseType(TypeDefinition type)
	{
		if (type == null)
		{
			return null;
		}
		TypeReference baseType = type.BaseType;
		if (baseType == null)
		{
			return null;
		}
		return baseType.Resolve();
	}

	private static MethodDefinition GetMatchingMethod(TypeDefinition type, MethodDefinition method)
	{
		return MetadataResolver.GetMethod(type.Methods, (MethodReference)(object)method);
	}
}
public static class ModuleDefinitionRocks
{
	public static IEnumerable<TypeDefinition> GetAllTypes(this ModuleDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		return ((IEnumerable<TypeDefinition>)self.Types).SelectMany(Functional.Y((Func<TypeDefinition, IEnumerable<TypeDefinition>> f) => (TypeDefinition type) => ((IEnumerable<TypeDefinition>)type.NestedTypes).SelectMany(f).Prepend(type)));
	}
}
public static class ParameterReferenceRocks
{
	public static int GetSequence(this ParameterReference self)
	{
		return self.Index + 1;
	}
}
public static class SecurityDeclarationRocks
{
	public static PermissionSet ToPermissionSet(this SecurityDeclaration self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (TryProcessPermissionSetAttribute(self, out var set))
		{
			return set;
		}
		return CreatePermissionSet(self);
	}

	private static bool TryProcessPermissionSetAttribute(SecurityDeclaration declaration, out PermissionSet set)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Expected I4, but got Unknown
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected O, but got Unknown
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_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)
		set = null;
		if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1)
		{
			return false;
		}
		SecurityAttribute val = declaration.SecurityAttributes[0];
		if (!Mixin.IsTypeOf(val.AttributeType, "System.Security.Permissions", "PermissionSetAttribute"))
		{
			return false;
		}
		PermissionSetAttribute val2 = new PermissionSetAttribute((SecurityAction)declaration.Action);
		CustomAttributeNamedArgument val3 = val.Properties[0];
		CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref val3)).Argument;
		string text = (string)((CustomAttributeArgument)(ref argument)).Value;
		string name = ((CustomAttributeNamedArgument)(ref val3)).Name;
		if (!(name == "XML"))
		{
			if (!(name == "Name"))
			{
				throw new NotImplementedException(((CustomAttributeNamedArgument)(ref val3)).Name);
			}
			val2.Name = text;
		}
		else
		{
			val2.XML = text;
		}
		set = val2.CreatePermissionSet();
		return true;
	}

	private static PermissionSet CreatePermissionSet(SecurityDeclaration declaration)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		PermissionSet permissionSet = new PermissionSet(PermissionState.None);
		Enumerator<SecurityAttribute> enumerator = declaration.SecurityAttributes.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				SecurityAttribute current = enumerator.Current;
				IPermission perm = CreatePermission(declaration, current);
				permissionSet.AddPermission(perm);
			}
			return permissionSet;
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static IPermission CreatePermission(SecurityDeclaration declaration, SecurityAttribute attribute)
	{
		SecurityAttribute obj = CreateSecurityAttribute(Type.GetType(((MemberReference)attribute.AttributeType).FullName) ?? throw new ArgumentException("attribute"), declaration) ?? throw new InvalidOperationException();
		CompleteSecurityAttribute(obj, attribute);
		return obj.CreatePermission();
	}

	private static void CompleteSecurityAttribute(SecurityAttribute security_attribute, SecurityAttribute attribute)
	{
		if (attribute.HasFields)
		{
			CompleteSecurityAttributeFields(security_attribute, attribute);
		}
		if (attribute.HasProperties)
		{
			CompleteSecurityAttributeProperties(security_attribute, attribute);
		}
	}

	private static void CompleteSecurityAttributeFields(SecurityAttribute security_attribute, SecurityAttribute attribute)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		Type type = security_attribute.GetType();
		Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Fields.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				CustomAttributeNamedArgument current = enumerator.Current;
				FieldInfo? field = type.GetField(((CustomAttributeNamedArgument)(ref current)).Name);
				CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument;
				field.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value);
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static void CompleteSecurityAttributeProperties(SecurityAttribute security_attribute, SecurityAttribute attribute)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		Type type = security_attribute.GetType();
		Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Properties.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				CustomAttributeNamedArgument current = enumerator.Current;
				PropertyInfo? property = type.GetProperty(((CustomAttributeNamedArgument)(ref current)).Name);
				CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument;
				property.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value, null);
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static SecurityAttribute CreateSecurityAttribute(Type attribute_type, SecurityDeclaration declaration)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Expected I4, but got Unknown
		try
		{
			return (SecurityAttribute)Activator.CreateInstance(attribute_type, (SecurityAction)declaration.Action);
		}
		catch (MissingMethodException)
		{
			return (SecurityAttribute)Activator.CreateInstance(attribute_type, new object[0]);
		}
	}

	public static SecurityDeclaration ToSecurityDeclaration(this PermissionSet self, SecurityAction action, ModuleDefinition module)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Expected O, but got Unknown
		//IL_005e: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Expected O, but got Unknown
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (module == null)
		{
			throw new ArgumentNullException("module");
		}
		SecurityDeclaration val = new SecurityDeclaration(action);
		SecurityAttribute val2 = new SecurityAttribute(module.TypeSystem.LookupType("System.Security.Permissions", "PermissionSetAttribute"));
		val2.Properties.Add(new CustomAttributeNamedArgument("XML", new CustomAttributeArgument(module.TypeSystem.String, (object)self.ToXml().ToString())));
		val.SecurityAttributes.Add(val2);
		return val;
	}
}
public static class TypeDefinitionRocks
{
	public static IEnumerable<MethodDefinition> GetConstructors(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.HasMethods)
		{
			return Empty<MethodDefinition>.Array;
		}
		return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => method.IsConstructor);
	}

	public static MethodDefinition GetStaticConstructor(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.HasMethods)
		{
			return null;
		}
		return self.GetConstructors().FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition ctor) => ctor.IsStatic));
	}

	public static IEnumerable<MethodDefinition> GetMethods(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.HasMethods)
		{
			return Empty<MethodDefinition>.Array;
		}
		return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => !method.IsConstructor);
	}

	public static TypeReference GetEnumUnderlyingType(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.IsEnum)
		{
			throw new ArgumentException();
		}
		return Mixin.GetEnumUnderlyingType(self);
	}
}
public static class TypeReferenceRocks
{
	public static ArrayType MakeArrayType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new ArrayType(self);
	}

	public static ArrayType MakeArrayType(this TypeReference self, int rank)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Expected O, but got Unknown
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		if (rank == 0)
		{
			throw new ArgumentOutOfRangeException("rank");
		}
		ArrayType val = new ArrayType(self);
		for (int i = 1; i < rank; i++)
		{
			val.Dimensions.Add(default(ArrayDimension));
		}
		return val;
	}

	public static PointerType MakePointerType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new PointerType(self);
	}

	public static ByReferenceType MakeByReferenceType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new ByReferenceType(self);
	}

	public static OptionalModifierType MakeOptionalModifierType(this TypeReference self, TypeReference modifierType)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		return new OptionalModifierType(modifierType, self);
	}

	public static RequiredModifierType MakeRequiredModifierType(this TypeReference self, TypeReference modifierType)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		return new RequiredModifierType(modifierType, self);
	}

	public static GenericInstanceType MakeGenericInstanceType(this TypeReference self, params TypeReference[] arguments)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (arguments == null)
		{
			throw new ArgumentNullException("arguments");
		}
		if (arguments.Length == 0)
		{
			throw new ArgumentException();
		}
		if (self.GenericParameters.Count != arguments.Length)
		{
			throw new ArgumentException();
		}
		GenericInstanceType val = new GenericInstanceType(self);
		foreach (TypeReference val2 in arguments)
		{
			val.GenericArguments.Add(val2);
		}
		return val;
	}

	public static PinnedType MakePinnedType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new PinnedType(self);
	}

	public static SentinelType MakeSentinelType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new SentinelType(self);
	}
}

BepInEx/core/MonoMod.RuntimeDetour.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using MonoMod.RuntimeDetour.Platforms;
using MonoMod.Utils;
using MonoMod.Utils.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2022 0x0ade")]
[assembly: AssemblyDescription("Flexible and easily extensible runtime detouring library. Wrap, replace and manipulate (Mono.Cecil) methods at runtime.")]
[assembly: AssemblyFileVersion("22.1.29.1")]
[assembly: AssemblyInformationalVersion("22.01.29.01")]
[assembly: AssemblyProduct("MonoMod.RuntimeDetour")]
[assembly: AssemblyTitle("MonoMod.RuntimeDetour")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("22.1.29.1")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
}
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison)
	{
		return self.Replace(oldValue, newValue);
	}

	public static bool Contains(this string self, string value, StringComparison comparison)
	{
		return self.Contains(value);
	}

	public static int GetHashCode(this string self, StringComparison comparison)
	{
		return self.GetHashCode();
	}

	public static int IndexOf(this string self, char value, StringComparison comparison)
	{
		return self.IndexOf(value);
	}

	public static int IndexOf(this string self, string value, StringComparison comparison)
	{
		return self.IndexOf(value);
	}

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	internal static class MMDbgLog
	{
		public static readonly string Tag;

		public static TextWriter Writer;

		public static bool Debugging;

		static MMDbgLog()
		{
			Tag = typeof(MMDbgLog).Assembly.GetName().Name;
			if (!(Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1"))
			{
				string? environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG");
				bool? obj;
				if (environmentVariable == null)
				{
					obj = null;
				}
				else
				{
					string text = environmentVariable.ToLower(CultureInfo.InvariantCulture);
					obj = ((text != null) ? new bool?(MultiTargetShims.Contains(text, Tag.ToLower(CultureInfo.InvariantCulture), StringComparison.Ordinal)) : null);
				}
				bool? flag = obj;
				if (!flag.GetValueOrDefault())
				{
					return;
				}
			}
			Start();
		}

		public static void WaitForDebugger()
		{
			if (!Debugging)
			{
				Debugging = true;
				Debugger.Launch();
				Thread.Sleep(6000);
				Debugger.Break();
			}
		}

		public static void Start()
		{
			if (Writer != null)
			{
				return;
			}
			string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH");
			if (text == "-")
			{
				Writer = Console.Out;
				return;
			}
			if (string.IsNullOrEmpty(text))
			{
				text = "mmdbglog.txt";
			}
			text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text));
			try
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
			catch
			{
			}
			try
			{
				string directoryName = Path.GetDirectoryName(text);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8);
			}
			catch
			{
			}
		}

		public static void Log(string str)
		{
			TextWriter writer = Writer;
			if (writer != null)
			{
				writer.WriteLine(str);
				writer.Flush();
			}
		}

		public static T Log<T>(string str, T value)
		{
			TextWriter writer = Writer;
			if (writer == null)
			{
				return value;
			}
			writer.WriteLine(string.Format(CultureInfo.InvariantCulture, str, new object[1] { value }));
			writer.Flush();
			return value;
		}
	}
}
namespace MonoMod.RuntimeDetour
{
	public struct DetourConfig
	{
		public bool ManualApply;

		public int Priority;

		public string ID;

		public IEnumerable<string> Before;

		public IEnumerable<string> After;
	}
	public class Detour : ISortableDetour, IDetour, IDisposable
	{
		private static Dictionary<MethodBase, List<Detour>> _DetourMap = new Dictionary<MethodBase, List<Detour>>((IEqualityComparer<MethodBase>?)new GenericMethodInstantiationComparer());

		private static Dictionary<MethodBase, MethodInfo> _BackupMethods = new Dictionary<MethodBase, MethodInfo>();

		private static uint _GlobalIndexNext = 0u;

		public static Func<Detour, MethodBase, MethodBase, bool> OnDetour;

		public static Func<Detour, bool> OnUndo;

		public static Func<Detour, MethodBase, MethodBase> OnGenerateTrampoline;

		private readonly uint _GlobalIndex;

		private int _Priority;

		private string _ID;

		private List<string> _Before = new List<string>();

		private ReadOnlyCollection<string> _BeforeRO;

		private List<string> _After = new List<string>();

		private ReadOnlyCollection<string> _AfterRO;

		public readonly MethodBase Method;

		public readonly MethodBase Target;

		public readonly MethodBase TargetReal;

		private NativeDetour _TopDetour;

		private MethodInfo _ChainedTrampoline;

		private static int compileMethodSubscribed = 0;

		private List<Detour> _DetourChain
		{
			get
			{
				if (!_DetourMap.TryGetValue(Method, out var value))
				{
					return null;
				}
				return value;
			}
		}

		public bool IsValid => Index != -1;

		public bool IsApplied { get; private set; }

		private bool IsTop => _TopDetour != null;

		public int Index => _DetourChain?.IndexOf(this) ?? (-1);

		public int MaxIndex => _DetourChain?.Count ?? (-1);

		public uint GlobalIndex => _GlobalIndex;

		public int Priority
		{
			get
			{
				return _Priority;
			}
			set
			{
				if (_Priority != value)
				{
					_Priority = value;
					_RefreshChain(Method);
				}
			}
		}

		public string ID
		{
			get
			{
				return _ID;
			}
			set
			{
				if (string.IsNullOrEmpty(value))
				{
					value = Extensions.GetID(Target, (string)null, (string)null, true, false, true);
				}
				if (!(_ID == value))
				{
					_ID = value;
					_RefreshChain(Method);
				}
			}
		}

		public IEnumerable<string> Before
		{
			get
			{
				return _BeforeRO ?? (_BeforeRO = _Before.AsReadOnly());
			}
			set
			{
				lock (_Before)
				{
					_Before.Clear();
					if (value != null)
					{
						foreach (string item in value)
						{
							_Before.Add(item);
						}
					}
					_RefreshChain(Method);
				}
			}
		}

		public IEnumerable<string> After
		{
			get
			{
				return _AfterRO ?? (_AfterRO = _After.AsReadOnly());
			}
			set
			{
				lock (_After)
				{
					_After.Clear();
					if (value != null)
					{
						foreach (string item in value)
						{
							_After.Add(item);
						}
					}
					_RefreshChain(Method);
				}
			}
		}

		public Detour(MethodBase from, MethodBase to, ref DetourConfig config)
		{
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Expected O, but got Unknown
			from = from.GetIdentifiable();
			if (from.Equals(to))
			{
				throw new ArgumentException("Cannot detour a method to itself!");
			}
			MMDbgLog.Log("detour from " + Extensions.GetID(from, (string)null, (string)null, true, false, false) + " to " + Extensions.GetID(to, (string)null, (string)null, true, false, false));
			Method = from;
			Target = to.Pin();
			TargetReal = DetourHelper.Runtime.GetDetourTarget(from, to);
			_GlobalIndex = _GlobalIndexNext++;
			_Priority = config.Priority;
			_ID = config.ID;
			if (config.Before != null)
			{
				foreach (string item in config.Before)
				{
					_Before.Add(item);
				}
			}
			if (config.After != null)
			{
				foreach (string item2 in config.After)
				{
					_After.Add(item2);
				}
			}
			lock (_BackupMethods)
			{
				if ((!_BackupMethods.TryGetValue(Method, out var value) || (object)value == null) && (object)(value = Method.CreateILCopy()) != null)
				{
					_BackupMethods[Method] = value.Pin();
				}
			}
			ParameterInfo[] parameters = Method.GetParameters();
			Type[] array;
			if (!Method.IsStatic)
			{
				array = new Type[parameters.Length + 1];
				array[0] = Extensions.GetThisParamType(Method);
				for (int i = 0; i < parameters.Length; i++)
				{
					array[i + 1] = parameters[i].ParameterType;
				}
			}
			else
			{
				array = new Type[parameters.Length];
				for (int j = 0; j < parameters.Length; j++)
				{
					array[j] = parameters[j].ParameterType;
				}
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition($"Chain<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", (Method as MethodInfo)?.ReturnType ?? typeof(void), array);
			try
			{
				_ChainedTrampoline = val.StubCriticalDetour().Generate().Pin();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			List<Detour> value2;
			lock (_DetourMap)
			{
				if (!_DetourMap.TryGetValue(Method, out value2))
				{
					value2 = (_DetourMap[Method] = new List<Detour>());
				}
			}
			lock (value2)
			{
				value2.Add(this);
			}
			if (!config.ManualApply)
			{
				Apply();
			}
		}

		public Detour(MethodBase from, MethodBase to, DetourConfig config)
			: this(from, to, ref config)
		{
		}

		public Detour(MethodBase from, MethodBase to)
			: this(from, to, DetourContext.Current?.DetourConfig ?? default(DetourConfig))
		{
		}

		public Detour(MethodBase method, IntPtr to, ref DetourConfig config)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), ref config)
		{
		}

		public Detour(MethodBase method, IntPtr to, DetourConfig config)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), ref config)
		{
		}

		public Detour(MethodBase method, IntPtr to)
			: this(method, DetourHelper.GenerateNativeProxy(to, method))
		{
		}

		public Detour(Delegate from, IntPtr to, ref DetourConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Detour(Delegate from, IntPtr to, DetourConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Detour(Delegate from, IntPtr to)
			: this(from.Method, to)
		{
		}

		public Detour(Delegate from, Delegate to, ref DetourConfig config)
			: this(from.Method, to.Method, ref config)
		{
		}

		public Detour(Delegate from, Delegate to, DetourConfig config)
			: this(from.Method, to.Method, ref config)
		{
		}

		public Detour(Delegate from, Delegate to)
			: this(from.Method, to.Method)
		{
		}

		public Detour(Expression from, IntPtr to, ref DetourConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Detour(Expression from, IntPtr to, DetourConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Detour(Expression from, IntPtr to)
			: this(((MethodCallExpression)from).Method, to)
		{
		}

		public Detour(Expression from, Expression to, ref DetourConfig config)
			: this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method, ref config)
		{
		}

		public Detour(Expression from, Expression to, DetourConfig config)
			: this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method, ref config)
		{
		}

		public Detour(Expression from, Expression to)
			: this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method)
		{
		}

		public Detour(Expression<Action> from, IntPtr to, ref DetourConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Detour(Expression<Action> from, IntPtr to, DetourConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Detour(Expression<Action> from, IntPtr to)
			: this(from.Body, to)
		{
		}

		public Detour(Expression<Action> from, Expression<Action> to, ref DetourConfig config)
			: this(from.Body, to.Body, ref config)
		{
		}

		public Detour(Expression<Action> from, Expression<Action> to, DetourConfig config)
			: this(from.Body, to.Body, ref config)
		{
		}

		public Detour(Expression<Action> from, Expression<Action> to)
			: this(from.Body, to.Body)
		{
		}

		public void Apply()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("Detour");
			}
			if (!IsApplied)
			{
				Func<Detour, MethodBase, MethodBase, bool> onDetour = OnDetour;
				if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[3] { this, Method, Target }))
				{
					IsApplied = true;
					_RefreshChain(Method);
				}
			}
		}

		public void Undo()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("Detour");
			}
			if (IsApplied)
			{
				Func<Detour, bool> onUndo = OnUndo;
				if (onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this }))
				{
					IsApplied = false;
					_RefreshChain(Method);
				}
			}
		}

		public void Free()
		{
			if (!IsValid)
			{
				return;
			}
			Undo();
			List<Detour> detourChain = _DetourChain;
			lock (detourChain)
			{
				detourChain.Remove(this);
				if (detourChain.Count == 0)
				{
					lock (_BackupMethods)
					{
						if (_BackupMethods.TryGetValue(Method, out var value))
						{
							value.Unpin();
							_BackupMethods.Remove(Method);
						}
					}
					lock (_DetourMap)
					{
						_DetourMap.Remove(Method);
					}
				}
			}
			_ChainedTrampoline.Unpin();
			Target.Unpin();
		}

		public void Dispose()
		{
			if (IsValid)
			{
				Undo();
				Free();
			}
		}

		public MethodBase GenerateTrampoline(MethodBase signature = null)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			Func<Detour, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline;
			MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null);
			if ((object)methodBase != null)
			{
				return methodBase;
			}
			if ((object)signature == null)
			{
				signature = Target;
			}
			Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void);
			ParameterInfo[] parameters = signature.GetParameters();
			Type[] array = new Type[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				array[i] = parameters[i].ParameterType;
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition($"Trampoline<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", type, array);
			try
			{
				ILProcessor iLProcessor = val.GetILProcessor();
				for (int j = 0; j < 32; j++)
				{
					iLProcessor.Emit(OpCodes.Nop);
				}
				for (int k = 0; k < array.Length; k++)
				{
					iLProcessor.Emit(OpCodes.Ldarg, k);
				}
				Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)_ChainedTrampoline);
				iLProcessor.Emit(OpCodes.Ret);
				return val.Generate();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		public T GenerateTrampoline<T>() where T : Delegate
		{
			if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
			{
				throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
			}
			return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T;
		}

		private void _TopUndo()
		{
			if (_TopDetour != null)
			{
				_TopDetour.Undo();
				_TopDetour.Free();
				_TopDetour = null;
				Method.Unpin();
				TargetReal.Unpin();
			}
		}

		private void _TopApply()
		{
			if (_TopDetour == null)
			{
				_TopDetour = new NativeDetour(Method.Pin().GetNativeStart(), TargetReal.Pin().GetNativeStart());
			}
		}

		private static void _OnCompileMethod(MethodBase method, IntPtr codeStart, ulong codeLen)
		{
			if ((object)method == null)
			{
				return;
			}
			MMDbgLog.Log("compiling: " + Extensions.GetID(method, (string)null, (string)null, true, false, false));
			if (_DetourMap.TryGetValue(method, out var value))
			{
				value.FindLast((Detour d) => d.IsTop)?._TopDetour?.ChangeSource(codeStart);
			}
		}

		private static void _RefreshChain(MethodBase method)
		{
			if (Interlocked.CompareExchange(ref compileMethodSubscribed, 1, 0) == 0)
			{
				DetourHelper.Runtime.OnMethodCompiled += _OnCompileMethod;
			}
			MMDbgLog.Log("detours applying for " + Extensions.GetID(method, (string)null, (string)null, true, false, false));
			List<Detour> list = _DetourMap[method];
			lock (list)
			{
				DetourSorter<Detour>.Sort(list);
				Detour detour = list.FindLast((Detour d) => d.IsTop);
				Detour detour2 = list.FindLast((Detour d) => d.IsApplied);
				if (detour != detour2)
				{
					detour?._TopUndo();
				}
				if (list.Count == 0)
				{
					return;
				}
				MethodBase method2 = _BackupMethods[method];
				foreach (Detour item in list)
				{
					if (item.IsApplied)
					{
						_ = item._ChainedTrampoline;
						using (NativeDetour nativeDetour = new NativeDetour(item._ChainedTrampoline.GetNativeStart(), method2.GetNativeStart()))
						{
							nativeDetour.Free();
						}
						method2 = item.Target;
					}
				}
				if (detour != detour2)
				{
					detour2?._TopApply();
				}
			}
		}
	}
	public class Detour<T> : Detour where T : Delegate
	{
		public Detour(T from, IntPtr to, ref DetourConfig config)
			: base(from, to, ref config)
		{
		}

		public Detour(T from, IntPtr to, DetourConfig config)
			: base(from, to, ref config)
		{
		}

		public Detour(T from, IntPtr to)
			: base(from, to)
		{
		}

		public Detour(T from, T to, ref DetourConfig config)
			: base(from, to, ref config)
		{
		}

		public Detour(T from, T to, DetourConfig config)
			: base(from, to, ref config)
		{
		}

		public Detour(T from, T to)
			: base(from, to)
		{
		}
	}
	public sealed class DetourContext : IDisposable
	{
		[ThreadStatic]
		private static List<DetourContext> _Contexts;

		[ThreadStatic]
		private static DetourContext Last;

		private MethodBase Creator;

		public int Priority;

		private readonly string _FallbackID;

		private string _ID;

		public List<string> Before = new List<string>();

		public List<string> After = new List<string>();

		private bool IsDisposed;

		private static List<DetourContext> Contexts => _Contexts ?? (_Contexts = new List<DetourContext>());

		internal static DetourContext Current
		{
			get
			{
				DetourContext last = Last;
				if (last != null && last.IsValid)
				{
					return Last;
				}
				List<DetourContext> contexts = Contexts;
				int num = contexts.Count - 1;
				while (num > -1)
				{
					DetourContext detourContext = contexts[num];
					if (!detourContext.IsValid)
					{
						contexts.RemoveAt(num);
						num--;
						continue;
					}
					return Last = detourContext;
				}
				return null;
			}
		}

		public string ID
		{
			get
			{
				return _ID ?? _FallbackID;
			}
			set
			{
				_ID = (string.IsNullOrEmpty(value) ? null : value);
			}
		}

		public DetourConfig DetourConfig
		{
			get
			{
				DetourConfig result = default(DetourConfig);
				result.Priority = Priority;
				result.ID = ID;
				result.Before = Before;
				result.After = After;
				return result;
			}
		}

		public HookConfig HookConfig
		{
			get
			{
				HookConfig result = default(HookConfig);
				result.Priority = Priority;
				result.ID = ID;
				result.Before = Before;
				result.After = After;
				return result;
			}
		}

		public ILHookConfig ILHookConfig
		{
			get
			{
				ILHookConfig result = default(ILHookConfig);
				result.Priority = Priority;
				result.ID = ID;
				result.Before = Before;
				result.After = After;
				return result;
			}
		}

		internal bool IsValid
		{
			get
			{
				if (IsDisposed)
				{
					return false;
				}
				if ((object)Creator == null)
				{
					return true;
				}
				StackTrace stackTrace = new StackTrace();
				int frameCount = stackTrace.FrameCount;
				for (int i = 0; i < frameCount; i++)
				{
					if ((object)stackTrace.GetFrame(i).GetMethod() == Creator)
					{
						return true;
					}
				}
				return false;
			}
		}

		public DetourContext(int priority, string id)
		{
			StackTrace stackTrace = new StackTrace();
			int frameCount = stackTrace.FrameCount;
			for (int i = 0; i < frameCount; i++)
			{
				MethodBase method = stackTrace.GetFrame(i).GetMethod();
				if ((object)method?.DeclaringType != typeof(DetourContext))
				{
					Creator = method;
					break;
				}
			}
			object obj = Creator?.DeclaringType?.Assembly?.GetName().Name;
			if (obj == null)
			{
				MethodBase creator = Creator;
				obj = (((object)creator != null) ? Extensions.GetID(creator, (string)null, (string)null, true, false, true) : null);
			}
			_FallbackID = (string)obj;
			Last = this;
			Contexts.Add(this);
			Priority = priority;
			ID = id;
		}

		public DetourContext(string id)
			: this(0, id)
		{
		}

		public DetourContext(int priority)
			: this(priority, null)
		{
		}

		public DetourContext()
			: this(0, null)
		{
		}

		public void Dispose()
		{
			if (IsDisposed)
			{
				IsDisposed = true;
				Last = null;
				Contexts.Remove(this);
			}
		}
	}
	public sealed class DetourModManager : IDisposable
	{
		private readonly Dictionary<IDetour, Assembly> DetourOwners = new Dictionary<IDetour, Assembly>();

		private readonly Dictionary<Assembly, List<IDetour>> OwnedDetourLists = new Dictionary<Assembly, List<IDetour>>();

		public HashSet<Assembly> Ignored = new HashSet<Assembly>();

		private bool Disposed;

		private static readonly string[] HookTypeNames = new string[4] { "MonoMod.RuntimeDetour.NativeDetour", "MonoMod.RuntimeDetour.Detour", "MonoMod.RuntimeDetour.Hook", "MonoMod.RuntimeDetour.ILHook" };

		public event Action<Assembly, MethodBase, Manipulator> OnILHook;

		public event Action<Assembly, MethodBase, MethodBase, object> OnHook;

		public event Action<Assembly, MethodBase, MethodBase> OnDetour;

		public event Action<Assembly, MethodBase, IntPtr, IntPtr> OnNativeDetour;

		public DetourModManager()
		{
			Ignored.Add(typeof(DetourModManager).Assembly);
			ILHook.OnDetour = (Func<ILHook, MethodBase, Manipulator, bool>)Delegate.Combine(ILHook.OnDetour, new Func<ILHook, MethodBase, Manipulator, bool>(RegisterILHook));
			ILHook.OnUndo = (Func<ILHook, bool>)Delegate.Combine(ILHook.OnUndo, new Func<ILHook, bool>(UnregisterDetour));
			Hook.OnDetour = (Func<Hook, MethodBase, MethodBase, object, bool>)Delegate.Combine(Hook.OnDetour, new Func<Hook, MethodBase, MethodBase, object, bool>(RegisterHook));
			Hook.OnUndo = (Func<Hook, bool>)Delegate.Combine(Hook.OnUndo, new Func<Hook, bool>(UnregisterDetour));
			Detour.OnDetour = (Func<Detour, MethodBase, MethodBase, bool>)Delegate.Combine(Detour.OnDetour, new Func<Detour, MethodBase, MethodBase, bool>(RegisterDetour));
			Detour.OnUndo = (Func<Detour, bool>)Delegate.Combine(Detour.OnUndo, new Func<Detour, bool>(UnregisterDetour));
			NativeDetour.OnDetour = (Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>)Delegate.Combine(NativeDetour.OnDetour, new Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>(RegisterNativeDetour));
			NativeDetour.OnUndo = (Func<NativeDetour, bool>)Delegate.Combine(NativeDetour.OnUndo, new Func<NativeDetour, bool>(UnregisterDetour));
		}

		public void Dispose()
		{
			if (!Disposed)
			{
				Disposed = true;
				OwnedDetourLists.Clear();
				ILHook.OnDetour = (Func<ILHook, MethodBase, Manipulator, bool>)Delegate.Remove(ILHook.OnDetour, new Func<ILHook, MethodBase, Manipulator, bool>(RegisterILHook));
				ILHook.OnUndo = (Func<ILHook, bool>)Delegate.Remove(ILHook.OnUndo, new Func<ILHook, bool>(UnregisterDetour));
				Hook.OnDetour = (Func<Hook, MethodBase, MethodBase, object, bool>)Delegate.Remove(Hook.OnDetour, new Func<Hook, MethodBase, MethodBase, object, bool>(RegisterHook));
				Hook.OnUndo = (Func<Hook, bool>)Delegate.Remove(Hook.OnUndo, new Func<Hook, bool>(UnregisterDetour));
				Detour.OnDetour = (Func<Detour, MethodBase, MethodBase, bool>)Delegate.Remove(Detour.OnDetour, new Func<Detour, MethodBase, MethodBase, bool>(RegisterDetour));
				Detour.OnUndo = (Func<Detour, bool>)Delegate.Remove(Detour.OnUndo, new Func<Detour, bool>(UnregisterDetour));
				NativeDetour.OnDetour = (Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>)Delegate.Remove(NativeDetour.OnDetour, new Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>(RegisterNativeDetour));
				NativeDetour.OnUndo = (Func<NativeDetour, bool>)Delegate.Remove(NativeDetour.OnUndo, new Func<NativeDetour, bool>(UnregisterDetour));
			}
		}

		public void Unload(Assembly asm)
		{
			if ((object)asm == null || Ignored.Contains(asm))
			{
				return;
			}
			HookEndpointManager.RemoveAllOwnedBy(asm);
			if (OwnedDetourLists.TryGetValue(asm, out var value))
			{
				IDetour[] array = value.ToArray();
				for (int i = 0; i < array.Length; i++)
				{
					array[i].Dispose();
				}
				if (value.Count > 0)
				{
					throw new Exception("Some detours failed to unregister in " + asm.FullName);
				}
				OwnedDetourLists.Remove(asm);
			}
		}

		internal Assembly GetHookOwner(StackTrace stack = null)
		{
			if (stack == null)
			{
				stack = new StackTrace();
			}
			Assembly assembly = null;
			int frameCount = stack.FrameCount;
			string text = null;
			for (int i = 0; i < frameCount; i++)
			{
				MethodBase method = stack.GetFrame(i).GetMethod();
				if ((object)method?.DeclaringType == null)
				{
					continue;
				}
				string fullName = method.DeclaringType.FullName;
				if (text == null)
				{
					if (HookTypeNames.Contains(fullName))
					{
						text = method.DeclaringType.FullName;
					}
				}
				else if (!(fullName == text))
				{
					assembly = method?.DeclaringType.Assembly;
					break;
				}
			}
			if (Ignored.Contains(assembly))
			{
				return null;
			}
			return assembly;
		}

		internal void TrackDetour(Assembly owner, IDetour detour)
		{
			if (!OwnedDetourLists.TryGetValue(owner, out var value))
			{
				value = (OwnedDetourLists[owner] = new List<IDetour>());
			}
			value.Add(detour);
			DetourOwners[detour] = owner;
		}

		internal bool RegisterILHook(ILHook _detour, MethodBase from, Manipulator manipulator)
		{
			Assembly hookOwner = GetHookOwner();
			if ((object)hookOwner == null)
			{
				return true;
			}
			this.OnILHook?.Invoke(hookOwner, from, manipulator);
			TrackDetour(hookOwner, _detour);
			return true;
		}

		internal bool RegisterHook(Hook _detour, MethodBase from, MethodBase to, object target)
		{
			Assembly hookOwner = GetHookOwner();
			if ((object)hookOwner == null)
			{
				return true;
			}
			this.OnHook?.Invoke(hookOwner, from, to, target);
			TrackDetour(hookOwner, _detour);
			return true;
		}

		internal bool RegisterDetour(Detour _detour, MethodBase from, MethodBase to)
		{
			Assembly hookOwner = GetHookOwner();
			if ((object)hookOwner == null)
			{
				return true;
			}
			this.OnDetour?.Invoke(hookOwner, from, to);
			TrackDetour(hookOwner, _detour);
			return true;
		}

		internal bool RegisterNativeDetour(NativeDetour _detour, MethodBase method, IntPtr from, IntPtr to)
		{
			Assembly hookOwner = GetHookOwner();
			if ((object)hookOwner == null)
			{
				return true;
			}
			this.OnNativeDetour?.Invoke(hookOwner, method, from, to);
			TrackDetour(hookOwner, _detour);
			return true;
		}

		internal bool UnregisterDetour(IDetour _detour)
		{
			if (DetourOwners.TryGetValue(_detour, out var value))
			{
				DetourOwners.Remove(_detour);
				OwnedDetourLists[value].Remove(_detour);
			}
			return true;
		}
	}
	public static class HarmonyDetourBridge
	{
		public enum Type
		{
			Auto,
			Basic,
			AsOriginal,
			Override
		}

		private class DetourToRDAttribute : Attribute
		{
			public string Type { get; }

			public int SkipParams { get; }

			public string Name { get; }

			public DetourToRDAttribute(string type, int skipParams = 0, string name = null)
			{
				Type = type;
				SkipParams = skipParams;
				Name = name;
			}
		}

		private class DetourToHAttribute : Attribute
		{
			public string Type { get; }

			public int SkipParams { get; }

			public string Name { get; }

			public DetourToHAttribute(string type, int skipParams = 0, string name = null)
			{
				Type = type;
				SkipParams = skipParams;
				Name = name;
			}
		}

		private class TranspileAttribute : Attribute
		{
			public string Type { get; }

			public string Name { get; }

			public TranspileAttribute(string type, string name = null)
			{
				Type = type;
				Name = name;
			}
		}

		private class CriticalAttribute : Attribute
		{
		}

		private static Type CurrentType;

		private static Assembly _HarmonyASM;

		private static readonly HashSet<IDisposable> _Detours;

		private static readonly Dictionary<System.Type, MethodInfo> _Emitters;

		[ThreadStatic]
		private static DynamicMethodDefinition _LastWrapperDMD;

		private static Assembly _SharedStateASM;

		private static DetourConfig _DetourConfig;

		public static bool Initialized { get; private set; }

		static HarmonyDetourBridge()
		{
			_Detours = new HashSet<IDisposable>();
			_Emitters = new Dictionary<System.Type, MethodInfo>();
			System.Type typeFromHandle = typeof(OpCode);
			System.Type proxyType = ILGeneratorShim.GetProxyType<CecilILGenerator>();
			MethodInfo[] methods = proxyType.GetMethods();
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.Name != "Emit")
				{
					continue;
				}
				ParameterInfo[] parameters = methodInfo.GetParameters();
				if (parameters.Length == 2 && (object)parameters[0].ParameterType == typeFromHandle)
				{
					System.Type parameterType = parameters[1].ParameterType;
					if (!_Emitters.ContainsKey(parameterType) || (object)methodInfo.DeclaringType == proxyType)
					{
						_Emitters[parameterType] = methodInfo;
					}
				}
			}
		}

		public static bool Init(bool forceLoad = true, Type type = Type.Auto)
		{
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Expected O, but got Unknown
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Expected O, but got Unknown
			if ((object)_HarmonyASM == null)
			{
				_HarmonyASM = _FindHarmony();
			}
			if ((object)_HarmonyASM == null && forceLoad)
			{
				_HarmonyASM = Assembly.Load(new AssemblyName
				{
					Name = "0Harmony"
				});
			}
			if ((object)_HarmonyASM == null)
			{
				return false;
			}
			if (Initialized)
			{
				return true;
			}
			Initialized = true;
			if (type == Type.Auto)
			{
				type = Type.AsOriginal;
			}
			DetourConfig detourConfig = default(DetourConfig);
			detourConfig.Priority = type switch
			{
				Type.Override => 536870911, 
				Type.AsOriginal => -536870912, 
				_ => 0, 
			};
			_DetourConfig = detourConfig;
			CurrentType = type;
			try
			{
				MethodInfo[] methods = typeof(HarmonyDetourBridge).GetMethods(BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					bool flag = methodInfo.GetCustomAttributes(typeof(CriticalAttribute), inherit: false).Any();
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(DetourToRDAttribute), inherit: false);
					for (int j = 0; j < customAttributes.Length; j++)
					{
						DetourToRDAttribute detourToRDAttribute = (DetourToRDAttribute)customAttributes[j];
						foreach (MethodInfo item in GetHarmonyMethod(methodInfo, detourToRDAttribute.Type, detourToRDAttribute.SkipParams, detourToRDAttribute.Name))
						{
							flag = false;
							_Detours.Add(new Hook(item, methodInfo));
						}
					}
					customAttributes = methodInfo.GetCustomAttributes(typeof(DetourToHAttribute), inherit: false);
					for (int j = 0; j < customAttributes.Length; j++)
					{
						DetourToHAttribute detourToHAttribute = (DetourToHAttribute)customAttributes[j];
						foreach (MethodInfo item2 in GetHarmonyMethod(methodInfo, detourToHAttribute.Type, detourToHAttribute.SkipParams, detourToHAttribute.Name))
						{
							flag = false;
							_Detours.Add(new Detour(methodInfo, item2));
						}
					}
					customAttributes = methodInfo.GetCustomAttributes(typeof(TranspileAttribute), inherit: false);
					for (int j = 0; j < customAttributes.Length; j++)
					{
						TranspileAttribute transpileAttribute = (TranspileAttribute)customAttributes[j];
						foreach (MethodInfo item3 in GetHarmonyMethod(methodInfo, transpileAttribute.Type, -1, transpileAttribute.Name))
						{
							DynamicMethodDefinition val = new DynamicMethodDefinition((MethodBase)item3);
							try
							{
								flag = false;
								ILContext val2 = new ILContext(val.Definition)
								{
									ReferenceBag = (IILReferenceBag)(object)RuntimeILReferenceBag.Instance
								};
								_Detours.Add((IDisposable)val2);
								val2.Invoke(Extensions.CreateDelegate<Manipulator>((MethodBase)methodInfo));
								if (val2.IsReadOnly)
								{
									val2.Dispose();
									_Detours.Remove((IDisposable)val2);
								}
								else
								{
									_Detours.Add(new Detour(item3, val.Generate()));
								}
							}
							finally
							{
								((IDisposable)val)?.Dispose();
							}
						}
					}
					if (flag)
					{
						throw new Exception("Cannot apply HarmonyDetourBridge rule " + methodInfo.Name);
					}
				}
			}
			catch
			{
				_EarlyReset();
				throw;
			}
			return true;
		}

		private static bool _EarlyReset()
		{
			foreach (IDisposable detour in _Detours)
			{
				detour.Dispose();
			}
			_Detours.Clear();
			return false;
		}

		public static void Reset()
		{
			if (Initialized)
			{
				Initialized = false;
				_EarlyReset();
			}
		}

		private static System.Type GetHarmonyType(string typeName)
		{
			return _HarmonyASM.GetType(typeName) ?? _HarmonyASM.GetType("HarmonyLib." + typeName) ?? _HarmonyASM.GetType("Harmony." + typeName) ?? _HarmonyASM.GetType("Harmony.ILCopying." + typeName);
		}

		private static IEnumerable<MethodInfo> GetHarmonyMethod(MethodInfo ctx, string typeName, int skipParams, string name)
		{
			System.Type harmonyType = GetHarmonyType(typeName);
			if ((object)harmonyType == null)
			{
				return null;
			}
			if (string.IsNullOrEmpty(name))
			{
				name = ctx.Name;
			}
			if (skipParams < 0)
			{
				return from method in harmonyType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
					where method.Name == name
					select method;
			}
			return new MethodInfo[1] { harmonyType.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, (from p in ctx.GetParameters().Skip(skipParams)
				select p.ParameterType).ToArray(), null) };
		}

		private static DynamicMethodDefinition CreateDMD(MethodBase original, string suffix)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			if ((object)original == null)
			{
				throw new ArgumentNullException("original");
			}
			ParameterInfo[] parameters = original.GetParameters();
			System.Type[] array;
			if (!original.IsStatic)
			{
				array = new System.Type[parameters.Length + 1];
				array[0] = Extensions.GetThisParamType(original);
				for (int i = 0; i < parameters.Length; i++)
				{
					array[i + 1] = parameters[i].ParameterType;
				}
			}
			else
			{
				array = new System.Type[parameters.Length];
				for (int j = 0; j < parameters.Length; j++)
				{
					array[j] = parameters[j].ParameterType;
				}
			}
			return new DynamicMethodDefinition(MultiTargetShims.Replace(original.Name + suffix, "<>", "", StringComparison.Ordinal), (original as MethodInfo)?.ReturnType ?? typeof(void), array);
		}

		[DetourToRD("Memory", 0, null)]
		private static long GetMethodStart(MethodBase method, out Exception exception)
		{
			exception = null;
			try
			{
				_Detours.Add((IDisposable)new LazyDisposable<MethodBase>(method, (Action<MethodBase>)delegate(MethodBase m)
				{
					m.Unpin();
				}));
				return (long)method.Pin().GetNativeStart();
			}
			catch (Exception ex)
			{
				exception = ex;
				return 0L;
			}
		}

		[DetourToRD("Memory", 0, null)]
		[Critical]
		private static string WriteJump(long memory, long destination)
		{
			_Detours.Add(new NativeDetour((IntPtr)memory, (IntPtr)destination));
			return null;
		}

		[DetourToRD("Memory", 0, null)]
		[Critical]
		private static string DetourMethod(MethodBase original, MethodBase replacement)
		{
			if ((object)replacement == null)
			{
				replacement = _LastWrapperDMD.Generate();
				_LastWrapperDMD.Dispose();
				_LastWrapperDMD = null;
			}
			_Detours.Add(new Detour(original, replacement, ref _DetourConfig));
			return null;
		}

		[DetourToRD("MethodBodyReader", 1, null)]
		private static MethodInfo EmitMethodForType(object self, System.Type type)
		{
			foreach (KeyValuePair<System.Type, MethodInfo> emitter in _Emitters)
			{
				if ((object)emitter.Key == type)
				{
					return emitter.Value;
				}
			}
			foreach (KeyValuePair<System.Type, MethodInfo> emitter2 in _Emitters)
			{
				if (emitter2.Key.IsAssignableFrom(type))
				{
					return emitter2.Value;
				}
			}
			return null;
		}

		[DetourToRD("PatchProcessor", 2, null)]
		[Critical]
		private static List<DynamicMethod> Patch(Func<object, List<DynamicMethod>> orig, object self)
		{
			orig(self);
			return new List<DynamicMethod>();
		}

		[Transpile("PatchFunctions", null)]
		[Critical]
		private static void UpdateWrapper(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchThrow(i)
			});
			val.Next.OpCode = OpCodes.Pop;
		}

		[Transpile("MethodPatcher", null)]
		[Critical]
		private static void CreatePatchedMethod(ILContext il)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			System.Type t_DynamicTools = GetHarmonyType("DynamicTools");
			if (!val.TryGotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchCall(i, t_DynamicTools, "CreateDynamicMethod")
			}))
			{
				il.MakeReadOnly();
				return;
			}
			val.Next.OpCode = OpCodes.Call;
			val.Next.Operand = il.Import((MethodBase)typeof(HarmonyDetourBridge).GetMethod("CreateDMD", BindingFlags.Static | BindingFlags.NonPublic));
			int varDMDi = -1;
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchStloc(i, ref varDMDi)
			});
			((VariableReference)il.Body.Variables[varDMDi]).VariableType = il.Import(typeof(DynamicMethodDefinition));
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchCallvirt<DynamicMethod>(i, "GetILGenerator")
			});
			val.Next.OpCode = OpCodes.Call;
			val.Next.Operand = il.Import((MethodBase)typeof(DynamicMethodDefinition).GetMethod("GetILGenerator", BindingFlags.Instance | BindingFlags.Public));
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchCall(i, t_DynamicTools, "PrepareDynamicMethod")
			});
			val.Next.OpCode = OpCodes.Pop;
			val.Next.Operand = null;
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction i) => ILPatternMatchingExt.MatchLdloc(i, varDMDi)
			});
			int index = val.Index;
			val.Index = index + 1;
			val.EmitDelegate<Func<DynamicMethodDefinition, DynamicMethod>>((Func<DynamicMethodDefinition, DynamicMethod>)delegate(DynamicMethodDefinition dmd)
			{
				_LastWrapperDMD = dmd;
				return null;
			});
		}

		[DetourToRD("HarmonySharedState", 1, null)]
		private static Assembly SharedStateAssembly(Func<Assembly> orig)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_006e: 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_0085: Expected O, but got Unknown
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			Assembly assembly = orig();
			if ((object)assembly != null)
			{
				return assembly;
			}
			if ((object)_SharedStateASM != null)
			{
				return _SharedStateASM;
			}
			string text = (string)GetHarmonyType("HarmonySharedState").GetField("name", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
			ModuleDefinition val = ModuleDefinition.CreateModule("MonoMod.RuntimeDetour." + text, new ModuleParameters
			{
				Kind = (ModuleKind)0,
				ReflectionImporterProvider = MMReflectionImporter.Provider
			});
			try
			{
				TypeDefinition val2 = new TypeDefinition("", text, (TypeAttributes)385)
				{
					BaseType = val.TypeSystem.Object
				};
				val.Types.Add(val2);
				val2.Fields.Add(new FieldDefinition("state", (FieldAttributes)22, val.ImportReference(typeof(Dictionary<MethodBase, byte[]>))));
				val2.Fields.Add(new FieldDefinition("version", (FieldAttributes)22, val.ImportReference(typeof(int))));
				return _SharedStateASM = ReflectionHelper.Load(val);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		private static Assembly _FindHarmony()
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (assembly.GetName().Name == "0Harmony" || assembly.GetName().Name == "Harmony" || (object)assembly.GetType("Harmony.HarmonyInstance") != null || (object)assembly.GetType("HarmonyLib.Harmony") != null)
				{
					return assembly;
				}
			}
			object obj = System.Type.GetType("Harmony.HarmonyInstance", throwOnError: false, ignoreCase: false)?.Assembly;
			if (obj == null)
			{
				System.Type? type = System.Type.GetType("HarmonyLib.Harmony", throwOnError: false, ignoreCase: false);
				if ((object)type == null)
				{
					return null;
				}
				obj = type.Assembly;
			}
			return (Assembly)obj;
		}
	}
	public struct HookConfig
	{
		public bool ManualApply;

		public int Priority;

		public string ID;

		public IEnumerable<string> Before;

		public IEnumerable<string> After;
	}
	public class Hook : IDetour, IDisposable
	{
		public static Func<Hook, MethodBase, MethodBase, object, bool> OnDetour;

		public static Func<Hook, bool> OnUndo;

		public static Func<Hook, MethodBase, MethodBase> OnGenerateTrampoline;

		public readonly MethodBase Method;

		public readonly MethodBase Target;

		public readonly MethodBase TargetReal;

		public readonly object DelegateTarget;

		private Detour _Detour;

		private readonly Type _OrigDelegateType;

		private readonly MethodInfo _OrigDelegateInvoke;

		private int? _RefTarget;

		private int? _RefTrampoline;

		private int? _RefTrampolineTmp;

		public bool IsValid => _Detour.IsValid;

		public bool IsApplied => _Detour.IsApplied;

		public Detour Detour => _Detour;

		public Hook(MethodBase from, MethodInfo to, object target, ref HookConfig config)
		{
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Expected O, but got Unknown
			//IL_025b: Expected O, but got Unknown
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_0377: Expected O, but got Unknown
			//IL_0379: Expected O, but got Unknown
			//IL_0397: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f6: Unknown result type (might be due to invalid IL or missing references)
			from = from.GetIdentifiable();
			Method = from;
			Target = to;
			DelegateTarget = target;
			Type type = (from as MethodInfo)?.ReturnType ?? typeof(void);
			if ((object)to.ReturnType != type && !Extensions.IsCompatible(to.ReturnType, type))
			{
				throw new InvalidOperationException($"Return type of hook for {from} doesn't match, must be {((from as MethodInfo)?.ReturnType ?? typeof(void)).FullName}");
			}
			if (target == null && !to.IsStatic)
			{
				throw new InvalidOperationException($"Hook for method {from} must be static, or you must pass a target instance.");
			}
			ParameterInfo[] parameters = Target.GetParameters();
			ParameterInfo[] parameters2 = Method.GetParameters();
			Type[] array;
			if (!Method.IsStatic)
			{
				array = new Type[parameters2.Length + 1];
				array[0] = Extensions.GetThisParamType(Method);
				for (int i = 0; i < parameters2.Length; i++)
				{
					array[i + 1] = parameters2[i].ParameterType;
				}
			}
			else
			{
				array = new Type[parameters2.Length];
				for (int j = 0; j < parameters2.Length; j++)
				{
					array[j] = parameters2[j].ParameterType;
				}
			}
			Type type2 = null;
			if (parameters.Length == array.Length + 1 && typeof(Delegate).IsAssignableFrom(parameters[0].ParameterType))
			{
				type2 = (_OrigDelegateType = parameters[0].ParameterType);
			}
			else if (parameters.Length != array.Length)
			{
				throw new InvalidOperationException($"Parameter count of hook for {from} doesn't match, must be {array.Length}");
			}
			for (int k = 0; k < array.Length; k++)
			{
				Type type3 = array[k];
				Type parameterType = parameters[k + (((object)type2 != null) ? 1 : 0)].ParameterType;
				if (!Extensions.IsCompatible(type3, parameterType))
				{
					throw new InvalidOperationException($"Parameter #{k} of hook for {from} doesn't match, must be {type3.FullName} or related");
				}
			}
			MethodInfo methodInfo = (_OrigDelegateInvoke = type2?.GetMethod("Invoke"));
			DynamicMethodDefinition val = new DynamicMethodDefinition($"Hook<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", (Method as MethodInfo)?.ReturnType ?? typeof(void), array);
			DynamicMethodDefinition val2 = val;
			DynamicMethodDefinition val3 = val;
			try
			{
				ILProcessor iLProcessor = val2.GetILProcessor();
				if (target != null)
				{
					_RefTarget = DynamicMethodHelper.EmitReference<object>(iLProcessor, target);
				}
				if ((object)type2 != null)
				{
					_RefTrampoline = DynamicMethodHelper.EmitReference<Delegate>(iLProcessor, (Delegate)null);
				}
				for (int l = 0; l < array.Length; l++)
				{
					iLProcessor.Emit(OpCodes.Ldarg, l);
				}
				Extensions.Emit(iLProcessor, OpCodes.Call, Target);
				iLProcessor.Emit(OpCodes.Ret);
				TargetReal = val2.Generate().Pin();
			}
			finally
			{
				((IDisposable)val3)?.Dispose();
			}
			if ((object)type2 != null)
			{
				ParameterInfo[] parameters3 = methodInfo.GetParameters();
				Type[] array2 = new Type[parameters3.Length];
				for (int m = 0; m < parameters3.Length; m++)
				{
					array2[m] = parameters3[m].ParameterType;
				}
				DynamicMethodDefinition val4 = new DynamicMethodDefinition($"Chain:TMP<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", methodInfo?.ReturnType ?? typeof(void), array2);
				val2 = val4;
				val3 = val4;
				try
				{
					ILProcessor iLProcessor = val2.GetILProcessor();
					_RefTrampolineTmp = DynamicMethodHelper.EmitReference<Delegate>(iLProcessor, (Delegate)null);
					iLProcessor.Emit(OpCodes.Brfalse, iLProcessor.Body.Instructions[0]);
					DynamicMethodHelper.EmitGetReference<Delegate>(iLProcessor, _RefTrampolineTmp.Value);
					for (int n = 0; n < array.Length; n++)
					{
						iLProcessor.Emit(OpCodes.Ldarg, n);
					}
					Extensions.Emit(iLProcessor, OpCodes.Callvirt, (MethodBase)methodInfo);
					iLProcessor.Emit(OpCodes.Ret);
					DynamicMethodHelper.SetReference(_RefTrampoline.Value, (object)Extensions.CreateDelegate((MethodBase)val2.Generate(), type2));
				}
				finally
				{
					((IDisposable)val3)?.Dispose();
				}
			}
			_Detour = new Detour(Method, TargetReal, new DetourConfig
			{
				ManualApply = true,
				Priority = config.Priority,
				ID = config.ID,
				Before = config.Before,
				After = config.After
			});
			_UpdateOrig(null);
			if (!config.ManualApply)
			{
				Apply();
			}
		}

		public Hook(MethodBase from, MethodInfo to, object target, HookConfig config)
			: this(from, to, target, ref config)
		{
		}

		public Hook(MethodBase from, MethodInfo to, object target)
			: this(from, to, target, DetourContext.Current?.HookConfig ?? default(HookConfig))
		{
		}

		public Hook(MethodBase from, MethodInfo to, ref HookConfig config)
			: this(from, to, null, ref config)
		{
		}

		public Hook(MethodBase from, MethodInfo to, HookConfig config)
			: this(from, to, null, ref config)
		{
		}

		public Hook(MethodBase from, MethodInfo to)
			: this(from, to, null)
		{
		}

		public Hook(MethodBase method, IntPtr to, ref HookConfig config)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), null, ref config)
		{
		}

		public Hook(MethodBase method, IntPtr to, HookConfig config)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), null, ref config)
		{
		}

		public Hook(MethodBase method, IntPtr to)
			: this(method, DetourHelper.GenerateNativeProxy(to, method), null)
		{
		}

		public Hook(MethodBase method, Delegate to, ref HookConfig config)
			: this(method, to.Method, to.Target, ref config)
		{
		}

		public Hook(MethodBase method, Delegate to, HookConfig config)
			: this(method, to.Method, to.Target, ref config)
		{
		}

		public Hook(MethodBase method, Delegate to)
			: this(method, to.Method, to.Target)
		{
		}

		public Hook(Delegate from, IntPtr to, ref HookConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Hook(Delegate from, IntPtr to, HookConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Hook(Delegate from, IntPtr to)
			: this(from.Method, to)
		{
		}

		public Hook(Delegate from, Delegate to, ref HookConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Hook(Delegate from, Delegate to, HookConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public Hook(Delegate from, Delegate to)
			: this(from.Method, to)
		{
		}

		public Hook(Expression from, IntPtr to, ref HookConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Hook(Expression from, IntPtr to, HookConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Hook(Expression from, IntPtr to)
			: this(((MethodCallExpression)from).Method, to)
		{
		}

		public Hook(Expression from, Delegate to, ref HookConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Hook(Expression from, Delegate to, HookConfig config)
			: this(((MethodCallExpression)from).Method, to, ref config)
		{
		}

		public Hook(Expression from, Delegate to)
			: this(((MethodCallExpression)from).Method, to)
		{
		}

		public Hook(Expression<Action> from, IntPtr to, ref HookConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Action> from, IntPtr to, HookConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Action> from, IntPtr to)
			: this(from.Body, to)
		{
		}

		public Hook(Expression<Action> from, Delegate to, ref HookConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Action> from, Delegate to, HookConfig config)
			: this(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Action> from, Delegate to)
			: this(from.Body, to)
		{
		}

		public void Apply()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("Hook");
			}
			if (!IsApplied)
			{
				Func<Hook, MethodBase, MethodBase, object, bool> onDetour = OnDetour;
				if (onDetour != null && !Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[4] { this, Method, Target, DelegateTarget }))
				{
					return;
				}
			}
			_Detour.Apply();
		}

		public void Undo()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("Hook");
			}
			if (IsApplied)
			{
				Func<Hook, bool> onUndo = OnUndo;
				if (onUndo != null && !Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this }))
				{
					return;
				}
			}
			_Detour.Undo();
			if (!IsValid)
			{
				_Free();
			}
		}

		public void Free()
		{
			if (IsValid)
			{
				_Detour.Free();
				_Free();
			}
		}

		public void Dispose()
		{
			if (IsValid)
			{
				Undo();
				Free();
			}
		}

		private void _Free()
		{
			if (_RefTarget.HasValue)
			{
				DynamicMethodHelper.FreeReference(_RefTarget.Value);
			}
			if (_RefTrampoline.HasValue)
			{
				DynamicMethodHelper.FreeReference(_RefTrampoline.Value);
			}
			if (_RefTrampolineTmp.HasValue)
			{
				DynamicMethodHelper.FreeReference(_RefTrampolineTmp.Value);
			}
			TargetReal.Unpin();
		}

		public MethodBase GenerateTrampoline(MethodBase signature = null)
		{
			Func<Hook, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline;
			MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null);
			if ((object)methodBase != null)
			{
				return methodBase;
			}
			return _Detour.GenerateTrampoline(signature);
		}

		public T GenerateTrampoline<T>() where T : Delegate
		{
			if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
			{
				throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
			}
			return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T;
		}

		internal void _UpdateOrig(MethodBase invoke)
		{
			if ((object)_OrigDelegateType != null)
			{
				Delegate @delegate = Extensions.CreateDelegate(invoke ?? GenerateTrampoline(_OrigDelegateInvoke), _OrigDelegateType);
				DynamicMethodHelper.SetReference(_RefTrampoline.Value, (object)@delegate);
				DynamicMethodHelper.SetReference(_RefTrampolineTmp.Value, (object)@delegate);
			}
		}
	}
	public class Hook<T> : Hook
	{
		public Hook(Expression<Action> from, T to, ref HookConfig config)
			: base(from.Body, to as Delegate, ref config)
		{
		}

		public Hook(Expression<Action> from, T to, HookConfig config)
			: base(from.Body, to as Delegate, ref config)
		{
		}

		public Hook(Expression<Action> from, T to)
			: base(from.Body, to as Delegate)
		{
		}

		public Hook(Expression<Func<T>> from, IntPtr to, ref HookConfig config)
			: base(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Func<T>> from, IntPtr to, HookConfig config)
			: base(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Func<T>> from, IntPtr to)
			: base(from.Body, to)
		{
		}

		public Hook(Expression<Func<T>> from, Delegate to, ref HookConfig config)
			: base(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Func<T>> from, Delegate to, HookConfig config)
			: base(from.Body, to, ref config)
		{
		}

		public Hook(Expression<Func<T>> from, Delegate to)
			: base(from.Body, to)
		{
		}

		public Hook(T from, IntPtr to, ref HookConfig config)
			: base(from as Delegate, to, ref config)
		{
		}

		public Hook(T from, IntPtr to, HookConfig config)
			: base(from as Delegate, to, ref config)
		{
		}

		public Hook(T from, IntPtr to)
			: base(from as Delegate, to)
		{
		}

		public Hook(T from, T to, ref HookConfig config)
			: base(from as Delegate, to as Delegate, ref config)
		{
		}

		public Hook(T from, T to, HookConfig config)
			: base(from as Delegate, to as Delegate, ref config)
		{
		}

		public Hook(T from, T to)
			: base(from as Delegate, to as Delegate)
		{
		}
	}
	public class Hook<TFrom, TTo> : Hook
	{
		public Hook(Expression<Func<TFrom>> from, TTo to, ref HookConfig config)
			: base(from.Body, to as Delegate)
		{
		}

		public Hook(Expression<Func<TFrom>> from, TTo to, HookConfig config)
			: base(from.Body, to as Delegate)
		{
		}

		public Hook(Expression<Func<TFrom>> from, TTo to)
			: base(from.Body, to as Delegate)
		{
		}

		public Hook(TFrom from, TTo to, ref HookConfig config)
			: base(from as Delegate, to as Delegate)
		{
		}

		public Hook(TFrom from, TTo to, HookConfig config)
			: base(from as Delegate, to as Delegate)
		{
		}

		public Hook(TFrom from, TTo to)
			: base(from as Delegate, to as Delegate)
		{
		}
	}
	public interface IDetour : IDisposable
	{
		bool IsValid { get; }

		bool IsApplied { get; }

		void Apply();

		void Undo();

		void Free();

		MethodBase GenerateTrampoline(MethodBase signature = null);

		T GenerateTrampoline<T>() where T : Delegate;
	}
	public interface ISortableDetour : IDetour, IDisposable
	{
		uint GlobalIndex { get; }

		int Priority { get; set; }

		string ID { get; set; }

		IEnumerable<string> Before { get; set; }

		IEnumerable<string> After { get; set; }
	}
	public struct ILHookConfig
	{
		public bool ManualApply;

		public int Priority;

		public string ID;

		public IEnumerable<string> Before;

		public IEnumerable<string> After;
	}
	public class ILHook : ISortableDetour, IDetour, IDisposable
	{
		private class Context
		{
			public List<ILHook> Chain = new List<ILHook>();

			public HashSet<ILContext> Active = new HashSet<ILContext>();

			public MethodBase Method;

			public Detour Detour;

			public Context(MethodBase method)
			{
				Method = method;
			}

			public void Add(ILHook hook)
			{
				List<ILHook> chain = Chain;
				lock (chain)
				{
					chain.Add(hook);
				}
			}

			public void Remove(ILHook hook)
			{
				List<ILHook> chain = Chain;
				lock (chain)
				{
					chain.Remove(hook);
					if (chain.Count == 0)
					{
						Refresh();
						lock (_Map)
						{
							_Map.Remove(Method);
							return;
						}
					}
				}
			}

			public void Refresh()
			{
				//IL_00be: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c5: Expected O, but got Unknown
				List<ILHook> chain = Chain;
				lock (chain)
				{
					foreach (ILContext item in Active)
					{
						item.Dispose();
					}
					Active.Clear();
					Detour?.Dispose();
					Detour = null;
					if (chain.Count == 0)
					{
						return;
					}
					bool flag = false;
					foreach (ILHook item2 in chain)
					{
						if (item2.IsApplied)
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						return;
					}
					DetourSorter<ILHook>.Sort(chain);
					DynamicMethodDefinition val = new DynamicMethodDefinition(Method);
					MethodBase to;
					try
					{
						MethodDefinition definition = val.Definition;
						foreach (ILHook item3 in chain)
						{
							if (item3.IsApplied)
							{
								InvokeManipulator(definition, item3.Manipulator);
							}
						}
						to = val.Generate();
					}
					finally
					{
						((IDisposable)val)?.Dispose();
					}
					Detour = new Detour(Method, to, ref ILDetourConfig);
				}
			}

			private void InvokeManipulator(MethodDefinition def, Manipulator cb)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				ILContext val = new ILContext(def);
				val.ReferenceBag = (IILReferenceBag)(object)RuntimeILReferenceBag.Instance;
				val.Invoke(cb);
				if (val.IsReadOnly)
				{
					val.Dispose();
					return;
				}
				val.MakeReadOnly();
				Active.Add(val);
			}
		}

		public static Func<ILHook, MethodBase, Manipulator, bool> OnDetour;

		public static Func<ILHook, bool> OnUndo;

		private static DetourConfig ILDetourConfig = new DetourConfig
		{
			Priority = -268435456,
			Before = new string[1] { "*" }
		};

		private static Dictionary<MethodBase, Context> _Map = new Dictionary<MethodBase, Context>();

		private static uint _GlobalIndexNext = 0u;

		private readonly uint _GlobalIndex;

		private int _Priority;

		private string _ID;

		private List<string> _Before = new List<string>();

		private ReadOnlyCollection<string> _BeforeRO;

		private List<string> _After = new List<string>();

		private ReadOnlyCollection<string> _AfterRO;

		public readonly MethodBase Method;

		public readonly Manipulator Manipulator;

		private Context _Ctx
		{
			get
			{
				if (!_Map.TryGetValue(Method, out var value))
				{
					return null;
				}
				return value;
			}
		}

		public bool IsValid => Index != -1;

		public bool IsApplied { get; private set; }

		public int Index => _Ctx?.Chain.IndexOf(this) ?? (-1);

		public int MaxIndex => _Ctx?.Chain.Count ?? (-1);

		public uint GlobalIndex => _GlobalIndex;

		public int Priority
		{
			get
			{
				return _Priority;
			}
			set
			{
				if (_Priority != value)
				{
					_Priority = value;
					_Ctx.Refresh();
				}
			}
		}

		public string ID
		{
			get
			{
				return _ID;
			}
			set
			{
				if (string.IsNullOrEmpty(value))
				{
					MethodInfo method = ((Delegate)(object)Manipulator).Method;
					value = (((object)method != null) ? Extensions.GetID((MethodBase)method, (string)null, (string)null, true, false, true) : null) ?? GetHashCode().ToString(CultureInfo.InvariantCulture);
				}
				if (!(_ID == value))
				{
					_ID = value;
					_Ctx.Refresh();
				}
			}
		}

		public IEnumerable<string> Before
		{
			get
			{
				return _BeforeRO ?? (_BeforeRO = _Before.AsReadOnly());
			}
			set
			{
				lock (_Before)
				{
					_Before.Clear();
					if (value != null)
					{
						foreach (string item in value)
						{
							_Before.Add(item);
						}
					}
					_Ctx.Refresh();
				}
			}
		}

		public IEnumerable<string> After
		{
			get
			{
				return _AfterRO ?? (_AfterRO = _After.AsReadOnly());
			}
			set
			{
				lock (_After)
				{
					_After.Clear();
					if (value != null)
					{
						foreach (string item in value)
						{
							_After.Add(item);
						}
					}
					_Ctx.Refresh();
				}
			}
		}

		public ILHook(MethodBase from, Manipulator manipulator, ref ILHookConfig config)
		{
			from = from.GetIdentifiable();
			Method = from.Pin();
			Manipulator = manipulator;
			_GlobalIndex = _GlobalIndexNext++;
			_Priority = config.Priority;
			_ID = config.ID;
			if (config.Before != null)
			{
				foreach (string item in config.Before)
				{
					_Before.Add(item);
				}
			}
			if (config.After != null)
			{
				foreach (string item2 in config.After)
				{
					_After.Add(item2);
				}
			}
			Context value;
			lock (_Map)
			{
				if (!_Map.TryGetValue(Method, out value))
				{
					value = (_Map[Method] = new Context(Method));
				}
			}
			lock (value)
			{
				value.Add(this);
			}
			if (!config.ManualApply)
			{
				Apply();
			}
		}

		public ILHook(MethodBase from, Manipulator manipulator, ILHookConfig config)
			: this(from, manipulator, ref config)
		{
		}

		public ILHook(MethodBase from, Manipulator manipulator)
			: this(from, manipulator, DetourContext.Current?.ILHookConfig ?? default(ILHookConfig))
		{
		}

		public void Apply()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("ILHook");
			}
			if (!IsApplied)
			{
				Func<ILHook, MethodBase, Manipulator, bool> onDetour = OnDetour;
				if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[3] { this, Method, Manipulator }))
				{
					IsApplied = true;
					_Ctx.Refresh();
				}
			}
		}

		public void Undo()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("ILHook");
			}
			if (IsApplied)
			{
				Func<ILHook, bool> onUndo = OnUndo;
				if (onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this }))
				{
					IsApplied = false;
					_Ctx.Refresh();
				}
			}
		}

		public void Free()
		{
			if (IsValid)
			{
				Undo();
				_Ctx.Remove(this);
				Method.Unpin();
			}
		}

		public void Dispose()
		{
			if (IsValid)
			{
				Undo();
				Free();
			}
		}

		public MethodBase GenerateTrampoline(MethodBase signature = null)
		{
			throw new NotSupportedException();
		}

		public T GenerateTrampoline<T>() where T : Delegate
		{
			throw new NotSupportedException();
		}
	}
	public struct NativeDetourConfig
	{
		public bool ManualApply;

		public bool SkipILCopy;
	}
	public class NativeDetour : IDetour, IDisposable
	{
		public static Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool> OnDetour;

		public static Func<NativeDetour, bool> OnUndo;

		public static Func<NativeDetour, MethodBase, MethodBase> OnGenerateTrampoline;

		private NativeDetourData _Data;

		public readonly MethodBase Method;

		private readonly MethodInfo _BackupMethod;

		private readonly IntPtr _BackupNative;

		private HashSet<MethodBase> _Pinned = new HashSet<MethodBase>();

		public bool IsValid { get; private set; }

		public bool IsApplied { get; private set; }

		public NativeDetourData Data => _Data;

		public NativeDetour(MethodBase method, IntPtr from, IntPtr to, ref NativeDetourConfig config)
		{
			if (from == to)
			{
				throw new InvalidOperationException($"Cannot detour from a location to itself! (from: {from:X16} to: {to:X16} method: {method})");
			}
			method = method?.GetIdentifiable();
			Method = method;
			Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool> onDetour = OnDetour;
			if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[4] { this, method, from, to }))
			{
				IsValid = true;
				_Data = DetourHelper.Native.Create(from, to);
				if (!config.SkipILCopy)
				{
					method?.TryCreateILCopy(out _BackupMethod);
				}
				_BackupNative = DetourHelper.Native.MemAlloc(_Data.Size);
				if (!config.ManualApply)
				{
					Apply();
				}
			}
		}

		public NativeDetour(MethodBase method, IntPtr from, IntPtr to, NativeDetourConfig config)
			: this(method, from, to, ref config)
		{
		}

		public NativeDetour(MethodBase method, IntPtr from, IntPtr to)
			: this(method, from, to, default(NativeDetourConfig))
		{
		}

		public NativeDetour(IntPtr from, IntPtr to, ref NativeDetourConfig config)
			: this(null, from, to, ref config)
		{
		}

		public NativeDetour(IntPtr from, IntPtr to, NativeDetourConfig config)
			: this(null, from, to, ref config)
		{
		}

		public NativeDetour(IntPtr from, IntPtr to)
			: this(null, from, to)
		{
		}

		public NativeDetour(MethodBase from, IntPtr to, ref NativeDetourConfig config)
			: this(from, from.Pin().GetNativeStart(), to, ref config)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(MethodBase from, IntPtr to, NativeDetourConfig config)
			: this(from, from.Pin().GetNativeStart(), to, ref config)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(MethodBase from, IntPtr to)
			: this(from, from.Pin().GetNativeStart(), to)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(IntPtr from, MethodBase to, ref NativeDetourConfig config)
			: this(from, to.Pin().GetNativeStart(), ref config)
		{
			_Pinned.Add(to);
		}

		public NativeDetour(IntPtr from, MethodBase to, NativeDetourConfig config)
			: this(from, to.Pin().GetNativeStart(), ref config)
		{
			_Pinned.Add(to);
		}

		public NativeDetour(IntPtr from, MethodBase to)
			: this(from, to.Pin().GetNativeStart())
		{
			_Pinned.Add(to);
		}

		public NativeDetour(MethodBase from, MethodBase to, ref NativeDetourConfig config)
			: this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to), ref config)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(MethodBase from, MethodBase to, NativeDetourConfig config)
			: this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to), ref config)
		{
			_Pinned.Add(from);
		}

		public NativeDetour(MethodBase from, MethodBase to)
			: this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to))
		{
			_Pinned.Add(from);
		}

		public NativeDetour(Delegate from, IntPtr to, ref NativeDetourConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public NativeDetour(Delegate from, IntPtr to, NativeDetourConfig config)
			: this(from.Method, to, ref config)
		{
		}

		public NativeDetour(Delegate from, IntPtr to)
			: this(from.Method, to)
		{
		}

		public NativeDetour(IntPtr from, Delegate to, ref NativeDetourConfig config)
			: this(from, to.Method, ref config)
		{
		}

		public NativeDetour(IntPtr from, Delegate to, NativeDetourConfig config)
			: this(from, to.Method, ref config)
		{
		}

		public NativeDetour(IntPtr from, Delegate to)
			: this(from, to.Method)
		{
		}

		public NativeDetour(Delegate from, Delegate to, ref NativeDetourConfig config)
			: this(from.Method, to.Method, ref config)
		{
		}

		public NativeDetour(Delegate from, Delegate to, NativeDetourConfig config)
			: this(from.Method, to.Method, ref config)
		{
		}

		public NativeDetour(Delegate from, Delegate to)
			: this(from.Method, to.Method)
		{
		}

		public void Apply()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			if (!IsApplied)
			{
				IsApplied = true;
				DetourHelper.Native.Copy(_Data.Method, _BackupNative, _Data.Type);
				DetourHelper.Native.MakeWritable(_Data);
				DetourHelper.Native.Apply(_Data);
				DetourHelper.Native.MakeExecutable(_Data);
				DetourHelper.Native.FlushICache(_Data);
			}
		}

		public void Undo()
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			Func<NativeDetour, bool> onUndo = OnUndo;
			if ((onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) && IsApplied)
			{
				IsApplied = false;
				DetourHelper.Native.MakeWritable(_Data);
				DetourHelper.Native.Copy(_BackupNative, _Data.Method, _Data.Type);
				DetourHelper.Native.MakeExecutable(_Data);
				DetourHelper.Native.FlushICache(_Data);
			}
		}

		public void ChangeSource(IntPtr newSource)
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			NativeDetourData data = _Data;
			_Data = DetourHelper.Native.Create(newSource, _Data.Target);
			IsApplied = false;
			Apply();
			DetourHelper.Native.Free(data);
		}

		public void ChangeTarget(IntPtr newTarget)
		{
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			NativeDetourData data = _Data;
			_Data = DetourHelper.Native.Create(_Data.Method, newTarget);
			IsApplied = false;
			Apply();
			DetourHelper.Native.Free(data);
		}

		public void Free()
		{
			if (!IsValid)
			{
				return;
			}
			IsValid = false;
			DetourHelper.Native.MemFree(_BackupNative);
			DetourHelper.Native.Free(_Data);
			if (IsApplied)
			{
				return;
			}
			foreach (MethodBase item in _Pinned)
			{
				item.Unpin();
			}
			_Pinned.Clear();
		}

		public void Dispose()
		{
			if (IsValid)
			{
				Undo();
				Free();
			}
		}

		public MethodBase GenerateTrampoline(MethodBase signature = null)
		{
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Expected O, but got Unknown
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Expected O, but got Unknown
			//IL_0198: Expected O, but got Unknown
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			Func<NativeDetour, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline;
			MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null);
			if ((object)methodBase != null)
			{
				return methodBase;
			}
			if (!IsValid)
			{
				throw new ObjectDisposedException("NativeDetour");
			}
			if ((object)_BackupMethod != null)
			{
				return _BackupMethod;
			}
			if ((object)signature == null)
			{
				throw new ArgumentNullException("A signature must be given if the NativeDetour doesn't hold a reference to a managed method.");
			}
			MethodBase methodBase2 = Method;
			if ((object)methodBase2 == null)
			{
				methodBase2 = DetourHelper.GenerateNativeProxy(_Data.Method, signature);
			}
			Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void);
			ParameterInfo[] parameters = signature.GetParameters();
			Type[] array = new Type[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				array[i] = parameters[i].ParameterType;
			}
			MethodBase method = Method;
			DynamicMethodDefinition val = new DynamicMethodDefinition(string.Format("Trampoline:Native<{0}>?{1}", (((object)method != null) ? Extensions.GetID(method, (string)null, (string)null, true, false, true) : null) ?? ((long)_Data.Method).ToString("X16", CultureInfo.InvariantCulture), GetHashCode()), type, array);
			try
			{
				ILProcessor iLProcessor = val.GetILProcessor();
				ExceptionHandler val2 = new ExceptionHandler((ExceptionHandlerType)2);
				iLProcessor.Body.ExceptionHandlers.Add(val2);
				iLProcessor.EmitDetourCopy(_BackupNative, _Data.Method, _Data.Type);
				VariableDefinition val3 = null;
				if ((object)type != typeof(void))
				{
					Collection<VariableDefinition> variables = iLProcessor.Body.Variables;
					VariableDefinition val4 = new VariableDefinition(Extensions.Import(iLProcessor, type));
					val3 = val4;
					variables.Add(val4);
				}
				int count = iLProcessor.Body.Instructions.Count;
				for (int j = 0; j < array.Length; j++)
				{
					iLProcessor.Emit(OpCodes.Ldarg, j);
				}
				if (methodBase2 is MethodInfo)
				{
					Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)(MethodInfo)methodBase2);
				}
				else
				{
					if (!(methodBase2 is ConstructorInfo))
					{
						throw new NotSupportedException("Method type " + methodBase2.GetType().FullName + " not supported.");
					}
					Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)(ConstructorInfo)methodBase2);
				}
				if (val3 != null)
				{
					iLProcessor.Emit(OpCodes.Stloc, val3);
				}
				Extensions.Emit(iLProcessor, OpCodes.Leave, (object)null);
				Instruction obj = iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1];
				int count2 = iLProcessor.Body.Instructions.Count;
				_ = iLProcessor.Body.Instructions.Count;
				iLProcessor.EmitDetourApply(_Data);
				int count3 = iLProcessor.Body.Instructions.Count;
				Instruction val5 = null;
				if (val3 != null)
				{
					iLProcessor.Emit(OpCodes.Ldloc, val3);
					val5 = iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1];
				}
				iLProcessor.Emit(OpCodes.Ret);
				val5 = val5 ?? iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1];
				obj.Operand = val5;
				val2.TryStart = iLProcessor.Body.Instructions[count];
				val2.TryEnd = iLProcessor.Body.Instructions[count2];
				val2.HandlerStart = iLProcessor.Body.Instructions[count2];
				val2.HandlerEnd = iLProcessor.Body.Instructions[count3];
				return val.Generate();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		public T GenerateTrampoline<T>() where T : Delegate
		{
			if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
			{
				throw new InvalidOperationException($"Type {typeof(T)} not a delegate type.");
			}
			return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T;
		}
	}
	internal static class DetourSorter<T> where T : ISortableDetour
	{
		private sealed class Group
		{
			public readonly string StepName;

			public List<T> Items = new List<T>();

			public List<Group> Children = new List<Group>();

			public List<Group> NonMatching = new List<Group>();

			public Group(string stepName)
			{
				StepName = stepName;
			}

			public Group(string stepName, List<T> items)
				: this(stepName)
			{
				Items.AddRange(items);
			}

			public void Step(Step step)
			{
				if (Children.Count != 0)
				{
					foreach (Group child in Children)
					{
						child.Step(step);
					}
					return;
				}
				if (Items.Count <= 1)
				{
					return;
				}
				if ((Items.Count == 2 && !((!step.IsFlat) ?? false)) || step.IsFlat.GetValueOrDefault())
				{
					Items.Sort(step);
					return;
				}
				string name = step.GetType().Name;
				Group group = new Group(name, new List<T> { Items[0] });
				Children.Add(group);
				for (int i = 1; i < Items.Count; i++)
				{
					T val = Items[i];
					if (step.Any(group.Items, val))
					{
						Group group2 = group;
						group = null;
						if (Children.Count > 1)
						{
							foreach (Group child2 in Children)
							{
								if (child2 != group2 && !step.Any(child2.Items, val) && !step.Any(child2.NonMatching, val))
								{
									group = child2;
									break;
								}
							}
						}
						if (group == null)
						{
							group = new Group(name);
							Children.Add(group);
							group.NonMatching.Add(group2);
							group2.NonMatching.Add(group);
						}
					}
					group.Items.Add(val);
				}
				if (Children.Count == 1)
				{
					Children.Clear();
				}
				else
				{
					Children.Sort(step.ForGroup);
				}
			}

			public void Flatten()
			{
				if (Children.Count != 0)
				{
					Items.Clear();
					Flatten(Items);
				}
			}

			public void Flatten(List<T> total)
			{
				if (Children.Count == 0)
				{
					total.AddRange(Items);
					return;
				}
				foreach (Group child in Children)
				{
					child.Flatten(total);
				}
			}
		}

		private abstract class Step : IComparer<T>
		{
			public abstract GroupComparer ForGroup { get; }

			public virtual bool? IsFlat => null;

			public abstract int Compare(T x, T y);

			public bool Any(List<T> xlist, T y)
			{
				foreach (T item in xlist)
				{
					if (Compare(item, y) != 0)
					{
						return true;
					}
				}
				return false;
			}

			public bool Any(List<Group> groups, T y)
			{
				foreach (Group group in groups)
				{
					if (Any(group.Items, y))
					{
						return true;
					}
				}
				return false;
			}
		}

		private sealed class GroupComparer : IComparer<Group>
		{
			public Step Step;

			public GroupComparer(Step step)
			{
				Step = step;
			}

			public int Compare(Group xg, Group yg)
			{
				foreach (T item in xg.Items)
				{
					foreach (T item2 in yg.Items)
					{
						int result;
						if ((result = Step.Compare(item, item2)) != 0)
						{
							return result;
						}
					}
				}
				return 0;
			}
		}

		private sealed class BeforeAfterAll : Step
		{
			public static readonly BeforeAfterAll _ = new BeforeAfterAll();

			public static readonly GroupComparer Group = new GroupComparer(_);

			public override GroupComparer ForGroup => Group;

			public override bool? IsFlat => false;

			public override int Compare(T a, T b)
			{
				if (a.Before.Contains("*") && !b.Before.Contains("*"))
				{
					return -1;
				}
				if (!a.Before.Contains("*") && b.Before.Contains("*"))
				{
					return 1;
				}
				if (a.After.Contains("*") && !b.After.Contains("*"))
				{
					return 1;
				}
				if (!a.After.Contains("*") && b.After.Contains("*"))
				{
					return -1;
				}
				return 0;
			}
		}

		private sealed class BeforeAfter : Step
		{
			public static readonly BeforeAfter _ = new BeforeAfter();

			public static readonly GroupComparer Group = new GroupComparer(_);

			public override GroupComparer ForGroup => Group;

			public override int Compare(T a, T b)
			{
				if (a.Before.Contains(b.ID))
				{
					return -1;
				}
				if (a.After.Contains(b.ID))
				{
					return 1;
				}
				if (b.Before.Contains(a.ID))
				{
					return 1;
				}
				if (b.After.Contains(a.ID))
				{
					return -1;
				}
				return 0;
			}
		}

		private sealed class Priority : Step
		{
			public static readonly Priority _ = new Priority();

			public static readonly GroupComparer Group = new GroupComparer(_);

			public override GroupComparer ForGroup => Group;

			public override int Compare(T a, T b)
			{
				int num = a.Priority - b.Priority;
				if (num != 0)
				{
					return num;
				}
				return 0;
			}
		}

		private sealed class GlobalIndex : Step
		{
			public static readonly GlobalIndex _ = new GlobalIndex();

			public static readonly GroupComparer Group = new GroupComparer(_);

			public override GroupComparer ForGroup => Group;

			public override int Compare(T a, T b)
			{
				return a.GlobalIndex.CompareTo(b.GlobalIndex);
			}
		}

		public static void Sort(List<T> detours)
		{
			lock (detours)
			{
				if (detours.Count > 1)
				{
					detours.Sort(GlobalIndex._);
					Group group = new Group("Init", detours);
					group.Step(BeforeAfterAll._);
					group.Step(BeforeAfter._);
					group.Step(Priority._);
					group.Step(GlobalIndex._);
					detours.Clear();
					group.Flatten(detours);
				}
			}
		}
	}
	public static class DetourHelper
	{
		private static readonly object _RuntimeLock = new object();

		private static bool _RuntimeInit = false;

		private static IDetourRuntimePlatform _Runtime;

		private static readonly object _NativeLock = new object();

		private static bool _NativeInit = false;

		private static IDetourNativePlatform _Native;

		private static readonly FieldInfo _f_Native = typeof(DetourHelper).GetField("_Native", BindingFlags.Static | BindingFlags.NonPublic);

		private static readonly MethodInfo _m_ToNativeDetourData = typeof(DetourHelper).GetMethod("ToNativeDetourData", BindingFlags.Static | BindingFlags.NonPublic);

		private static readonly MethodInfo _m_Copy = typeof(IDetourNativePlatform).GetMethod("Copy");

		private static readonly MethodInfo _m_Apply = typeof(IDetourNativePlatform).GetMethod("Apply");

		private static readonly ConstructorInfo _ctor_Exception = typeof(Exception).GetConstructor(new Type[1] { typeof(string) });

		public static IDetourRuntimePlatform Runtime
		{
			get
			{
				if (_Runtime != null)
				{
					return _Runtime;
				}
				lock (_RuntimeLock)
				{
					if (_Runtime != null)
					{
						return _Runtime;
					}
					if (_RuntimeInit)
					{
						return null;
					}
					_RuntimeInit = true;
					if ((object)Type.GetType("Mono.Runtime") != null)
					{
						_Runtime = new DetourRuntimeMonoPlatform();
					}
					else if (typeof(object).Assembly.GetName().Name == "System.Private.CoreLib")
					{
						_Runtime = DetourRuntimeNETCorePlatform.Create();
					}
					else
					{
						_Runtime = new DetourRuntimeNETPlatform();
					}
					return _Runtime;
				}
			}
			set
			{
				_Runtime = value;
			}
		}

		public static IDetourNativePlatform Native
		{
			get
			{
				if (_Native != null)
				{
					return _Native;
				}
				lock (_NativeLock)
				{
					if (_Native != null)
					{
						return _Native;
					}
					if (_NativeInit)
					{
						return null;
					}
					_NativeInit = true;
					IDetourNativePlatform detourNativePlatform = ((!PlatformHelper.Is((Platform)65536)) ? ((IDetourNativePlatform)new DetourNativeX86Platform()) : ((IDetourNativePlatform)new DetourNativeARMPlatform()));
					if (PlatformHelper.Is((Platform)37))
					{
						return _Native = new DetourNativeWindowsPlatform(detourNativePlatform);
					}
					if ((object)Type.GetType("Mono.Runtime") != null)
					{
						try
						{
							return _Native = new DetourNativeMonoPlatform(detourNativePlatform, "libmonosgen-2.0." + PlatformHelper.LibrarySuffix);
						}
						catch
						{
						}
					}
					string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_RUNTIMEDETOUR_MONOPOSIXHELPER");
					if (((object)Type.GetType("Mono.Runtime") != null && environmentVariable != "0") || environmentVariable == "1")
					{
						try
						{
							return _Native = new DetourNativeMonoPosixPlatform(detourNativePlatform);
						}
						catch
						{
						}
					}
					try
					{
						return _Native = new DetourNativeLibcPlatform(detourNativePlatform);
					}
					catch
					{
					}
					return detourNativePlatform;
				}
			}
			set
			{
				_Native = value;
			}
		}

		public static void MakeWritable(this IDetourNativePlatform plat, NativeDetourData detour)
		{
			plat.MakeWritable(detour.Method, detour.Size);
		}

		public static void MakeExecutable(this IDetourNativePlatform plat, NativeDetourData detour)
		{
			plat.MakeExecutable(detour.Method, detour.Size);
		}

		public static void FlushICache(this IDetourNativePlatform plat, NativeDetourData detour)
		{
			plat.FlushICache(detour.Method, detour.Size);
		}

		public unsafe static void Write(this IntPtr to, ref int offs, byte value)
		{
			*(byte*)((long)to + offs) = value;
			offs++;
		}

		public unsafe static void Write(this IntPtr to, ref int offs, ushort value)
		{
			*(ushort*)((long)to + offs) = value;
			offs += 2;
		}

		public unsafe static void Write(this IntPtr to, ref int offs, uint value)
		{
			*(uint*)((long)to + offs) = value;
			offs += 4;
		}

		public unsafe static void Write(this IntPtr to, ref int offs, ulong value)
		{
			*(ulong*)((long)to + offs) = value;
			offs += 8;
		}

		public static MethodBase GetIdentifiable(this MethodBase method)
		{
			return Runtime.GetIdentifiable(method);
		}

		public static IntPtr GetNativeStart(this MethodBase method)
		{
			return Runtime.GetNativeStart(method);
		}

		public static IntPtr GetNativeStart(this Delegate method)
		{
			return method.Method.GetNativeStart();
		}

		public static IntPtr GetNativeStart(this Expression method)
		{
			return ((MethodCallExpression)method).Method.GetNativeStart();
		}

		public static MethodInfo CreateILCopy(this MethodBase method)
		{
			return Runtime.CreateCopy(method);
		}

		public static bool TryCreateILCopy(this MethodBase method, out MethodInfo dm)
		{
			return Runtime.TryCreateCopy(method, out dm);
		}

		public static T Pin<T>(this T method) where T : MethodBase
		{
			Runtime.Pin(method);
			return method;
		}

		public static T Unpin<T>(this T method) where T : MethodBase
		{
			Runtime.Unpin(method);
			return method;
		}

		public static MethodInfo GenerateNativeProxy(IntPtr target, MethodBase signature)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void);
			ParameterInfo[] parameters = signature.GetParameters();
			Type[] array = new Type[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				array[i] = parameters[i].ParameterType;
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition("Native<" + ((long)target).ToString("X16", CultureInfo.InvariantCulture) + ">", type, array);
			MethodInfo methodInfo;
			try
			{
				methodInfo = val.StubCriticalDetour().Generate().Pin();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			NativeDetourData detour = Native.Create(methodInfo.GetNativeStart(), target);
			Native.MakeWritable(detour);
			Native.Apply(detour);
			Native.MakeExecutable(detour);
			Native.FlushICache(detour);
			Native.Free(detour);
			return methodInfo;
		}

		private static NativeDetourData ToNativeDetourData(IntPtr method, IntPtr target, uint size, byte type, IntPtr extra)
		{
			NativeDetourData result = default(NativeDetourData);
			result.Method = method;
			result.Target = target;
			result.Size = size;
			result.Type = type;
			result.Extra = extra;
			return result;
		}

		public static DynamicMethodDefinition StubCriticalDetour(this DynamicMethodDefinition dm)
		{
			//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_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			ILProcessor iLProcessor = dm.GetILProcessor();
			ModuleDefinition module = ((MemberReference)iLProcessor.Body.Method).Module;
			for (int i = 0; i < 32; i++)
			{
				iLProcessor.Emit(OpCodes.Nop);
			}
			iLProcessor.Emit(OpCodes.Ldstr, ((MemberReference)dm.Definition).Name + " should've been detoured!");
			iLProcessor.Emit(OpCodes.Newobj, module.ImportReference((MethodBase)_ctor_Exception));
			iLProcessor.Emit(OpCodes.Throw);
			return dm;
		}

		public static void EmitDetourCopy(this ILProcessor il, IntPtr src, IntPtr dst, byte type)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			ModuleDefinition module = ((MemberReference)il.Body.Method).Module;
			il.Emit(OpCodes.Ldsfld, module.ImportReference(_f_Native));
			il.Emit(OpCodes.Ldc_I8, (long)src);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Ldc_I8, (long)dst);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Ldc_I4, (int)type);
			il.Emit(OpCodes.Conv_U1);
			il.Emit(OpCodes.Callvirt, module.ImportReference((MethodBase)_m_Copy));
		}

		public static void EmitDetourApply(this ILProcessor il, NativeDetourData data)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			ModuleDefinition module = ((MemberReference)il.Body.Method).Module;
			il.Emit(OpCodes.Ldsfld, module.ImportReference(_f_Native));
			il.Emit(OpCodes.Ldc_I8, (long)data.Method);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Ldc_I8, (long)data.Target);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Ldc_I4, (int)data.Size);
			il.Emit(OpCodes.Ldc_I4, (int)data.Type);
			il.Emit(OpCodes.Conv_U1);
			il.Emit(OpCodes.Ldc_I8, (long)data.Extra);
			il.Emit(OpCodes.Conv_I);
			il.Emit(OpCodes.Call, module.ImportReference((MethodBase)_m_ToNativeDetourData));
			il.Emit(OpCodes.Callvirt, module.ImportReference((MethodBase)_m_Apply));
		}
	}
	public interface IDetourNativePlatform
	{
		NativeDetourData Create(IntPtr from, IntPtr to, byte? type = null);

		void Free(NativeDetourData detour);

		void Apply(NativeDetourData detour);

		void Copy(IntPtr src, IntPtr dst, byte type);

		void MakeWritable(IntPtr src, uint size);

		void MakeExecutable(IntPtr src, uint size);

		void MakeReadWriteExecutable(IntPtr src, uint size);

		void FlushICache(IntPtr src, uint size);

		IntPtr MemAlloc(uint size);

		void MemFree(IntPtr ptr);
	}
	public interface IDetourRuntimePlatform
	{
		bool OnMethodCompiledWillBeCalled { get; }

		event OnMethodCompiledEvent OnMethodCompiled;

		MethodBase GetIdentifiable(MethodBase method);

		IntPtr GetNativeStart(MethodBase method);

		MethodInfo CreateCopy(MethodBase method);

		bool TryCreateCopy(MethodBase method, out MethodInfo dm);

		void Pin(MethodBase method);

		void Unpin(MethodBase method);

		MethodBase GetDetourTarget(MethodBase from, MethodBase to);

		uint TryMemAllocScratchCloseTo(IntPtr target, out IntPtr ptr, int size);
	}
	public delegate void OnMethodCompiledEvent(MethodBase method, IntPtr codeStart, ulong codeSize);
	public struct NativeDetourData
	{
		public IntPtr Method;

		public IntPtr Target;

		public byte Type;

		public uint Size;

		public IntPtr Extra;
	}
}
namespace MonoMod.RuntimeDetour.Platforms
{
	public class DetourNativeARMPlatform : IDetourNativePlatform
	{
		public enum DetourType : byte
		{
			Thumb,
			ThumbBX,
			AArch32,
			AArch32BX,
			AArch64
		}

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate int d_flushicache(IntPtr code, ulong size);

		private static readonly uint[] DetourSizes = new uint[5] { 8u, 12u, 8u, 12u, 16u };

		public bool ShouldFlushICache = true;

		private readonly byte[] _FlushCache32 = new byte[44]
		{
			128, 64, 45, 233, 0, 48, 160, 225, 1, 192,
			128, 224, 20, 224, 159, 229, 3, 0, 160, 225,
			12, 16, 160, 225, 14, 112, 160, 225, 0, 32,
			160, 227, 0, 0, 0, 239, 128, 128, 189, 232,
			2, 0, 15, 0
		};

		private readonly byte[] _FlushCache64 = new byte[76]
		{
			1, 0, 1, 139, 0, 244, 126, 146, 63, 0,
			0, 235, 201, 0, 0, 84, 226, 3, 0, 170,
			34, 126, 11, 213, 66, 16, 0, 145, 63, 0,
			2, 235, 168, 255, 255, 84, 159, 59, 3, 213,
			63, 0, 0, 235, 169, 0, 0, 84, 32, 117,
			11, 213, 0, 16, 0, 145, 63, 0, 0, 235,
			168, 255, 255, 84, 159, 59, 3, 213, 223, 63,
			3, 213, 192, 3, 95, 214
		};

		private static DetourType GetDetourType(IntPtr from, IntPtr to)
		{
			if (IntPtr.Size >= 8)
			{
				return DetourType.AArch64;
			}
			bool num = ((long)from & 1) == 1;
			bool flag = ((long)to & 1) == 1;
			if (num)
			{
				if (flag)
				{
					return DetourType.Thumb;
				}
				return DetourType.ThumbBX;
			}
			if (flag)
			{
				return DetourType.AArch32BX;
			}
			return DetourType.AArch32;
		}

		public NativeDetourData Create(IntPtr from, IntPtr to, byte? type)
		{
			NativeDetourData nativeDetourData = default(NativeDetourData);
			nativeDetourData.Method = (IntPtr)((long)from & -2);
			nativeDetourData.Target = (IntPtr)((long)to & -2);
			NativeDetourData result = nativeDetourData;
			uint[] detourSizes = DetourSizes;
			int num = ((int?)type) ?? ((int)GetDetourType(from, to));
			byte b = (byte)num;
			result.Type = (byte)num;
			result.Size = detourSizes[b];
			return result;
		}

		public void Free(NativeDetourData detour)
		{
		}

		public void Apply(NativeDetourData detour)
		{
			int offs = 0;
			switch ((DetourType)detour.Type)
			{
			case DetourType.Thumb:
				detour.Method.Write(ref offs, 223);
				detour.Method.Write(ref offs, 248);
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 240);
				detour.Method.Write(ref offs, (uint)(int)detour.Target | 1u);
				break;
			case DetourType.ThumbBX:
				detour.Method.Write(ref offs, 223);
				detour.Method.Write(ref offs, 248);
				detour.Method.Write(ref offs, 4);
				detour.Method.Write(ref offs, 160);
				detour.Method.Write(ref offs, 80);
				detour.Method.Write(ref offs, 71);
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 191);
				detour.Method.Write(ref offs, (uint)(int)detour.Target | 0u);
				break;
			case DetourType.AArch32:
				detour.Method.Write(ref offs, 4);
				detour.Method.Write(ref offs, 240);
				detour.Method.Write(ref offs, 31);
				detour.Method.Write(ref offs, 229);
				detour.Method.Write(ref offs, (uint)(int)detour.Target | 0u);
				break;
			case DetourType.AArch32BX:
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 128);
				detour.Method.Write(ref offs, 159);
				detour.Method.Write(ref offs, 229);
				detour.Method.Write(ref offs, 24);
				detour.Method.Write(ref offs, byte.MaxValue);
				detour.Method.Write(ref offs, 47);
				detour.Method.Write(ref offs, 225);
				detour.Method.Write(ref offs, (uint)(int)detour.Target | 1u);
				break;
			case DetourType.AArch64:
				detour.Method.Write(ref offs, 79);
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 0);
				detour.Method.Write(ref offs, 88);
				detour.Method.Write(ref offs, 224);
				detour.Method.Write(ref offs, 1);
				detour.Method.Write(ref offs, 31);
				detour.Method.Write(ref offs, 214);
				detour.Method.Write(ref offs, (ulong)(long)detour.Target);
				break;
			default:
				throw new NotSupportedException($"Unknown detour type {detour.Type}");
			}
		}

		public unsafe void Copy(IntPtr src, IntPtr dst, byte type)
		{
			switch ((DetourType)type)
			{
			case DetourType.Thumb:
				*(int*)(long)dst = *(int*)(long)src;
				*(int*)((long)dst + 4) = *(int*)((long)src + 4);
				break;
			case DetourType.ThumbBX:
				*(int*)(long)dst = *(int*)(long)src;
				*(short*)((long)dst + 4) = *(short*)((long)src + 4);
				*(short*)((long)dst + 6) = *(short*)((long)src + 6);
				*(int*)((long)dst + 8) = *(int*)((long)src + 8);
				break;
			case DetourType.AArch32:
				*(int*)(long)dst = *(int*)(long)src;
				*(int*)((long)dst + 4) = *(int*)((long)src + 4);
				break;
			case DetourType.AArch32BX:
				*(int*)(long)dst = *(int*)(long)src;
				*(int*)((long)dst + 4) = *(int*)((long)src + 4);
				*(int*)((long)dst + 8) = *(int*)((long)src + 8);
				break;
			case DetourType.AArch64:
				*(int*)(long)dst = *(int*)(long)src;
				*(int*)((long)dst + 4) = *(int*)((long)src + 4);
				*(long*)((long)dst + 8) = *(long*)((long)src + 8);
				break;
			default:
				throw new NotSupportedException($"Unknown detour type {type}");
			}
		}

		public void MakeWritable(IntPtr src, uint size)
		{
		}

		public void MakeExecutable(IntPtr src, uint size)
		{
		}

		public void MakeReadWriteExecutable(IntPtr src, uint size)
		{
		}

		public unsafe void FlushICache(IntPtr src, uint size)
		{
			if (ShouldFlushICache)
			{
				byte[] array = ((IntPtr.Size >= 8) ? _FlushCache64 : _FlushCache32);
				fixed (byte* ptr = array)
				{
					DetourHelper.Native.MakeExecutable((IntPtr)ptr, (uint)array.Length);
					(Marshal.GetDelegateForFunctionPointer((IntPtr)ptr, typeof(d_flushicache)) as d_flushicache)(src, size);
				}
			}
		}

		public IntPtr MemAlloc(uint size)
		{
			return Marshal.AllocHGlobal((int)size);
		}

		public void MemFree(IntPtr ptr)
		{
			Marshal.FreeHGlobal(ptr);
		}
	}
	public class DetourNativeLibcPlatform : IDetourNativePlatform
	{
		[Flags]
		private enum MmapProts
		{
			PROT_READ = 1,
			PROT_WRITE = 2,
			PROT_EXEC = 4,
			PROT_NONE = 0,
			PROT_GROWSDOWN = 0x1000000,
			PROT_GROWSUP = 0x2000000
		}

		private readonly IDetourNativePlatform Inner;

		private readonly long _Pagesize;

		public DetourNativeLibcPlatform(IDetourNativePlatform inner)
		{
			Inner = inner;
			PropertyInfo property = typeof(Environment).GetProperty("SystemPageSize");
			if ((object)property == null)
			{
				throw new NotSupportedException("Unsupported runtime");
			}
			_Pagesize = (int)property.GetValue(null, new object[0]);
		}

		private void SetMemPerms(IntPtr start, ulong len, MmapProts prot)
		{
			long pagesize = _Pagesize;
			long num = (long)start & ~(pagesize - 1);
			long num2 = ((long)start + (long)len + pagesize - 1) & ~(pagesize - 1);
			if (mprotect((IntPtr)num, (IntPtr)(num2 - num), prot) != 0)
			{
				throw new Win32Exception();
			}
		}

		public void MakeWritable(IntPtr src, uint size)
		{
			SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC);
		}

		public void MakeExecutable(IntPtr src, uint size)
		{
			SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC);
		}

		public void MakeReadWriteExecutable(IntPtr

BepInEx/core/MonoMod.Utils.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Utils;
using MonoMod.Utils.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("MonoMod.Utils.Cil.ILGeneratorProxy")]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2022 0x0ade")]
[assembly: AssemblyDescription("Utilities and smaller MonoMod \"components\" (f.e. ModInterop, DynDll, DynData). Can be used for your own mods. Required by all other MonoMod components.")]
[assembly: AssemblyFileVersion("22.1.29.1")]
[assembly: AssemblyInformationalVersion("22.01.29.01")]
[assembly: AssemblyProduct("MonoMod.Utils")]
[assembly: AssemblyTitle("MonoMod.Utils")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("22.1.29.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison)
	{
		return self.Replace(oldValue, newValue);
	}

	public static bool Contains(this string self, string value, StringComparison comparison)
	{
		return self.Contains(value);
	}

	public static int GetHashCode(this string self, StringComparison comparison)
	{
		return self.GetHashCode();
	}

	public static int IndexOf(this string self, char value, StringComparison comparison)
	{
		return self.IndexOf(value);
	}

	public static int IndexOf(this string self, string value, StringComparison comparison)
	{
		return self.IndexOf(value);
	}

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	public class IgnoresAccessChecksToAttribute : Attribute
	{
		public string AssemblyName { get; }

		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
			AssemblyName = assemblyName;
		}
	}
}
namespace MonoMod
{
	internal static class MMDbgLog
	{
		public static readonly string Tag;

		public static TextWriter Writer;

		public static bool Debugging;

		static MMDbgLog()
		{
			Tag = typeof(MMDbgLog).Assembly.GetName().Name;
			if (!(Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1"))
			{
				string? environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG");
				bool? obj;
				if (environmentVariable == null)
				{
					obj = null;
				}
				else
				{
					string text = environmentVariable.ToLower(CultureInfo.InvariantCulture);
					obj = ((text != null) ? new bool?(MultiTargetShims.Contains(text, Tag.ToLower(CultureInfo.InvariantCulture), StringComparison.Ordinal)) : null);
				}
				bool? flag = obj;
				if (!flag.GetValueOrDefault())
				{
					return;
				}
			}
			Start();
		}

		public static void WaitForDebugger()
		{
			if (!Debugging)
			{
				Debugging = true;
				Debugger.Launch();
				Thread.Sleep(6000);
				Debugger.Break();
			}
		}

		public static void Start()
		{
			if (Writer != null)
			{
				return;
			}
			string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH");
			if (text == "-")
			{
				Writer = Console.Out;
				return;
			}
			if (string.IsNullOrEmpty(text))
			{
				text = "mmdbglog.txt";
			}
			text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text));
			try
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
			catch
			{
			}
			try
			{
				string directoryName = Path.GetDirectoryName(text);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8);
			}
			catch
			{
			}
		}

		public static void Log(string str)
		{
			TextWriter writer = Writer;
			if (writer != null)
			{
				writer.WriteLine(str);
				writer.Flush();
			}
		}

		public static T Log<T>(string str, T value)
		{
			TextWriter writer = Writer;
			if (writer == null)
			{
				return value;
			}
			writer.WriteLine(string.Format(CultureInfo.InvariantCulture, str, new object[1] { value }));
			writer.Flush();
			return value;
		}
	}
}
namespace MonoMod.ModInterop
{
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class ModExportNameAttribute : Attribute
	{
		public string Name;

		public ModExportNameAttribute(string name)
		{
			Name = name;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field)]
	public sealed class ModImportNameAttribute : Attribute
	{
		public string Name;

		public ModImportNameAttribute(string name)
		{
			Name = name;
		}
	}
	public static class ModInteropManager
	{
		private static HashSet<Type> Registered = new HashSet<Type>();

		private static Dictionary<string, List<MethodInfo>> Methods = new Dictionary<string, List<MethodInfo>>();

		private static List<FieldInfo> Fields = new List<FieldInfo>();

		public static void ModInterop(this Type type)
		{
			if (Registered.Contains(type))
			{
				return;
			}
			Registered.Add(type);
			string name = type.Assembly.GetName().Name;
			object[] customAttributes = type.GetCustomAttributes(typeof(ModExportNameAttribute), inherit: false);
			for (int i = 0; i < customAttributes.Length; i++)
			{
				name = ((ModExportNameAttribute)customAttributes[i]).Name;
			}
			FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (typeof(Delegate).IsAssignableFrom(fieldInfo.FieldType))
				{
					Fields.Add(fieldInfo);
				}
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public);
			foreach (MethodInfo method in methods)
			{
				method.RegisterModExport();
				method.RegisterModExport(name);
			}
			foreach (FieldInfo field in Fields)
			{
				if (!Methods.TryGetValue(field.GetModImportName(), out var value))
				{
					field.SetValue(null, null);
					continue;
				}
				bool flag = false;
				foreach (MethodInfo item in value)
				{
					try
					{
						field.SetValue(null, Delegate.CreateDelegate(field.FieldType, null, item));
						flag = true;
					}
					catch
					{
						continue;
					}
					break;
				}
				if (!flag)
				{
					field.SetValue(null, null);
				}
			}
		}

		public static void RegisterModExport(this MethodInfo method, string prefix = null)
		{
			if (!method.IsPublic || !method.IsStatic)
			{
				throw new MemberAccessException("Utility must be public static");
			}
			string text = method.Name;
			if (!string.IsNullOrEmpty(prefix))
			{
				text = prefix + "." + text;
			}
			if (!Methods.TryGetValue(text, out var value))
			{
				value = (Methods[text] = new List<MethodInfo>());
			}
			if (!value.Contains(method))
			{
				value.Add(method);
			}
		}

		private static string GetModImportName(this FieldInfo field)
		{
			object[] customAttributes = field.GetCustomAttributes(typeof(ModImportNameAttribute), inherit: false);
			int num = 0;
			if (num < customAttributes.Length)
			{
				return ((ModImportNameAttribute)customAttributes[num]).Name;
			}
			customAttributes = field.DeclaringType.GetCustomAttributes(typeof(ModImportNameAttribute), inherit: false);
			num = 0;
			if (num < customAttributes.Length)
			{
				return ((ModImportNameAttribute)customAttributes[num]).Name + "." + field.Name;
			}
			return field.Name;
		}
	}
}
namespace MonoMod.Utils
{
	public sealed class DynData<TTarget> : IDisposable where TTarget : class
	{
		private class _Data_ : IDisposable
		{
			public readonly Dictionary<string, Func<TTarget, object>> Getters = new Dictionary<string, Func<TTarget, object>>();

			public readonly Dictionary<string, Action<TTarget, object>> Setters = new Dictionary<string, Action<TTarget, object>>();

			public readonly Dictionary<string, object> Data = new Dictionary<string, object>();

			public readonly HashSet<string> Disposable = new HashSet<string>();

			~_Data_()
			{
				Dispose();
			}

			public void Dispose()
			{
				lock (Data)
				{
					if (Data.Count == 0)
					{
						return;
					}
					foreach (string item in Disposable)
					{
						if (Data.TryGetValue(item, out var value) && value is IDisposable disposable)
						{
							disposable.Dispose();
						}
					}
					Disposable.Clear();
					Data.Clear();
				}
			}
		}

		private static int CreationsInProgress;

		private static readonly object[] _NoArgs;

		private static readonly _Data_ _DataStatic;

		private static readonly Dictionary<WeakReference, _Data_> _DataMap;

		private static readonly HashSet<WeakReference> _DataMapDead;

		private static readonly Dictionary<string, Func<TTarget, object>> _SpecialGetters;

		private static readonly Dictionary<string, Action<TTarget, object>> _SpecialSetters;

		private readonly WeakReference Weak;

		private TTarget KeepAlive;

		private readonly _Data_ _Data;

		public Dictionary<string, Func<TTarget, object>> Getters => _Data.Getters;

		public Dictionary<string, Action<TTarget, object>> Setters => _Data.Setters;

		public Dictionary<string, object> Data => _Data.Data;

		public bool IsAlive
		{
			get
			{
				if (Weak != null)
				{
					return Weak.SafeGetIsAlive();
				}
				return true;
			}
		}

		public TTarget Target => Weak?.SafeGetTarget() as TTarget;

		public object this[string name]
		{
			get
			{
				if (_SpecialGetters.TryGetValue(name, out var value) || Getters.TryGetValue(name, out value))
				{
					return value(Weak?.SafeGetTarget() as TTarget);
				}
				if (Data.TryGetValue(name, out var value2))
				{
					return value2;
				}
				return null;
			}
			set
			{
				if (_SpecialSetters.TryGetValue(name, out var value2) || Setters.TryGetValue(name, out value2))
				{
					value2(Weak?.SafeGetTarget() as TTarget, value);
					return;
				}
				object obj;
				if (_Data.Disposable.Contains(name) && (obj = this[name]) != null && obj is IDisposable disposable)
				{
					disposable.Dispose();
				}
				Data[name] = value;
			}
		}

		public static event Action<DynData<TTarget>, TTarget> OnInitialize;

		static DynData()
		{
			CreationsInProgress = 0;
			_NoArgs = new object[0];
			_DataStatic = new _Data_();
			_DataMap = new Dictionary<WeakReference, _Data_>(new WeakReferenceComparer());
			_DataMapDead = new HashSet<WeakReference>();
			_SpecialGetters = new Dictionary<string, Func<TTarget, object>>();
			_SpecialSetters = new Dictionary<string, Action<TTarget, object>>();
			GCListener.OnCollect += delegate
			{
				if (CreationsInProgress != 0)
				{
					return;
				}
				lock (_DataMap)
				{
					foreach (KeyValuePair<WeakReference, _Data_> item in _DataMap)
					{
						if (!item.Key.SafeGetIsAlive())
						{
							_DataMapDead.Add(item.Key);
							item.Value.Dispose();
						}
					}
					foreach (WeakReference item2 in _DataMapDead)
					{
						_DataMap.Remove(item2);
					}
					_DataMapDead.Clear();
				}
			};
			FieldInfo[] fields = typeof(TTarget).GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo field in fields)
			{
				string name = field.Name;
				_SpecialGetters[name] = (TTarget obj) => field.GetValue(obj);
				_SpecialSetters[name] = delegate(TTarget obj, object value)
				{
					field.SetValue(obj, value);
				};
			}
			PropertyInfo[] properties = typeof(TTarget).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo propertyInfo in properties)
			{
				string name2 = propertyInfo.Name;
				MethodInfo get = propertyInfo.GetGetMethod(nonPublic: true);
				if ((object)get != null)
				{
					_SpecialGetters[name2] = (TTarget obj) => get.Invoke(obj, _NoArgs);
				}
				MethodInfo set = propertyInfo.GetSetMethod(nonPublic: true);
				if ((object)set != null)
				{
					_SpecialSetters[name2] = delegate(TTarget obj, object value)
					{
						set.Invoke(obj, new object[1] { value });
					};
				}
			}
		}

		public DynData()
			: this((TTarget)null, keepAlive: false)
		{
		}

		public DynData(TTarget obj)
			: this(obj, keepAlive: true)
		{
		}

		public DynData(TTarget obj, bool keepAlive)
		{
			if (obj != null)
			{
				WeakReference weakReference = new WeakReference(obj);
				WeakReference key = weakReference;
				CreationsInProgress++;
				lock (_DataMap)
				{
					if (!_DataMap.TryGetValue(key, out _Data))
					{
						_Data = new _Data_();
						_DataMap.Add(key, _Data);
					}
				}
				CreationsInProgress--;
				Weak = weakReference;
				if (keepAlive)
				{
					KeepAlive = obj;
				}
			}
			else
			{
				_Data = _DataStatic;
			}
			DynData<TTarget>.OnInitialize?.Invoke(this, obj);
		}

		public T Get<T>(string name)
		{
			return (T)this[name];
		}

		public void Set<T>(string name, T value)
		{
			this[name] = value;
		}

		public void RegisterProperty(string name, Func<TTarget, object> getter, Action<TTarget, object> setter)
		{
			Getters[name] = getter;
			Setters[name] = setter;
		}

		public void UnregisterProperty(string name)
		{
			Getters.Remove(name);
			Setters.Remove(name);
		}

		private void Dispose(bool disposing)
		{
			KeepAlive = null;
		}

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

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}
	}
	public static class Extensions
	{
		private static readonly Type t_StateMachineAttribute = typeof(object).Assembly.GetType("System.Runtime.CompilerServices.StateMachineAttribute");

		private static readonly PropertyInfo p_StateMachineType = t_StateMachineAttribute?.GetProperty("StateMachineType");

		private static readonly Type t_Code = typeof(Code);

		private static readonly Type t_OpCodes = typeof(OpCodes);

		private static readonly Dictionary<int, OpCode> _ToLongOp = new Dictionary<int, OpCode>();

		private static readonly Dictionary<int, OpCode> _ToShortOp = new Dictionary<int, OpCode>();

		private static readonly object[] _NoArgs = new object[0];

		private static readonly Dictionary<Type, FieldInfo> fmap_mono_assembly = new Dictionary<Type, FieldInfo>();

		private static readonly bool _MonoAssemblyNameHasArch = new AssemblyName("Dummy, ProcessorArchitecture=MSIL").ProcessorArchitecture == ProcessorArchitecture.MSIL;

		private static readonly Type _RTDynamicMethod = typeof(DynamicMethod).GetNestedType("RTDynamicMethod", BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly Type t_ParamArrayAttribute = typeof(ParamArrayAttribute);

		private static readonly FieldInfo f_GenericParameter_position = typeof(GenericParameter).GetField("position", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo f_GenericParameter_type = typeof(GenericParameter).GetField("type", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly Dictionary<Type, int> _GetManagedSizeCache = new Dictionary<Type, int> { 
		{
			typeof(void),
			0
		} };

		private static MethodInfo _GetManagedSizeHelper;

		private static readonly Dictionary<MethodBase, Func<IntPtr>> _GetLdftnPointerCache = new Dictionary<MethodBase, Func<IntPtr>>();

		public static string ToHexadecimalString(this byte[] data)
		{
			return MultiTargetShims.Replace(BitConverter.ToString(data), "-", string.Empty, StringComparison.Ordinal);
		}

		public static T InvokePassing<T>(this MulticastDelegate md, T val, params object[] args)
		{
			if ((object)md == null)
			{
				return val;
			}
			object[] array = new object[args.Length + 1];
			array[0] = val;
			Array.Copy(args, 0, array, 1, args.Length);
			Delegate[] invocationList = md.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				array[0] = invocationList[i].DynamicInvoke(array);
			}
			return (T)array[0];
		}

		public static bool InvokeWhileTrue(this MulticastDelegate md, params object[] args)
		{
			if ((object)md == null)
			{
				return true;
			}
			Delegate[] invocationList = md.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				if (!(bool)invocationList[i].DynamicInvoke(args))
				{
					return false;
				}
			}
			return true;
		}

		public static bool InvokeWhileFalse(this MulticastDelegate md, params object[] args)
		{
			if ((object)md == null)
			{
				return false;
			}
			Delegate[] invocationList = md.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				if ((bool)invocationList[i].DynamicInvoke(args))
				{
					return true;
				}
			}
			return false;
		}

		public static T InvokeWhileNull<T>(this MulticastDelegate md, params object[] args) where T : class
		{
			if ((object)md == null)
			{
				return null;
			}
			Delegate[] invocationList = md.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				T val = (T)invocationList[i].DynamicInvoke(args);
				if (val != null)
				{
					return val;
				}
			}
			return null;
		}

		public static string SpacedPascalCase(this string input)
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < input.Length; i++)
			{
				char c = input[i];
				if (i > 0 && char.IsUpper(c))
				{
					stringBuilder.Append(' ');
				}
				stringBuilder.Append(c);
			}
			return stringBuilder.ToString();
		}

		public static string ReadNullTerminatedString(this BinaryReader stream)
		{
			string text = "";
			char c;
			while ((c = stream.ReadChar()) != 0)
			{
				text += c;
			}
			return text;
		}

		public static void WriteNullTerminatedString(this BinaryWriter stream, string text)
		{
			if (text != null)
			{
				foreach (char ch in text)
				{
					stream.Write(ch);
				}
			}
			stream.Write('\0');
		}

		public static T CastDelegate<T>(this Delegate source) where T : class
		{
			return source.CastDelegate(typeof(T)) as T;
		}

		public static Delegate CastDelegate(this Delegate source, Type type)
		{
			if ((object)source == null)
			{
				return null;
			}
			Delegate[] invocationList = source.GetInvocationList();
			if (invocationList.Length == 1)
			{
				return CreateDelegate(invocationList[0].Method, type, invocationList[0].Target);
			}
			Delegate[] array = new Delegate[invocationList.Length];
			for (int i = 0; i < invocationList.Length; i++)
			{
				array[i] = invocationList[i].CastDelegate(type);
			}
			return Delegate.Combine(array);
		}

		public static bool TryCastDelegate<T>(this Delegate source, out T result) where T : class
		{
			if (source is T val)
			{
				result = val;
				return true;
			}
			Delegate result2;
			bool result3 = source.TryCastDelegate(typeof(T), out result2);
			result = result2 as T;
			return result3;
		}

		public static bool TryCastDelegate(this Delegate source, Type type, out Delegate result)
		{
			result = null;
			if ((object)source == null)
			{
				return false;
			}
			try
			{
				Delegate[] invocationList = source.GetInvocationList();
				if (invocationList.Length == 1)
				{
					result = CreateDelegate(invocationList[0].Method, type, invocationList[0].Target);
					return true;
				}
				Delegate[] array = new Delegate[invocationList.Length];
				for (int i = 0; i < invocationList.Length; i++)
				{
					array[i] = invocationList[i].CastDelegate(type);
				}
				result = Delegate.Combine(array);
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static void LogDetailed(this Exception e, string tag = null)
		{
			if (tag == null)
			{
				Console.WriteLine("--------------------------------");
				Console.WriteLine("Detailed exception log:");
			}
			for (Exception ex = e; ex != null; ex = ex.InnerException)
			{
				Console.WriteLine("--------------------------------");
				Console.WriteLine(ex.GetType().FullName + ": " + ex.Message + "\n" + ex.StackTrace);
				if (ex is ReflectionTypeLoadException ex2)
				{
					for (int i = 0; i < ex2.Types.Length; i++)
					{
						Console.WriteLine("ReflectionTypeLoadException.Types[" + i + "]: " + ex2.Types[i]);
					}
					for (int j = 0; j < ex2.LoaderExceptions.Length; j++)
					{
						ex2.LoaderExceptions[j].LogDetailed(tag + ((tag == null) ? "" : ", ") + "rtle:" + j);
					}
				}
				if (ex is TypeLoadException)
				{
					Console.WriteLine("TypeLoadException.TypeName: " + ((TypeLoadException)ex).TypeName);
				}
				if (ex is BadImageFormatException)
				{
					Console.WriteLine("BadImageFormatException.FileName: " + ((BadImageFormatException)ex).FileName);
				}
			}
		}

		public static MethodInfo GetStateMachineTarget(this MethodInfo method)
		{
			if ((object)p_StateMachineType == null)
			{
				return null;
			}
			object[] customAttributes = method.GetCustomAttributes(inherit: false);
			for (int i = 0; i < customAttributes.Length; i++)
			{
				Attribute attribute = (Attribute)customAttributes[i];
				if (t_StateMachineAttribute.IsCompatible(attribute.GetType()))
				{
					return (p_StateMachineType.GetValue(attribute, null) as Type)?.GetMethod("MoveNext", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				}
			}
			return null;
		}

		public static MethodBase GetActualGenericMethodDefinition(this MethodInfo method)
		{
			return (method.IsGenericMethod ? method.GetGenericMethodDefinition() : method).GetUnfilledMethodOnGenericType();
		}

		public static MethodBase GetUnfilledMethodOnGenericType(this MethodBase method)
		{
			if ((object)method.DeclaringType != null && method.DeclaringType.IsGenericType)
			{
				Type genericTypeDefinition = method.DeclaringType.GetGenericTypeDefinition();
				method = MethodBase.GetMethodFromHandle(method.MethodHandle, genericTypeDefinition.TypeHandle);
			}
			return method;
		}

		public static bool Is(this MemberReference member, string fullName)
		{
			if (member == null)
			{
				return false;
			}
			return MultiTargetShims.Replace(member.FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal);
		}

		public static bool Is(this MemberReference member, string typeFullName, string name)
		{
			if (member == null)
			{
				return false;
			}
			if (MultiTargetShims.Replace(((MemberReference)member.DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal))
			{
				return member.Name == name;
			}
			return false;
		}

		public static bool Is(this MemberReference member, Type type, string name)
		{
			if (member == null)
			{
				return false;
			}
			if (MultiTargetShims.Replace(((MemberReference)member.DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal))
			{
				return member.Name == name;
			}
			return false;
		}

		public static bool Is(this MethodReference method, string fullName)
		{
			if (method == null)
			{
				return false;
			}
			if (MultiTargetShims.Contains(fullName, " ", StringComparison.Ordinal))
			{
				if (MultiTargetShims.Replace(method.GetID(null, null, withType: true, simple: true), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal))
				{
					return true;
				}
				if (MultiTargetShims.Replace(method.GetID(), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal))
				{
					return true;
				}
			}
			return MultiTargetShims.Replace(((MemberReference)method).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal);
		}

		public static bool Is(this MethodReference method, string typeFullName, string name)
		{
			if (method == null)
			{
				return false;
			}
			if (MultiTargetShims.Contains(name, " ", StringComparison.Ordinal) && MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal) && MultiTargetShims.Replace(method.GetID(null, null, withType: false), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(name, "+", "/", StringComparison.Ordinal))
			{
				return true;
			}
			if (MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal))
			{
				return ((MemberReference)method).Name == name;
			}
			return false;
		}

		public static bool Is(this MethodReference method, Type type, string name)
		{
			if (method == null)
			{
				return false;
			}
			if (MultiTargetShims.Contains(name, " ", StringComparison.Ordinal) && MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal) && MultiTargetShims.Replace(method.GetID(null, null, withType: false), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(name, "+", "/", StringComparison.Ordinal))
			{
				return true;
			}
			if (MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal))
			{
				return ((MemberReference)method).Name == name;
			}
			return false;
		}

		public static void ReplaceOperands(this ILProcessor il, object from, object to)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<Instruction> enumerator = il.Body.Instructions.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Instruction current = enumerator.Current;
					if (current.Operand?.Equals(from) ?? (from == null))
					{
						current.Operand = to;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public static FieldReference Import(this ILProcessor il, FieldInfo field)
		{
			return ((MemberReference)il.Body.Method).Module.ImportReference(field);
		}

		public static MethodReference Import(this ILProcessor il, MethodBase method)
		{
			return ((MemberReference)il.Body.Method).Module.ImportReference(method);
		}

		public static TypeReference Import(this ILProcessor il, Type type)
		{
			return ((MemberReference)il.Body.Method).Module.ImportReference(type);
		}

		public static MemberReference Import(this ILProcessor il, MemberInfo member)
		{
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (!(member is FieldInfo field))
			{
				if (!(member is MethodBase method))
				{
					if (member is Type type)
					{
						return (MemberReference)(object)il.Import(type);
					}
					throw new NotSupportedException("Unsupported member type " + member.GetType().FullName);
				}
				return (MemberReference)(object)il.Import(method);
			}
			return (MemberReference)(object)il.Import(field);
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, FieldInfo field)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return il.Create(opcode, il.Import(field));
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, MethodBase method)
		{
			//IL_0012: 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)
			if (method is DynamicMethod)
			{
				return il.Create(opcode, (object)method);
			}
			return il.Create(opcode, il.Import(method));
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, Type type)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return il.Create(opcode, il.Import(type));
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, object operand)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Instruction obj = il.Create(OpCodes.Nop);
			obj.OpCode = opcode;
			obj.Operand = operand;
			return obj;
		}

		public static Instruction Create(this ILProcessor il, OpCode opcode, MemberInfo member)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (!(member is FieldInfo field))
			{
				if (!(member is MethodBase method))
				{
					if (member is Type type)
					{
						return il.Create(opcode, type);
					}
					throw new NotSupportedException("Unsupported member type " + member.GetType().FullName);
				}
				return il.Create(opcode, method);
			}
			return il.Create(opcode, field);
		}

		public static void Emit(this ILProcessor il, OpCode opcode, FieldInfo field)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(opcode, il.Import(field));
		}

		public static void Emit(this ILProcessor il, OpCode opcode, MethodBase method)
		{
			//IL_0012: 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)
			if (method is DynamicMethod)
			{
				il.Emit(opcode, (object)method);
			}
			else
			{
				il.Emit(opcode, il.Import(method));
			}
		}

		public static void Emit(this ILProcessor il, OpCode opcode, Type type)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(opcode, il.Import(type));
		}

		public static void Emit(this ILProcessor il, OpCode opcode, MemberInfo member)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (!(member is FieldInfo field))
			{
				if (!(member is MethodBase method))
				{
					if (!(member is Type type))
					{
						throw new NotSupportedException("Unsupported member type " + member.GetType().FullName);
					}
					il.Emit(opcode, type);
				}
				else
				{
					il.Emit(opcode, method);
				}
			}
			else
			{
				il.Emit(opcode, field);
			}
		}

		public static void Emit(this ILProcessor il, OpCode opcode, object operand)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			il.Append(il.Create(opcode, operand));
		}

		public static TypeDefinition SafeResolve(this TypeReference r)
		{
			try
			{
				return r.Resolve();
			}
			catch
			{
				return null;
			}
		}

		public static FieldDefinition SafeResolve(this FieldReference r)
		{
			try
			{
				return r.Resolve();
			}
			catch
			{
				return null;
			}
		}

		public static MethodDefinition SafeResolve(this MethodReference r)
		{
			try
			{
				return r.Resolve();
			}
			catch
			{
				return null;
			}
		}

		public static PropertyDefinition SafeResolve(this PropertyReference r)
		{
			try
			{
				return r.Resolve();
			}
			catch
			{
				return null;
			}
		}

		public static CustomAttribute GetCustomAttribute(this ICustomAttributeProvider cap, string attribute)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (cap == null || !cap.HasCustomAttributes)
			{
				return null;
			}
			Enumerator<CustomAttribute> enumerator = cap.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current = enumerator.Current;
					if (((MemberReference)current.AttributeType).FullName == attribute)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static bool HasCustomAttribute(this ICustomAttributeProvider cap, string attribute)
		{
			return cap.GetCustomAttribute(attribute) != null;
		}

		public static int GetInt(this Instruction instr)
		{
			//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_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: 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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			OpCode opCode = instr.OpCode;
			if (opCode == OpCodes.Ldc_I4_M1)
			{
				return -1;
			}
			if (opCode == OpCodes.Ldc_I4_0)
			{
				return 0;
			}
			if (opCode == OpCodes.Ldc_I4_1)
			{
				return 1;
			}
			if (opCode == OpCodes.Ldc_I4_2)
			{
				return 2;
			}
			if (opCode == OpCodes.Ldc_I4_3)
			{
				return 3;
			}
			if (opCode == OpCodes.Ldc_I4_4)
			{
				return 4;
			}
			if (opCode == OpCodes.Ldc_I4_5)
			{
				return 5;
			}
			if (opCode == OpCodes.Ldc_I4_6)
			{
				return 6;
			}
			if (opCode == OpCodes.Ldc_I4_7)
			{
				return 7;
			}
			if (opCode == OpCodes.Ldc_I4_8)
			{
				return 8;
			}
			if (opCode == OpCodes.Ldc_I4_S)
			{
				return (sbyte)instr.Operand;
			}
			return (int)instr.Operand;
		}

		public static int? GetIntOrNull(this Instruction instr)
		{
			//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_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			OpCode opCode = instr.OpCode;
			if (opCode == OpCodes.Ldc_I4_M1)
			{
				return -1;
			}
			if (opCode == OpCodes.Ldc_I4_0)
			{
				return 0;
			}
			if (opCode == OpCodes.Ldc_I4_1)
			{
				return 1;
			}
			if (opCode == OpCodes.Ldc_I4_2)
			{
				return 2;
			}
			if (opCode == OpCodes.Ldc_I4_3)
			{
				return 3;
			}
			if (opCode == OpCodes.Ldc_I4_4)
			{
				return 4;
			}
			if (opCode == OpCodes.Ldc_I4_5)
			{
				return 5;
			}
			if (opCode == OpCodes.Ldc_I4_6)
			{
				return 6;
			}
			if (opCode == OpCodes.Ldc_I4_7)
			{
				return 7;
			}
			if (opCode == OpCodes.Ldc_I4_8)
			{
				return 8;
			}
			if (opCode == OpCodes.Ldc_I4_S)
			{
				return (sbyte)instr.Operand;
			}
			if (opCode == OpCodes.Ldc_I4)
			{
				return (int)instr.Operand;
			}
			return null;
		}

		public static bool IsBaseMethodCall(this MethodBody body, MethodReference called)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			MethodDefinition method = body.Method;
			if (called == null)
			{
				return false;
			}
			TypeReference val = ((MemberReference)called).DeclaringType;
			while (val is TypeSpecification)
			{
				val = ((TypeSpecification)val).ElementType;
			}
			string patchFullName = ((MemberReference)(object)val).GetPatchFullName();
			bool flag = false;
			try
			{
				TypeDefinition val2 = method.DeclaringType;
				while ((val2 = val2.BaseType?.SafeResolve()) != null)
				{
					if (((MemberReference)(object)val2).GetPatchFullName() == patchFullName)
					{
						flag = true;
						break;
					}
				}
			}
			catch
			{
				flag = ((MemberReference)(object)method.DeclaringType).GetPatchFullName() == patchFullName;
			}
			if (!flag)
			{
				return false;
			}
			return true;
		}

		public static bool IsCallvirt(this MethodReference method)
		{
			if (!method.HasThis)
			{
				return false;
			}
			if (((MemberReference)method).DeclaringType.IsValueType)
			{
				return false;
			}
			return true;
		}

		public static bool IsStruct(this TypeReference type)
		{
			if (!type.IsValueType)
			{
				return false;
			}
			if (type.IsPrimitive)
			{
				return false;
			}
			return true;
		}

		public static OpCode ToLongOp(this OpCode op)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected I4, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected I4, but got Unknown
			//IL_00a0: 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)
			string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code);
			if (!name.EndsWith("_S", StringComparison.Ordinal))
			{
				return op;
			}
			lock (_ToLongOp)
			{
				if (_ToLongOp.TryGetValue((int)((OpCode)(ref op)).Code, out var value))
				{
					return value;
				}
				return _ToLongOp[(int)((OpCode)(ref op)).Code] = (OpCode)(((??)(OpCode?)t_OpCodes.GetField(name.Substring(0, name.Length - 2))?.GetValue(null)) ?? op);
			}
		}

		public static OpCode ToShortOp(this OpCode op)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected I4, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected I4, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code);
			if (name.EndsWith("_S", StringComparison.Ordinal))
			{
				return op;
			}
			lock (_ToShortOp)
			{
				if (_ToShortOp.TryGetValue((int)((OpCode)(ref op)).Code, out var value))
				{
					return value;
				}
				return _ToShortOp[(int)((OpCode)(ref op)).Code] = (OpCode)(((??)(OpCode?)t_OpCodes.GetField(name + "_S")?.GetValue(null)) ?? op);
			}
		}

		public static void RecalculateILOffsets(this MethodDefinition method)
		{
			if (method.HasBody)
			{
				int num = 0;
				for (int i = 0; i < method.Body.Instructions.Count; i++)
				{
					Instruction val = method.Body.Instructions[i];
					val.Offset = num;
					num += val.GetSize();
				}
			}
		}

		public static void FixShortLongOps(this MethodDefinition method)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			if (!method.HasBody)
			{
				return;
			}
			for (int i = 0; i < method.Body.Instructions.Count; i++)
			{
				Instruction val = method.Body.Instructions[i];
				if (val.Operand is Instruction)
				{
					val.OpCode = val.OpCode.ToLongOp();
				}
			}
			method.RecalculateILOffsets();
			bool flag;
			do
			{
				flag = false;
				for (int j = 0; j < method.Body.Instructions.Count; j++)
				{
					Instruction val2 = method.Body.Instructions[j];
					object operand = val2.Operand;
					Instruction val3 = (Instruction)((operand is Instruction) ? operand : null);
					if (val3 != null)
					{
						int num = val3.Offset - (val2.Offset + val2.GetSize());
						if (num == (sbyte)num)
						{
							OpCode opCode = val2.OpCode;
							val2.OpCode = val2.OpCode.ToShortOp();
							flag = opCode != val2.OpCode;
						}
					}
				}
			}
			while (flag);
		}

		public static bool Is(this MemberInfo minfo, MemberReference mref)
		{
			return mref.Is(minfo);
		}

		public static bool Is(this MemberReference mref, MemberInfo minfo)
		{
			if (mref == null)
			{
				return false;
			}
			TypeReference val = mref.DeclaringType;
			if (((val != null) ? ((MemberReference)val).FullName : null) == "<Module>")
			{
				val = null;
			}
			GenericParameter val2 = (GenericParameter)(object)((mref is GenericParameter) ? mref : null);
			if (val2 != null)
			{
				if (!(minfo is Type type))
				{
					return false;
				}
				if (!type.IsGenericParameter)
				{
					IGenericParameterProvider owner = val2.Owner;
					IGenericInstance val3 = (IGenericInstance)(object)((owner is IGenericInstance) ? owner : null);
					if (val3 != null)
					{
						return ((MemberReference)(object)val3.GenericArguments[val2.Position]).Is(type);
					}
					return false;
				}
				return val2.Position == type.GenericParameterPosition;
			}
			if ((object)minfo.DeclaringType != null)
			{
				if (val == null)
				{
					return false;
				}
				Type type2 = minfo.DeclaringType;
				if (minfo is Type && type2.IsGenericType && !type2.IsGenericTypeDefinition)
				{
					type2 = type2.GetGenericTypeDefinition();
				}
				if (!((MemberReference)(object)val).Is(type2))
				{
					return false;
				}
			}
			else if (val != null)
			{
				return false;
			}
			if (!(mref is TypeSpecification) && mref.Name != minfo.Name)
			{
				return false;
			}
			TypeReference val4 = (TypeReference)(object)((mref is TypeReference) ? mref : null);
			if (val4 != null)
			{
				if (!(minfo is Type type3))
				{
					return false;
				}
				if (type3.IsGenericParameter)
				{
					return false;
				}
				GenericInstanceType val5 = (GenericInstanceType)(object)((mref is GenericInstanceType) ? mref : null);
				if (val5 != null)
				{
					if (!type3.IsGenericType)
					{
						return false;
					}
					Collection<TypeReference> genericArguments = val5.GenericArguments;
					Type[] genericArguments2 = type3.GetGenericArguments();
					if (genericArguments.Count != genericArguments2.Length)
					{
						return false;
					}
					for (int i = 0; i < genericArguments.Count; i++)
					{
						if (!((MemberReference)(object)genericArguments[i]).Is(genericArguments2[i]))
						{
							return false;
						}
					}
					return ((MemberReference)(object)((TypeSpecification)val5).ElementType).Is(type3.GetGenericTypeDefinition());
				}
				if (val4.HasGenericParameters)
				{
					if (!type3.IsGenericType)
					{
						return false;
					}
					Collection<GenericParameter> genericParameters = val4.GenericParameters;
					Type[] genericArguments3 = type3.GetGenericArguments();
					if (genericParameters.Count != genericArguments3.Length)
					{
						return false;
					}
					for (int j = 0; j < genericParameters.Count; j++)
					{
						if (!((MemberReference)(object)genericParameters[j]).Is(genericArguments3[j]))
						{
							return false;
						}
					}
				}
				else if (type3.IsGenericType)
				{
					return false;
				}
				ArrayType val6 = (ArrayType)(object)((mref is ArrayType) ? mref : null);
				if (val6 != null)
				{
					if (!type3.IsArray)
					{
						return false;
					}
					if (val6.Dimensions.Count == type3.GetArrayRank())
					{
						return ((MemberReference)(object)((TypeSpecification)val6).ElementType).Is(type3.GetElementType());
					}
					return false;
				}
				ByReferenceType val7 = (ByReferenceType)(object)((mref is ByReferenceType) ? mref : null);
				if (val7 != null)
				{
					if (!type3.IsByRef)
					{
						return false;
					}
					return ((MemberReference)(object)((TypeSpecification)val7).ElementType).Is(type3.GetElementType());
				}
				PointerType val8 = (PointerType)(object)((mref is PointerType) ? mref : null);
				if (val8 != null)
				{
					if (!type3.IsPointer)
					{
						return false;
					}
					return ((MemberReference)(object)((TypeSpecification)val8).ElementType).Is(type3.GetElementType());
				}
				TypeSpecification val9 = (TypeSpecification)(object)((mref is TypeSpecification) ? mref : null);
				if (val9 != null)
				{
					return ((MemberReference)(object)val9.ElementType).Is(type3.HasElementType ? type3.GetElementType() : type3);
				}
				if (val != null)
				{
					return mref.Name == type3.Name;
				}
				return mref.FullName == MultiTargetShims.Replace(type3.FullName, "+", "/", StringComparison.Ordinal);
			}
			if (minfo is Type)
			{
				return false;
			}
			MethodReference methodRef = (MethodReference)(object)((mref is MethodReference) ? mref : null);
			if (methodRef != null)
			{
				if (!(minfo is MethodBase methodBase))
				{
					return false;
				}
				Collection<ParameterDefinition> parameters = methodRef.Parameters;
				ParameterInfo[] parameters2 = methodBase.GetParameters();
				if (parameters.Count != parameters2.Length)
				{
					return false;
				}
				GenericInstanceMethod val10 = (GenericInstanceMethod)(object)((mref is GenericInstanceMethod) ? mref : null);
				if (val10 != null)
				{
					if (!methodBase.IsGenericMethod)
					{
						return false;
					}
					Collection<TypeReference> genericArguments4 = val10.GenericArguments;
					Type[] genericArguments5 = methodBase.GetGenericArguments();
					if (genericArguments4.Count != genericArguments5.Length)
					{
						return false;
					}
					for (int k = 0; k < genericArguments4.Count; k++)
					{
						if (!((MemberReference)(object)genericArguments4[k]).Is(genericArguments5[k]))
						{
							return false;
						}
					}
					return ((MemberReference)(object)((MethodSpecification)val10).ElementMethod).Is((methodBase as MethodInfo)?.GetGenericMethodDefinition() ?? methodBase);
				}
				if (methodRef.HasGenericParameters)
				{
					if (!methodBase.IsGenericMethod)
					{
						return false;
					}
					Collection<GenericParameter> genericParameters2 = methodRef.GenericParameters;
					Type[] genericArguments6 = methodBase.GetGenericArguments();
					if (genericParameters2.Count != genericArguments6.Length)
					{
						return false;
					}
					for (int l = 0; l < genericParameters2.Count; l++)
					{
						if (!((MemberReference)(object)genericParameters2[l]).Is(genericArguments6[l]))
						{
							return false;
						}
					}
				}
				else if (methodBase.IsGenericMethod)
				{
					return false;
				}
				Relinker relinker = null;
				relinker = delegate(IMetadataTokenProvider paramMemberRef, IGenericParameterProvider ctx)
				{
					TypeReference val15 = (TypeReference)(object)((paramMemberRef is TypeReference) ? paramMemberRef : null);
					return (IMetadataTokenProvider)((val15 == null) ? ((object)paramMemberRef) : ((object)ResolveParameter(val15)));
				};
				if (!((MemberReference)(object)methodRef.ReturnType.Relink(relinker, null)).Is((methodBase as MethodInfo)?.ReturnType ?? typeof(void)) && !((MemberReference)(object)methodRef.ReturnType).Is((methodBase as MethodInfo)?.ReturnType ?? typeof(void)))
				{
					return false;
				}
				for (int m = 0; m < parameters.Count; m++)
				{
					if (!((MemberReference)(object)((ParameterReference)parameters[m]).ParameterType.Relink(relinker, null)).Is(parameters2[m].ParameterType) && !((MemberReference)(object)((ParameterReference)parameters[m]).ParameterType).Is(parameters2[m].ParameterType))
					{
						return false;
					}
				}
				return true;
			}
			if (minfo is MethodInfo)
			{
				return false;
			}
			if (mref is FieldReference != minfo is FieldInfo)
			{
				return false;
			}
			if (mref is PropertyReference != minfo is PropertyInfo)
			{
				return false;
			}
			if (mref is EventReference != minfo is EventInfo)
			{
				return false;
			}
			return true;
			TypeReference ResolveParameter(TypeReference paramTypeRef)
			{
				GenericParameter val11 = (GenericParameter)(object)((paramTypeRef is GenericParameter) ? paramTypeRef : null);
				if (val11 != null)
				{
					if (val11.Owner is MethodReference)
					{
						MethodReference obj = methodRef;
						GenericInstanceMethod val12 = (GenericInstanceMethod)(object)((obj is GenericInstanceMethod) ? obj : null);
						if (val12 != null)
						{
							return val12.GenericArguments[val11.Position];
						}
					}
					IGenericParameterProvider owner2 = val11.Owner;
					TypeReference val13 = (TypeReference)(object)((owner2 is TypeReference) ? owner2 : null);
					if (val13 != null)
					{
						TypeReference declaringType = ((MemberReference)methodRef).DeclaringType;
						GenericInstanceType val14 = (GenericInstanceType)(object)((declaringType is GenericInstanceType) ? declaringType : null);
						if (val14 != null && ((MemberReference)val13).FullName == ((MemberReference)((TypeSpecification)val14).ElementType).FullName)
						{
							return val14.GenericArguments[val11.Position];
						}
					}
					return paramTypeRef;
				}
				if (paramTypeRef == ((MemberReference)methodRef).DeclaringType.GetElementType())
				{
					return ((MemberReference)methodRef).DeclaringType;
				}
				return paramTypeRef;
			}
		}

		public static IMetadataTokenProvider ImportReference(this ModuleDefinition mod, IMetadataTokenProvider mtp)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			if (mtp is TypeReference)
			{
				return (IMetadataTokenProvider)(object)mod.ImportReference((TypeReference)mtp);
			}
			if (mtp is FieldReference)
			{
				return (IMetadataTokenProvider)(object)mod.ImportReference((FieldReference)mtp);
			}
			if (mtp is MethodReference)
			{
				return (IMetadataTokenProvider)(object)mod.ImportReference((MethodReference)mtp);
			}
			return mtp;
		}

		public static void AddRange<T>(this Collection<T> list, IEnumerable<T> other)
		{
			foreach (T item in other)
			{
				list.Add(item);
			}
		}

		public static void AddRange(this IDictionary dict, IDictionary other)
		{
			foreach (DictionaryEntry item in other)
			{
				dict.Add(item.Key, item.Value);
			}
		}

		public static void AddRange<K, V>(this IDictionary<K, V> dict, IDictionary<K, V> other)
		{
			foreach (KeyValuePair<K, V> item in other)
			{
				dict.Add(item.Key, item.Value);
			}
		}

		public static void AddRange<K, V>(this Dictionary<K, V> dict, Dictionary<K, V> other)
		{
			foreach (KeyValuePair<K, V> item in other)
			{
				dict.Add(item.Key, item.Value);
			}
		}

		public static void InsertRange<T>(this Collection<T> list, int index, IEnumerable<T> other)
		{
			foreach (T item in other)
			{
				list.Insert(index++, item);
			}
		}

		public static bool IsCompatible(this Type type, Type other)
		{
			if (!type._IsCompatible(other))
			{
				return other._IsCompatible(type);
			}
			return true;
		}

		private static bool _IsCompatible(this Type type, Type other)
		{
			if ((object)type == other)
			{
				return true;
			}
			if (type.IsAssignableFrom(other))
			{
				return true;
			}
			if (other.IsEnum && type.IsCompatible(Enum.GetUnderlyingType(other)))
			{
				return true;
			}
			if ((other.IsPointer || other.IsByRef) && (object)type == typeof(IntPtr))
			{
				return true;
			}
			return false;
		}

		public static T GetDeclaredMember<T>(this T member) where T : MemberInfo
		{
			if ((object)member.DeclaringType == member.ReflectedType)
			{
				return member;
			}
			int metadataToken = member.MetadataToken;
			MemberInfo[] members = member.DeclaringType.GetMembers((BindingFlags)(-1));
			foreach (MemberInfo memberInfo in members)
			{
				if (memberInfo.MetadataToken == metadataToken)
				{
					return (T)memberInfo;
				}
			}
			return member;
		}

		public unsafe static void SetMonoCorlibInternal(this Assembly asm, bool value)
		{
			if ((object)Type.GetType("Mono.Runtime") == null)
			{
				return;
			}
			Type type = asm?.GetType();
			if ((object)type == null)
			{
				return;
			}
			FieldInfo value2;
			lock (fmap_mono_assembly)
			{
				if (!fmap_mono_assembly.TryGetValue(type, out value2))
				{
					value2 = type.GetField("_mono_assembly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? type.GetField("dynamic_assembly", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					fmap_mono_assembly[type] = value2;
				}
			}
			if ((object)value2 == null)
			{
				return;
			}
			AssemblyName assemblyName = new AssemblyName(asm.FullName);
			lock (ReflectionHelper.AssemblyCache)
			{
				WeakReference value3 = new WeakReference(asm);
				ReflectionHelper.AssemblyCache[asm.GetRuntimeHashedFullName()] = value3;
				ReflectionHelper.AssemblyCache[assemblyName.FullName] = value3;
				ReflectionHelper.AssemblyCache[assemblyName.Name] = value3;
			}
			long num = 0L;
			object value4 = value2.GetValue(asm);
			if (!(value4 is IntPtr intPtr))
			{
				if (value4 is UIntPtr uIntPtr)
				{
					num = (long)(ulong)uIntPtr;
				}
			}
			else
			{
				num = (long)intPtr;
			}
			int num2 = IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + 20 + 4 + 4 + 4 + (_MonoAssemblyNameHasArch ? ((!(typeof(object).Assembly.GetName().Name == "System.Private.CoreLib")) ? ((IntPtr.Size == 4) ? 12 : 16) : ((IntPtr.Size == 4) ? 20 : 24)) : ((typeof(object).Assembly.GetName().Name == "System.Private.CoreLib") ? 16 : 8)) + IntPtr.Size + IntPtr.Size + 1 + 1 + 1;
			byte* ptr = (byte*)(num + num2);
			*ptr = (byte)(value ? 1 : 0);
		}

		public static bool IsDynamicMethod(this MethodBase method)
		{
			if ((object)_RTDynamicMethod != null)
			{
				if (!(method is DynamicMethod))
				{
					return (object)method.GetType() == _RTDynamicMethod;
				}
				return true;
			}
			if (method is DynamicMethod)
			{
				return true;
			}
			if (method.MetadataToken != 0 || !method.IsStatic || !method.IsPublic || (method.Attributes & MethodAttributes.PrivateScope) != 0)
			{
				return false;
			}
			MethodInfo[] methods = method.DeclaringType.GetMethods(BindingFlags.Static | BindingFlags.Public);
			foreach (MethodInfo methodInfo in methods)
			{
				if ((object)method == methodInfo)
				{
					return false;
				}
			}
			return true;
		}

		public static object SafeGetTarget(this WeakReference weak)
		{
			try
			{
				return weak.Target;
			}
			catch (InvalidOperationException)
			{
				return null;
			}
		}

		public static bool SafeGetIsAlive(this WeakReference weak)
		{
			try
			{
				return weak.IsAlive;
			}
			catch (InvalidOperationException)
			{
				return false;
			}
		}

		public static T CreateDelegate<T>(this MethodBase method) where T : Delegate
		{
			return (T)method.CreateDelegate(typeof(T), null);
		}

		public static T CreateDelegate<T>(this MethodBase method, object target) where T : Delegate
		{
			return (T)method.CreateDelegate(typeof(T), target);
		}

		public static Delegate CreateDelegate(this MethodBase method, Type delegateType)
		{
			return method.CreateDelegate(delegateType, null);
		}

		public static Delegate CreateDelegate(this MethodBase method, Type delegateType, object target)
		{
			if (!typeof(Delegate).IsAssignableFrom(delegateType))
			{
				throw new ArgumentException("Type argument must be a delegate type!");
			}
			if (method is DynamicMethod dynamicMethod)
			{
				return dynamicMethod.CreateDelegate(delegateType, target);
			}
			RuntimeMethodHandle methodHandle = method.MethodHandle;
			RuntimeHelpers.PrepareMethod(methodHandle);
			IntPtr functionPointer = methodHandle.GetFunctionPointer();
			return (Delegate)Activator.CreateInstance(delegateType, target, functionPointer);
		}

		public static MethodDefinition FindMethod(this TypeDefinition type, string id, bool simple = true)
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<MethodDefinition> enumerator;
			if (simple && !MultiTargetShims.Contains(id, " ", StringComparison.Ordinal))
			{
				enumerator = type.Methods.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						MethodDefinition current = enumerator.Current;
						if (((MethodReference)(object)current).GetID(null, null, withType: true, simple: true) == id)
						{
							return current;
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				enumerator = type.Methods.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						MethodDefinition current2 = enumerator.Current;
						if (((MethodReference)(object)current2).GetID(null, null, withType: false, simple: true) == id)
						{
							return current2;
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current3 = enumerator.Current;
					if (((MethodReference)(object)current3).GetID() == id)
					{
						return current3;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current4 = enumerator.Current;
					if (((MethodReference)(object)current4).GetID(null, null, withType: false) == id)
					{
						return current4;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static MethodDefinition FindMethodDeep(this TypeDefinition type, string id, bool simple = true)
		{
			MethodDefinition obj = type.FindMethod(id, simple);
			if (obj == null)
			{
				TypeReference baseType = type.BaseType;
				if (baseType == null)
				{
					return null;
				}
				TypeDefinition obj2 = baseType.Resolve();
				if (obj2 == null)
				{
					return null;
				}
				obj = obj2.FindMethodDeep(id, simple);
			}
			return obj;
		}

		public static MethodInfo FindMethod(this Type type, string id, bool simple = true)
		{
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			MethodInfo[] array;
			if (simple && !MultiTargetShims.Contains(id, " ", StringComparison.Ordinal))
			{
				array = methods;
				foreach (MethodInfo methodInfo in array)
				{
					if (methodInfo.GetID(null, null, withType: true, proxyMethod: false, simple: true) == id)
					{
						return methodInfo;
					}
				}
				array = methods;
				foreach (MethodInfo methodInfo2 in array)
				{
					if (methodInfo2.GetID(null, null, withType: false, proxyMethod: false, simple: true) == id)
					{
						return methodInfo2;
					}
				}
			}
			array = methods;
			foreach (MethodInfo methodInfo3 in array)
			{
				if (methodInfo3.GetID(null, null, withType: true, proxyMethod: false, simple: false) == id)
				{
					return methodInfo3;
				}
			}
			array = methods;
			foreach (MethodInfo methodInfo4 in array)
			{
				if (methodInfo4.GetID(null, null, withType: false, proxyMethod: false, simple: false) == id)
				{
					return methodInfo4;
				}
			}
			return null;
		}

		public static MethodInfo FindMethodDeep(this Type type, string id, bool simple = true)
		{
			MethodInfo methodInfo = type.FindMethod(id, simple);
			if ((object)methodInfo == null)
			{
				Type? baseType = type.BaseType;
				if ((object)baseType == null)
				{
					return null;
				}
				methodInfo = baseType.FindMethodDeep(id, simple);
			}
			return methodInfo;
		}

		public static PropertyDefinition FindProperty(this TypeDefinition type, string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<PropertyDefinition> enumerator = type.Properties.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					PropertyDefinition current = enumerator.Current;
					if (((MemberReference)current).Name == name)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static PropertyDefinition FindPropertyDeep(this TypeDefinition type, string name)
		{
			PropertyDefinition obj = type.FindProperty(name);
			if (obj == null)
			{
				TypeReference baseType = type.BaseType;
				if (baseType == null)
				{
					return null;
				}
				TypeDefinition obj2 = baseType.Resolve();
				if (obj2 == null)
				{
					return null;
				}
				obj = obj2.FindPropertyDeep(name);
			}
			return obj;
		}

		public static FieldDefinition FindField(this TypeDefinition type, string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<FieldDefinition> enumerator = type.Fields.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					FieldDefinition current = enumerator.Current;
					if (((MemberReference)current).Name == name)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static FieldDefinition FindFieldDeep(this TypeDefinition type, string name)
		{
			FieldDefinition obj = type.FindField(name);
			if (obj == null)
			{
				TypeReference baseType = type.BaseType;
				if (baseType == null)
				{
					return null;
				}
				TypeDefinition obj2 = baseType.Resolve();
				if (obj2 == null)
				{
					return null;
				}
				obj = obj2.FindFieldDeep(name);
			}
			return obj;
		}

		public static EventDefinition FindEvent(this TypeDefinition type, string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<EventDefinition> enumerator = type.Events.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					EventDefinition current = enumerator.Current;
					if (((MemberReference)current).Name == name)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return null;
		}

		public static EventDefinition FindEventDeep(this TypeDefinition type, string name)
		{
			EventDefinition obj = type.FindEvent(name);
			if (obj == null)
			{
				TypeReference baseType = type.BaseType;
				if (baseType == null)
				{
					return null;
				}
				TypeDefinition obj2 = baseType.Resolve();
				if (obj2 == null)
				{
					return null;
				}
				obj = obj2.FindEventDeep(name);
			}
			return obj;
		}

		public static string GetID(this MethodReference method, string name = null, string type = null, bool withType = true, bool simple = false)
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (simple)
			{
				if (withType && (type != null || ((MemberReference)method).DeclaringType != null))
				{
					stringBuilder.Append(type ?? ((MemberReference)(object)((MemberReference)method).DeclaringType).GetPatchFullName()).Append("::");
				}
				stringBuilder.Append(name ?? ((MemberReference)method).Name);
				return stringBuilder.ToString();
			}
			stringBuilder.Append(((MemberReference)(object)method.ReturnType).GetPatchFullName()).Append(" ");
			if (withType && (type != null || ((MemberReference)method).DeclaringType != null))
			{
				stringBuilder.Append(type ?? ((MemberReference)(object)((MemberReference)method).DeclaringType).GetPatchFullName()).Append("::");
			}
			stringBuilder.Append(name ?? ((MemberReference)method).Name);
			GenericInstanceMethod val = (GenericInstanceMethod)(object)((method is GenericInstanceMethod) ? method : null);
			if (val != null && val.GenericArguments.Count != 0)
			{
				stringBuilder.Append("<");
				Collection<TypeReference> genericArguments = val.GenericArguments;
				for (int i = 0; i < genericArguments.Count; i++)
				{
					if (i > 0)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.Append(((MemberReference)(object)genericArguments[i]).GetPatchFullName());
				}
				stringBuilder.Append(">");
			}
			else if (method.GenericParameters.Count != 0)
			{
				stringBuilder.Append("<");
				Collection<GenericParameter> genericParameters = method.GenericParameters;
				for (int j = 0; j < genericParameters.Count; j++)
				{
					if (j > 0)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.Append(((MemberReference)genericParameters[j]).Name);
				}
				stringBuilder.Append(">");
			}
			stringBuilder.Append("(");
			if (method.HasParameters)
			{
				Collection<ParameterDefinition> parameters = method.Parameters;
				for (int k = 0; k < parameters.Count; k++)
				{
					ParameterDefinition val2 = parameters[k];
					if (k > 0)
					{
						stringBuilder.Append(",");
					}
					if (((ParameterReference)val2).ParameterType.IsSentinel)
					{
						stringBuilder.Append("...,");
					}
					stringBuilder.Append(((MemberReference)(object)((ParameterReference)val2).ParameterType).GetPatchFullName());
				}
			}
			stringBuilder.Append(")");
			return stringBuilder.ToString();
		}

		public static string GetID(this CallSite method)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(((MemberReference)(object)method.ReturnType).GetPatchFullName()).Append(" ");
			stringBuilder.Append("(");
			if (method.HasParameters)
			{
				Collection<ParameterDefinition> parameters = method.Parameters;
				for (int i = 0; i < parameters.Count; i++)
				{
					ParameterDefinition val = parameters[i];
					if (i > 0)
					{
						stringBuilder.Append(",");
					}
					if (((ParameterReference)val).ParameterType.IsSentinel)
					{
						stringBuilder.Append("...,");
					}
					stringBuilder.Append(((MemberReference)(object)((ParameterReference)val).ParameterType).GetPatchFullName());
				}
			}
			stringBuilder.Append(")");
			return stringBuilder.ToString();
		}

		public static string GetID(this MethodBase method, string name = null, string type = null, bool withType = true, bool proxyMethod = false, bool simple = false)
		{
			while (method is MethodInfo && method.IsGenericMethod && !method.IsGenericMethodDefinition)
			{
				method = ((MethodInfo)method).GetGenericMethodDefinition();
			}
			StringBuilder stringBuilder = new StringBuilder();
			if (simple)
			{
				if (withType && (type != null || (object)method.DeclaringType != null))
				{
					stringBuilder.Append(type ?? method.DeclaringType.FullName).Append("::");
				}
				stringBuilder.Append(name ?? method.Name);
				return stringBuilder.ToString();
			}
			stringBuilder.Append((method as MethodInfo)?.ReturnType?.FullName ?? "System.Void").Append(" ");
			if (withType && (type != null || (object)method.DeclaringType != null))
			{
				stringBuilder.Append(type ?? MultiTargetShims.Replace(method.DeclaringType.FullName, "+", "/", StringComparison.Ordinal)).Append("::");
			}
			stringBuilder.Append(name ?? method.Name);
			if (method.ContainsGenericParameters)
			{
				stringBuilder.Append("<");
				Type[] genericArguments = method.GetGenericArguments();
				for (int i = 0; i < genericArguments.Length; i++)
				{
					if (i > 0)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.Append(genericArguments[i].Name);
				}
				stringBuilder.Append(">");
			}
			stringBuilder.Append("(");
			ParameterInfo[] parameters = method.GetParameters();
			for (int j = (proxyMethod ? 1 : 0); j < parameters.Length; j++)
			{
				ParameterInfo parameterInfo = parameters[j];
				if (j > (proxyMethod ? 1 : 0))
				{
					stringBuilder.Append(",");
				}
				bool flag;
				try
				{
					flag = parameterInfo.GetCustomAttributes(t_ParamArrayAttribute, inherit: false).Length != 0;
				}
				catch (NotSupportedException)
				{
					flag = false;
				}
				if (flag)
				{
					stringBuilder.Append("...,");
				}
				stringBuilder.Append(parameterInfo.ParameterType.FullName);
			}
			stringBuilder.Append(")");
			return stringBuilder.ToString();
		}

		public static string GetPatchName(this MemberReference mr)
		{
			MemberReference obj = ((mr is ICustomAttributeProvider) ? mr : null);
			return ((obj != null) ? ((ICustomAttributeProvider)(object)obj).GetPatchName() : null) ?? mr.Name;
		}

		public static string GetPatchFullName(this MemberReference mr)
		{
			MemberReference obj = ((mr is ICustomAttributeProvider) ? mr : null);
			return ((obj != null) ? ((ICustomAttributeProvider)(object)obj).GetPatchFullName(mr) : null) ?? mr.FullName;
		}

		private static string GetPatchName(this ICustomAttributeProvider cap)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			CustomAttribute customAttribute = cap.GetCustomAttribute("MonoMod.MonoModPatch");
			string text;
			if (customAttribute != null)
			{
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				text = (string)((CustomAttributeArgument)(ref val)).Value;
				int num = text.LastIndexOf('.');
				if (num != -1 && num != text.Length - 1)
				{
					text = text.Substring(num + 1);
				}
				return text;
			}
			text = ((MemberReference)cap).Name;
			if (!text.StartsWith("patch_", StringComparison.Ordinal))
			{
				return text;
			}
			return text.Substring(6);
		}

		private static string GetPatchFullName(this ICustomAttributeProvider cap, MemberReference mr)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Expected O, but got Unknown
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Expected O, but got Unknown
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Expected O, but got Unknown
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			TypeReference val = (TypeReference)(object)((cap is TypeReference) ? cap : null);
			if (val != null)
			{
				CustomAttribute customAttribute = cap.GetCustomAttribute("MonoMod.MonoModPatch");
				string text;
				if (customAttribute != null)
				{
					CustomAttributeArgument val2 = customAttribute.ConstructorArguments[0];
					text = (string)((CustomAttributeArgument)(ref val2)).Value;
				}
				else
				{
					text = ((MemberReference)cap).Name;
					text = (text.StartsWith("patch_", StringComparison.Ordinal) ? text.Substring(6) : text);
				}
				if (text.StartsWith("global::", StringComparison.Ordinal))
				{
					text = text.Substring(8);
				}
				else if (!MultiTargetShims.Contains(text, ".", StringComparison.Ordinal) && !MultiTargetShims.Contains(text, "/", StringComparison.Ordinal))
				{
					if (!string.IsNullOrEmpty(val.Namespace))
					{
						text = val.Namespace + "." + text;
					}
					else if (val.IsNested)
					{
						text = ((MemberReference)(object)((MemberReference)val).DeclaringType).GetPatchFullName() + "/" + text;
					}
				}
				if (mr is TypeSpecification)
				{
					List<TypeSpecification> list = new List<TypeSpecification>();
					TypeSpecification val3 = (TypeSpecification)mr;
					TypeReference elementType;
					do
					{
						list.Add(val3);
						elementType = val3.ElementType;
					}
					while ((val3 = (TypeSpecification)(object)((elementType is TypeSpecification) ? elementType : null)) != null);
					StringBuilder stringBuilder = new StringBuilder(text.Length + list.Count * 4);
					stringBuilder.Append(text);
					for (int num = list.Count - 1; num > -1; num--)
					{
						val3 = list[num];
						if (((TypeReference)val3).IsByReference)
						{
							stringBuilder.Append("&");
						}
						else if (((TypeReference)val3).IsPointer)
						{
							stringBuilder.Append("*");
						}
						else if (!((TypeReference)val3).IsPinned && !((TypeReference)val3).IsSentinel)
						{
							if (((TypeReference)val3).IsArray)
							{
								ArrayType val4 = (ArrayType)val3;
								if (val4.IsVector)
								{
									stringBuilder.Append("[]");
								}
								else
								{
									stringBuilder.Append("[");
									for (int i = 0; i < val4.Dimensions.Count; i++)
									{
										if (i > 0)
										{
											stringBuilder.Append(",");
										}
										ArrayDimension val5 = val4.Dimensions[i];
										stringBuilder.Append(((object)(ArrayDimension)(ref val5)).ToString());
									}
									stringBuilder.Append("]");
								}
							}
							else if (((TypeReference)val3).IsRequiredModifier)
							{
								stringBuilder.Append("modreq(").Append(((RequiredModifierType)val3).ModifierType).Append(")");
							}
							else if (((TypeReference)val3).IsOptionalModifier)
							{
								stringBuilder.Append("modopt(").Append(((OptionalModifierType)val3).ModifierType).Append(")");
							}
							else if (((TypeReference)val3).IsGenericInstance)
							{
								GenericInstanceType val6 = (GenericInstanceType)val3;
								stringBuilder.Append("<");
								for (int j = 0; j < val6.GenericArguments.Count; j++)
								{
									if (j > 0)
									{
										stringBuilder.Append(",");
									}
									stringBuilder.Append(((MemberReference)(object)val6.GenericArguments[j]).GetPatchFullName());
								}
								stringBuilder.Append(">");
							}
							else
							{
								if (!((TypeReference)val3).IsFunctionPointer)
								{
									throw new NotSupportedException($"MonoMod can't handle TypeSpecification: {((MemberReference)val).FullName} ({((object)val).GetType()})");
								}
								FunctionPointerType val7 = (FunctionPointerType)val3;
								stringBuilder.Append(" ").Append(((MemberReference)(object)val7.ReturnType).GetPatchFullName()).Append(" *(");
								if (val7.HasParameters)
								{
									for (int k = 0; k < val7.Parameters.Count; k++)
									{
										ParameterDefinition val8 = val7.Parameters[k];
										if (k > 0)
										{
											stringBuilder.Append(",");
										}
										if (((ParameterReference)val8).ParameterType.IsSentinel)
										{
											stringBuilder.Append("...,");
										}
										stringBuilder.Append(((MemberReference)((ParameterReference)val8).ParameterType).FullName);
									}
								}
								stringBuilder.Append(")");
							}
						}
					}
					text = stringBuilder.ToString();
				}
				return text;
			}
			FieldReference val9 = (FieldReference)(object)((cap is FieldReference) ? cap : null);
			if (val9 != null)
			{
				return ((MemberReference)(object)val9.FieldType).GetPatchFullName() + " " + ((MemberReference)(object)((MemberReference)val9).DeclaringType).GetPatchFullName() + "::" + cap.GetPatchName();
			}
			if (cap is MethodReference)
			{
				throw new InvalidOperationException("GetPatchFullName not supported on MethodReferences - use GetID instead");
			}
			throw new InvalidOperationException($"GetPatchFullName not supported on type {((object)cap).GetType()}");
		}

		public static MethodDefinition Clone(this MethodDefinition o, MethodDefinition c = null)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			if (o == null)
			{
				return null;
			}
			if (c == null)
			{
				c = new MethodDefinition(((MemberReference)o).Name, o.Attributes, ((MethodReference)o).ReturnType);
			}
			((MemberReference)c).Name = ((MemberReference)o).Name;
			c.Attributes = o.Attributes;
			((MethodReference)c).ReturnType = ((MethodReference)o).ReturnType;
			c.DeclaringType = o.DeclaringType;
			((MemberReference)c).MetadataToken = ((MemberReference)c).MetadataToken;
			c.Body = o.Body?.Clone(c);
			c.Attributes = o.Attributes;
			c.ImplAttributes = o.ImplAttributes;
			c.PInvokeInfo = o.PInvokeInfo;
			c.IsPreserveSig = o.IsPreserveSig;
			c.IsPInvokeImpl = o.IsPInvokeImpl;
			Enumerator<GenericParameter> enumerator = ((MethodReference)o).GenericParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					GenericParameter current = enumerator.Current;
					((MethodReference)c).GenericParameters.Add(current.Clone());
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<ParameterDefinition> enumerator2 = ((MethodReference)o).Parameters.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					ParameterDefinition current2 = enumerator2.Current;
					((MethodReference)c).Parameters.Add(current2.Clone());
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<CustomAttribute> enumerator3 = o.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					CustomAttribute current3 = enumerator3.Current;
					c.CustomAttributes.Add(current3.Clone());
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodReference> enumerator4 = o.Overrides.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodReference current4 = enumerator4.Current;
					c.Overrides.Add(current4);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			if (c.Body != null)
			{
				Enumerator<Instruction> enumerator5 = c.Body.Instructions.GetEnumerator();
				try
				{
					while (enumerator5.MoveNext())
					{
						Instruction current5 = enumerator5.Current;
						object operand = current5.Operand;
						GenericParameter val = (GenericParameter)((operand is GenericParameter) ? operand : null);
						int num;
						if (val != null && (num = ((MethodReference)o).GenericParameters.IndexOf(val)) != -1)
						{
							current5.Operand = ((MethodReference)c).GenericParameters[num];
							continue;
						}
						object operand2 = current5.Operand;
						ParameterDefinition val2 = (ParameterDefinition)((operand2 is ParameterDefinition) ? operand2 : null);
						if (val2 != null && (num = ((MethodReference)o).Parameters.IndexOf(val2)) != -1)
						{
							current5.Operand = ((MethodReference)c).Parameters[num];
						}
					}
				}
				finally
				{
					((IDisposable)enumerator5).Dispose();
				}
			}
			return c;
		}

		public static MethodBody Clone(this MethodBody bo, MethodDefinition m)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			if (bo == null)
			{
				return null;
			}
			MethodBody bc = new MethodBody(m);
			bc.MaxStackSize = bo.MaxStackSize;
			bc.InitLocals = bo.InitLocals;
			bc.LocalVarToken = bo.LocalVarToken;
			bc.Instructions.AddRange(((IEnumerable<Instruction>)bo.Instructions).Select(delegate(Instruction o)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				Instruction obj = Instruction.Create(OpCodes.Nop);
				obj.OpCode = o.OpCode;
				obj.Operand = o.Operand;
				obj.Offset = o.Offset;
				return obj;
			}));
			Enumerator<Instruction> enumerator = bc.Instructions.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Instruction current = enumerator.Current;
					object operand = current.Operand;
					Instruction val = (Instruction)((operand is Instruction) ? operand : null);
					if (val != null)
					{
						current.Operand = bc.Instructions[bo.Instructions.IndexOf(val)];
					}
					else if (current.Operand is Instruction[] source)
					{
						current.Operand = source.Select((Instruction i) => bc.Instructions[bo.Instructions.IndexOf(i)]).ToArray();
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			bc.ExceptionHandlers.AddRange(((IEnumerable<ExceptionHandler>)bo.ExceptionHandlers).Select((Func<ExceptionHandler, ExceptionHandler>)((ExceptionHandler o) => new ExceptionHandler(o.HandlerType)
			{
				TryStart = ((o.TryStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.TryStart)]),
				TryEnd = ((o.TryEnd == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.TryEnd)]),
				FilterStart = ((o.FilterStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.FilterStart)]),
				HandlerStart = ((o.HandlerStart == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.HandlerStart)]),
				HandlerEnd = ((o.HandlerEnd == null) ? null : bc.Instructions[bo.Instructions.IndexOf(o.HandlerEnd)]),
				CatchType = o.CatchType
			})));
			bc.Variables.AddRange(((IEnumerable<VariableDefinition>)bo.Variables).Select((Func<VariableDefinition, VariableDefinition>)((VariableDefinition o) => new VariableDefinition(((VariableReference)o).VariableType))));
			m.CustomDebugInformations.AddRange((IEnumerable<CustomDebugInformation>)bo.Method.CustomDebugInformations);
			m.DebugInformation.SequencePoints.AddRange(((IEnumerable<SequencePoint>)bo.Method.DebugInformation.SequencePoints).Select((Func<SequencePoint, SequencePoint>)((SequencePoint o) => new SequencePoint(((IEnumerable<Instruction>)bc.Instructions).FirstOrDefault((Func<Instruction, bool>)((Instruction i) => i.Offset == o.Offset)), o.Document)
			{
				StartLine = o.StartLine,
				StartColumn = o.StartColumn,
				EndLine = o.EndLine,
				EndColumn = o.EndColumn
			})));
			return bc;
		}

		public static GenericParameter Update(this GenericParameter param, int position, GenericParameterType type)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			f_GenericParameter_position.SetValue(param, position);
			f_GenericParameter_type.SetValue(param, type);
			return param;
		}

		public static GenericParameter ResolveGenericParameter(this IGenericParameterProvider provider, GenericParameter orig)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			if (provider is GenericParameter && ((MemberReference)(GenericParameter)provider).Name == ((MemberReference)orig).Name)
			{
				return (GenericParameter)provider;
			}
			Enumerator<GenericParameter> enumerator = provider.GenericParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					GenericParameter current = enumerator.Current;
					if (((MemberReference)current).Name == ((MemberReference)orig).Name)
					{
						return current;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			int position = orig.Position;
			if (provider is MethodReference && orig.DeclaringMethod != null)
			{
				if (position < provider.GenericParameters.Count)
				{
					return provider.GenericParameters[position];
				}
				return orig.Clone().Update(position, (GenericParameterType)1);
			}
			if (provider is TypeReference && ((MemberReference)orig).DeclaringType != null)
			{
				if (position < provider.GenericParameters.Count)
				{
					return provider.GenericParameters[position];
				}
				return orig.Clone().Update(position, (GenericParameterType)0);
			}
			IGenericParameterProvider obj = ((provider is TypeSpecification) ? provider : null);
			object obj2 = ((obj != null) ? ((IGenericParameterProvider)(object)((TypeSpecification)obj).ElementType).ResolveGenericParameter(orig) : null);
			if (obj2 == null)
			{
				IGenericParameterProvider obj3 = ((provider is MemberReference) ? provider : null);
				if (obj3 == null)
				{
					return null;
				}
				TypeReference declaringType = ((MemberReference)obj3).DeclaringType;
				if (declaringType == null)
				{
					return null;
				}
				obj2 = ((IGenericParameterProvider)(object)declaringType).ResolveGenericParameter(orig);
			}
			return (GenericParameter)obj2;
		}

		public static IMetadataTokenProvider Relink(this IMetadataTokenProvider mtp, Relinker relinker, IGenericParameterProvider context)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			if (mtp is TypeReference)
			{
				return (IMetadataTokenProvider)(object)Extensions.Relink((TypeReference)mtp, relinker, context);
			}
			if (mtp is MethodReference)
			{
				return Extensions.Relink((MethodReference)mtp, relinker, context);
			}
			if (mtp is FieldReference)
			{
				return Extensions.Relink((FieldReference)mtp, relinker, context);
			}
			if (mtp is ParameterDefinition)
			{
				return (IMetadataTokenProvider)(object)Extensions.Relink((ParameterDefinition)mtp, relinker, context);
			}
			if (mtp is CallSite)
			{
				return (IMetadataTokenProvider)(object)Extensions.Relink((CallSite)mtp, relinker, context);
			}
			throw new InvalidOperationException($"MonoMod can't handle metadata token providers of the type {((object)mtp).GetType()}");
		}

		public static TypeReference Relink(this TypeReference type, Relinker relinker, IGenericParameterProvider context)
		{
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Expected O, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			if (type == null)
			{
				return null;
			}
			TypeSpecification val = (TypeSpecification)(object)((type is TypeSpecification) ? type : null);
			if (val != null)
			{
				TypeReference val2 = val.ElementType.Relink(relinker, context);
				if (type.IsSentinel)
				{
					return (TypeReference)new SentinelType(val2);
				}
				if (type.IsByReference)
				{
					return (TypeReference)new ByReferenceType(val2);
				}
				if (type.IsPointer)
				{
					return (TypeReference)new PointerType(val2);
				}
				if (type.IsPinned)
				{
					return (TypeReference)new PinnedType(val2);
				}
				if (type.IsArray)
				{
					ArrayType val3 = new ArrayType(val2, ((ArrayType)type).Rank);
					for (int i = 0; i < val3.Rank; i++)
					{
						val3.Dimensions[i] = ((ArrayType)type).Dimensions[i];
					}
					return (TypeReference)(object)val3;
				}
				if (type.IsRequiredModifier)
				{
					return (TypeReference)new RequiredModifierType(((RequiredModifierType)type).ModifierType.Relink(relinker, context), val2);
				}
				if (type.IsOptionalModifier)
				{
					return (TypeReference)new OptionalModifierType(((OptionalModifierType)type).ModifierType.Relink(relinker, context), val2);
				}
				if (type.IsGenericInstance)
				{
					GenericInstanceType val4 = new GenericInstanceType(val2);
					Enumerator<TypeReference> enumerator = ((GenericInstanceType)type).GenericArguments.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							TypeReference current = enumerator.Current;
							val4.GenericArguments.Add(current?.Relink(relinker, context));
						}
						return (TypeReference)(object)val4;
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (type.IsFunctionPointer)
				{
					FunctionPointerType val5 = (FunctionPointerType)type;
					val5.ReturnType = val5.ReturnType.Relink(relinker, context);
					for (int j = 0; j < val5.Parameters.Count; j++)
					{
						((ParameterReference)val5.Parameters[j]).ParameterType = ((ParameterReference)val5.Parameters[j]).ParameterType.Relink(relinker, context);
					}
					return (TypeReference)(object)val5;
				}
				throw new NotSupportedException($"MonoMod can't handle TypeSpecification: {((MemberReference)type).FullName} ({((object)type).GetType()})");
			}
			if (!type.IsGenericParameter || context == null)
			{
				return (TypeReference)relinker((IMetadataTokenProvider)(object)type, context);
			}
			GenericParameter val6 = context.ResolveGenericParameter((GenericParameter)type);
			if (val6 == null)
			{
				throw new RelinkTargetNotFoundException(string.Format("{0} {1} (context: {2})", "MonoMod relinker failed finding", ((MemberReference)type).FullName, context), (IMetadataTokenProvider)(object)type, (IMetadataTokenProvider)(object)context);
			}
			for (int k = 0; k < val6.Constraints.Count; k++)
			{
				if (!val6.Constraints[k].GetConstraintType().IsGenericInstance)
				{
					val6.Constraints[k] = val6.Constraints[k].Relink(relinker, context);
				}
			}
			return (TypeReference)(object)val6;
		}

		public static IMetadataTokenProvider Relink(this MethodReference method, Relinker relinker, IGenericParameterProvider context)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Expected O, but got Unknown
			if (method.IsGenericInstance)
			{
				GenericInstanceMethod val = (GenericInstanceMethod)method;
				GenericInstanceMethod val2 = new GenericInstanceMethod((MethodReference)((MethodSpecification)val).ElementMethod.Relink(relinker, context));
				Enumerator<TypeReference> enumerator = val.GenericArguments.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						TypeReference current = enumerator.Current;
						val2.GenericArguments.Add(current.Relink(relinker, context));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				return (IMetadataTokenProvider)(MethodReference)relinker((IMetadataTokenProvider)(object)val2, context);
			}
			MethodReference val3 = new MethodReference(((MemberReference)method).Name, method.ReturnType, ((MemberReference)method).DeclaringType.Relink(relinker, context));
			val3.CallingConvention = method.CallingConvention;
			val3.ExplicitThis = method.ExplicitThis;
			val3.HasThis = method.HasThis;
			Enumerator<GenericParameter> enumerator2 = method.GenericParameters.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					GenericParameter current2 = enumerator2.Current;
					val3.GenericParameters.Add(current2.Relink(relinker, context));
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			val3.ReturnType = val3.ReturnType?.Relink(relinker, (IGenericParameterProvider)(object)val3);
			Enumerator<ParameterDefinition> enumerator3 = method.Parameters.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					ParameterDefinition current3 = enumerator3.Current;
					((ParameterReference)current3).ParameterType = ((ParameterReference)current3).ParameterType.Relink(relinker, (IGenericParameterProvider)(object)method);
					val3.Parameters.Add(current3);
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			retur

BepInEx/patchers/ValheimModding-HookGenPatcher/BepInEx.MonoMod.HookGenPatcher/BepInEx.MonoMod.HookGenPatcher.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using BepInEx.Configuration;
using BepInEx.Logging;
using Mono.Cecil;
using MonoMod;
using MonoMod.RuntimeDetour.HookGen;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyDescription("Runtime hookgen for bepinex")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HarbingerOfMe")]
[assembly: AssemblyProduct("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyCopyright("HarbingerOfMe2020")]
[assembly: AssemblyTrademark("MIT")]
[assembly: ComVisible(false)]
[assembly: Guid("12032e45-9577-4195-8f4f-a729911b2f08")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: NeutralResourcesLanguage("")]
[assembly: AssemblyVersion("1.2.0.0")]
namespace BepInEx.MonoMod.HookGenPatcher;

public static class HookGenPatcher
{
	internal static ManualLogSource Logger = Logger.CreateLogSource("HookGenPatcher");

	private const string CONFIG_FILE_NAME = "HookGenPatcher.cfg";

	private static readonly ConfigFile Config = new ConfigFile(Path.Combine(Paths.ConfigPath, "HookGenPatcher.cfg"), true);

	private const char EntrySeparator = ',';

	private static readonly ConfigEntry<string> AssemblyNamesToHookGenPatch = Config.Bind<string>("General", "MMHOOKAssemblyNames", "Assembly-CSharp.dll", $"Assembly names to make mmhooks for, separate entries with : {','} ");

	private static readonly ConfigEntry<bool> preciseHash = Config.Bind<bool>("General", "Preciser filehashing", false, "Hash file using contents instead of size. Minor perfomance impact.");

	private static bool skipHashing => !preciseHash.Value;

	public static IEnumerable<string> TargetDLLs { get; } = new string[0];


	public static void Initialize()
	{
		//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cf: Expected O, but got Unknown
		//IL_0237: Unknown result type (might be due to invalid IL or missing references)
		//IL_023e: Expected O, but got Unknown
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_027a: Expected O, but got Unknown
		//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02be: Expected O, but got Unknown
		string[] array = AssemblyNamesToHookGenPatch.Value.Split(new char[1] { ',' });
		string text = Path.Combine(Paths.PluginPath, "MMHOOK");
		string[] array2 = array;
		foreach (string text2 in array2)
		{
			string text3 = "MMHOOK_" + text2;
			string text4 = Path.Combine(Paths.ManagedPath, text2);
			string text5 = Path.Combine(text, text3);
			bool flag = true;
			string[] files = Directory.GetFiles(Paths.PluginPath, text3, SearchOption.AllDirectories);
			foreach (string text6 in files)
			{
				if (Path.GetFileName(text6).Equals(text3))
				{
					text5 = text6;
					Logger.LogInfo((object)"Previous MMHOOK location found. Using that location to save instead.");
					flag = false;
					break;
				}
			}
			if (flag)
			{
				Directory.CreateDirectory(text);
			}
			FileInfo fileInfo = new FileInfo(text4);
			long length = fileInfo.Length;
			long num = 0L;
			if (File.Exists(text5))
			{
				try
				{
					AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text5);
					try
					{
						if (val.MainModule.GetType("BepHookGen.size" + length) != null)
						{
							if (skipHashing)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
							num = fileInfo.makeHash();
							if (val.MainModule.GetType("BepHookGen.content" + num) != null)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
						}
					}
					finally
					{
						((IDisposable)val)?.Dispose();
					}
				}
				catch (BadImageFormatException)
				{
					Logger.LogWarning((object)("Failed to read " + Path.GetFileName(text5) + ", probably corrupted, remaking one."));
				}
			}
			Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
			Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			MonoModder val2 = new MonoModder
			{
				InputPath = text4,
				OutputPath = text5,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				IAssemblyResolver assemblyResolver = val2.AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Paths.BepInExAssemblyDirectory);
				}
				val2.Read();
				val2.MapDependencies();
				if (File.Exists(text5))
				{
					Logger.LogDebug((object)("Clearing " + text5));
					File.Delete(text5);
				}
				Logger.LogInfo((object)"Starting HookGenerator");
				HookGenerator val3 = new HookGenerator(val2, Path.GetFileName(text5));
				ModuleDefinition outputModule = val3.OutputModule;
				try
				{
					val3.Generate();
					outputModule.Types.Add(new TypeDefinition("BepHookGen", "size" + length, (TypeAttributes)131072));
					if (!skipHashing)
					{
						outputModule.Types.Add(new TypeDefinition("BepHookGen", "content" + ((num == 0L) ? fileInfo.makeHash() : num), (TypeAttributes)131072));
					}
					outputModule.Write(text5);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				Logger.LogInfo((object)"Done.");
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}
	}

	public static void Patch(AssemblyDefinition _)
	{
	}

	private static long makeHash(this FileInfo fileInfo)
	{
		FileStream inputStream = fileInfo.OpenRead();
		byte[] value = null;
		using (MD5 mD = new MD5CryptoServiceProvider())
		{
			value = mD.ComputeHash(inputStream);
		}
		long num = BitConverter.ToInt64(value, 0);
		if (num == 0L)
		{
			return 1L;
		}
		return num;
	}
}

BepInEx/patchers/ValheimModding-HookGenPatcher/BepInEx.MonoMod.HookGenPatcher/MonoMod.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Mdb;
using Mono.Cecil.Pdb;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.InlineRT;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("General purpose .NET assembly modding \"basework\". This package contains the core IL patcher and relinker.")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod")]
[assembly: AssemblyTitle("MonoMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	[MonoMod__SafeToCopy__]
	public class MonoModAdded : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModConstructor : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomAttributeAttribute : Attribute
	{
		public MonoModCustomAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomMethodAttributeAttribute : Attribute
	{
		public MonoModCustomMethodAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModEnumReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCall : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCallvirt : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	[Obsolete("Use MonoModLinkFrom or RuntimeDetour / HookGen instead.")]
	public class MonoModHook : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModHook(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModHook(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIfFlag : Attribute
	{
		public MonoModIfFlag(string key)
		{
		}

		public MonoModIfFlag(string key, bool fallback)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIgnore : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	public class MonoModLinkFrom : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModLinkFrom(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModLinkFrom(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModLinkTo : Attribute
	{
		public MonoModLinkTo(string t)
		{
		}

		public MonoModLinkTo(Type t)
		{
		}

		public MonoModLinkTo(string t, string n)
		{
		}

		public MonoModLinkTo(Type t, string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModNoNew : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOnPlatform : Attribute
	{
		public MonoModOnPlatform(params Platform[] p)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginal : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginalName : Attribute
	{
		public MonoModOriginalName(string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPatch : Attribute
	{
		public MonoModPatch(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPublic : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModRemove : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModTargetModule : Attribute
	{
		public MonoModTargetModule(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	internal class MonoMod__SafeToCopy__ : Attribute
	{
	}
	public delegate bool MethodParser(MonoModder modder, MethodBody body, Instruction instr, ref int instri);
	public delegate void MethodRewriter(MonoModder modder, MethodDefinition method);
	public delegate void MethodBodyRewriter(MonoModder modder, MethodBody body, Instruction instr, int instri);
	public delegate ModuleDefinition MissingDependencyResolver(MonoModder modder, ModuleDefinition main, string name, string fullName);
	public delegate void PostProcessor(MonoModder modder);
	public delegate void ModReadEventHandler(MonoModder modder, ModuleDefinition mod);
	public class RelinkMapEntry
	{
		public string Type;

		public string FindableID;

		public RelinkMapEntry()
		{
		}

		public RelinkMapEntry(string type, string findableID)
		{
			Type = type;
			FindableID = findableID;
		}
	}
	public enum DebugSymbolFormat
	{
		Auto,
		MDB,
		PDB
	}
	public class MonoModder : IDisposable
	{
		public static readonly bool IsMono = (object)Type.GetType("Mono.Runtime") != null;

		public static readonly Version Version = typeof(MonoModder).Assembly.GetName().Version;

		public Dictionary<string, object> SharedData = new Dictionary<string, object>();

		public Dictionary<string, object> RelinkMap = new Dictionary<string, object>();

		public Dictionary<string, ModuleDefinition> RelinkModuleMap = new Dictionary<string, ModuleDefinition>();

		public HashSet<string> SkipList = new HashSet<string>(EqualityComparer<string>.Default);

		public Dictionary<string, IMetadataTokenProvider> RelinkMapCache = new Dictionary<string, IMetadataTokenProvider>();

		public Dictionary<string, TypeReference> RelinkModuleMapCache = new Dictionary<string, TypeReference>();

		public Dictionary<string, OpCode> ForceCallMap = new Dictionary<string, OpCode>();

		public ModReadEventHandler OnReadMod;

		public PostProcessor PostProcessors;

		public Dictionary<string, Action<object, object[]>> CustomAttributeHandlers = new Dictionary<string, Action<object, object[]>> { 
		{
			"MonoMod.MonoModPublic",
			delegate
			{
			}
		} };

		public Dictionary<string, Action<object, object[]>> CustomMethodAttributeHandlers = new Dictionary<string, Action<object, object[]>>();

		public MissingDependencyResolver MissingDependencyResolver;

		public MethodParser MethodParser;

		public MethodRewriter MethodRewriter;

		public MethodBodyRewriter MethodBodyRewriter;

		public Stream Input;

		public string InputPath;

		public Stream Output;

		public string OutputPath;

		public List<string> DependencyDirs = new List<string>();

		public ModuleDefinition Module;

		public Dictionary<ModuleDefinition, List<ModuleDefinition>> DependencyMap = new Dictionary<ModuleDefinition, List<ModuleDefinition>>();

		public Dictionary<string, ModuleDefinition> DependencyCache = new Dictionary<string, ModuleDefinition>();

		public Func<ICustomAttributeProvider, TypeReference, bool> ShouldCleanupAttrib;

		public bool LogVerboseEnabled;

		public bool CleanupEnabled;

		public bool PublicEverything;

		public List<ModuleReference> Mods = new List<ModuleReference>();

		public bool Strict;

		public bool MissingDependencyThrow;

		public bool RemovePatchReferences;

		public bool PreventInline;

		public bool? UpgradeMSCORLIB;

		public ReadingMode ReadingMode = (ReadingMode)1;

		public DebugSymbolFormat DebugSymbolOutputFormat;

		public int CurrentRID;

		protected IAssemblyResolver _assemblyResolver;

		protected ReaderParameters _readerParameters;

		protected WriterParameters _writerParameters;

		public bool GACEnabled;

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

		protected string[] _GACPaths;

		protected MethodDefinition _mmOriginalCtor;

		protected MethodDefinition _mmOriginalNameCtor;

		protected MethodDefinition _mmAddedCtor;

		protected MethodDefinition _mmPatchCtor;

		public virtual IAssemblyResolver AssemblyResolver
		{
			get
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Expected O, but got Unknown
				if (_assemblyResolver == null)
				{
					DefaultAssemblyResolver val = new DefaultAssemblyResolver();
					foreach (string dependencyDir in DependencyDirs)
					{
						((BaseAssemblyResolver)val).AddSearchDirectory(dependencyDir);
					}
					_assemblyResolver = (IAssemblyResolver)(object)val;
				}
				return _assemblyResolver;
			}
			set
			{
				_assemblyResolver = value;
			}
		}

		public virtual ReaderParameters ReaderParameters
		{
			get
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Expected O, but got Unknown
				if (_readerParameters == null)
				{
					_readerParameters = new ReaderParameters(ReadingMode)
					{
						AssemblyResolver = AssemblyResolver,
						ReadSymbols = true
					};
				}
				return _readerParameters;
			}
			set
			{
				_readerParameters = value;
			}
		}

		public virtual WriterParameters WriterParameters
		{
			get
			{
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Expected O, but got Unknown
				//IL_0067: Expected O, but got Unknown
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Expected O, but got Unknown
				if (_writerParameters == null)
				{
					bool flag = DebugSymbolOutputFormat == DebugSymbolFormat.PDB;
					bool flag2 = DebugSymbolOutputFormat == DebugSymbolFormat.MDB;
					if (DebugSymbolOutputFormat == DebugSymbolFormat.Auto)
					{
						if ((PlatformHelper.Current & 0x25) == 37)
						{
							flag = true;
						}
						else
						{
							flag2 = true;
						}
					}
					WriterParameters val = new WriterParameters
					{
						WriteSymbols = true
					};
					object symbolWriterProvider;
					if (!flag)
					{
						if (!flag2)
						{
							symbolWriterProvider = null;
						}
						else
						{
							ISymbolWriterProvider val2 = (ISymbolWriterProvider)new MdbWriterProvider();
							symbolWriterProvider = val2;
						}
					}
					else
					{
						ISymbolWriterProvider val2 = (ISymbolWriterProvider)new NativePdbWriterProvider();
						symbolWriterProvider = val2;
					}
					val.SymbolWriterProvider = (ISymbolWriterProvider)symbolWriterProvider;
					_writerParameters = val;
				}
				return _writerParameters;
			}
			set
			{
				_writerParameters = value;
			}
		}

		public string[] GACPaths
		{
			get
			{
				if (!GACEnabled)
				{
					return _GACPathsNone;
				}
				if (_GACPaths != null)
				{
					return _GACPaths;
				}
				if (!IsMono)
				{
					string environmentVariable = Environment.GetEnvironmentVariable("windir");
					if (string.IsNullOrEmpty(environmentVariable))
					{
						return _GACPaths = _GACPathsNone;
					}
					environmentVariable = Path.Combine(environmentVariable, "Microsoft.NET");
					environmentVariable = Path.Combine(environmentVariable, "assembly");
					_GACPaths = new string[3]
					{
						Path.Combine(environmentVariable, "GAC_32"),
						Path.Combine(environmentVariable, "GAC_64"),
						Path.Combine(environmentVariable, "GAC_MSIL")
					};
				}
				else
				{
					List<string> list = new List<string>();
					string text = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)), "gac");
					if (Directory.Exists(text))
					{
						list.Add(text);
					}
					string environmentVariable2 = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX");
					if (!string.IsNullOrEmpty(environmentVariable2))
					{
						string[] array = environmentVariable2.Split(new char[1] { Path.PathSeparator });
						foreach (string text2 in array)
						{
							if (!string.IsNullOrEmpty(text2))
							{
								string path = text2;
								path = Path.Combine(path, "lib");
								path = Path.Combine(path, "mono");
								path = Path.Combine(path, "gac");
								if (Directory.Exists(path) && !list.Contains(path))
								{
									list.Add(path);
								}
							}
						}
					}
					_GACPaths = list.ToArray();
				}
				return _GACPaths;
			}
			set
			{
				GACEnabled = true;
				_GACPaths = value;
			}
		}

		public MonoModder()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			MethodParser = DefaultParser;
			MissingDependencyResolver = DefaultMissingDependencyResolver;
			PostProcessors = (PostProcessor)Delegate.Combine(PostProcessors, new PostProcessor(DefaultPostProcessor));
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DEPDIRS");
			if (!string.IsNullOrEmpty(environmentVariable))
			{
				foreach (string item in from dir in environmentVariable.Split(new char[1] { Path.PathSeparator })
					select dir.Trim())
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(item);
					}
					DependencyDirs.Add(item);
				}
			}
			LogVerboseEnabled = Environment.GetEnvironmentVariable("MONOMOD_LOG_VERBOSE") == "1";
			CleanupEnabled = Environment.GetEnvironmentVariable("MONOMOD_CLEANUP") != "0";
			PublicEverything = Environment.GetEnvironmentVariable("MONOMOD_PUBLIC_EVERYTHING") == "1";
			PreventInline = Environment.GetEnvironmentVariable("MONOMOD_PREVENTINLINE") == "1";
			Strict = Environment.GetEnvironmentVariable("MONOMOD_STRICT") == "1";
			MissingDependencyThrow = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") != "0";
			RemovePatchReferences = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_REMOVE_PATCH") != "0";
			string environmentVariable2 = Environment.GetEnvironmentVariable("MONOMOD_DEBUG_FORMAT");
			if (environmentVariable2 != null)
			{
				environmentVariable2 = environmentVariable2.ToLowerInvariant();
				if (environmentVariable2 == "pdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.PDB;
				}
				else if (environmentVariable2 == "mdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.MDB;
				}
			}
			string environmentVariable3 = Environment.GetEnvironmentVariable("MONOMOD_MSCORLIB_UPGRADE");
			UpgradeMSCORLIB = (string.IsNullOrEmpty(environmentVariable3) ? null : new bool?(environmentVariable3 != "0"));
			GACEnabled = Environment.GetEnvironmentVariable("MONOMOD_GAC_ENABLED") != "0";
			MonoModRulesManager.Register(this);
		}

		public virtual void ClearCaches(bool all = false, bool shareable = false, bool moduleSpecific = false)
		{
			if (all || shareable)
			{
				foreach (KeyValuePair<string, ModuleDefinition> item in DependencyCache)
				{
					item.Value.Dispose();
				}
				DependencyCache.Clear();
			}
			if (all || moduleSpecific)
			{
				RelinkMapCache.Clear();
				RelinkModuleMapCache.Clear();
			}
		}

		public virtual void Dispose()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			ClearCaches(all: true);
			ModuleDefinition module = Module;
			if (module != null)
			{
				module.Dispose();
			}
			Module = null;
			((IDisposable)AssemblyResolver)?.Dispose();
			AssemblyResolver = null;
			foreach (ModuleDefinition mod in Mods)
			{
				if ((int)mod != 0)
				{
					mod.Dispose();
				}
			}
			foreach (List<ModuleDefinition> value in DependencyMap.Values)
			{
				foreach (ModuleDefinition item in value)
				{
					if (item != null)
					{
						item.Dispose();
					}
				}
			}
			DependencyMap.Clear();
			Input?.Dispose();
			Output?.Dispose();
		}

		public virtual void Log(object value)
		{
			Log(value.ToString());
		}

		public virtual void Log(string text)
		{
			Console.Write("[MonoMod] ");
			Console.WriteLine(text);
		}

		public virtual void LogVerbose(object value)
		{
			if (LogVerboseEnabled)
			{
				Log(value);
			}
		}

		public virtual void LogVerbose(string text)
		{
			if (LogVerboseEnabled)
			{
				Log(text);
			}
		}

		private static ModuleDefinition _ReadModule(Stream input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
					input.Seek(0L, SeekOrigin.Begin);
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		private static ModuleDefinition _ReadModule(string input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		public virtual void Read()
		{
			if (Module != null)
			{
				return;
			}
			if (Input != null)
			{
				Log("Reading input stream into module.");
				Module = _ReadModule(Input, GenReaderParameters(mainModule: true));
			}
			else if (InputPath != null)
			{
				Log("Reading input file into module.");
				IAssemblyResolver assemblyResolver = AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Path.GetDirectoryName(InputPath));
				}
				DependencyDirs.Add(Path.GetDirectoryName(InputPath));
				Module = _ReadModule(InputPath, GenReaderParameters(mainModule: true, InputPath));
			}
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_MODS");
			if (string.IsNullOrEmpty(environmentVariable))
			{
				return;
			}
			foreach (string item in from path in environmentVariable.Split(new char[1] { Path.PathSeparator })
				select path.Trim())
			{
				ReadMod(item);
			}
		}

		public virtual void MapDependencies()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition main = mod;
				MapDependencies(main);
			}
			MapDependencies(Module);
		}

		public virtual void MapDependencies(ModuleDefinition main)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (DependencyMap.ContainsKey(main))
			{
				return;
			}
			DependencyMap[main] = new List<ModuleDefinition>();
			Enumerator<AssemblyNameReference> enumerator = main.AssemblyReferences.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					AssemblyNameReference current = enumerator.Current;
					MapDependency(main, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void MapDependency(ModuleDefinition main, AssemblyNameReference depRef)
		{
			MapDependency(main, depRef.Name, depRef.FullName, depRef);
		}

		public virtual void MapDependency(ModuleDefinition main, string name, string fullName = null, AssemblyNameReference depRef = null)
		{
			if (!DependencyMap.TryGetValue(main, out var value))
			{
				value = (DependencyMap[main] = new List<ModuleDefinition>());
			}
			if (fullName != null && (DependencyCache.TryGetValue(fullName, out var value2) || DependencyCache.TryGetValue(fullName + " [RT:" + main.RuntimeVersion + "]", out value2)))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			if (DependencyCache.TryGetValue(name, out value2) || DependencyCache.TryGetValue(name + " [RT:" + main.RuntimeVersion + "]", out value2))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " (" + name + ") from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			string text = Path.GetExtension(name).ToLowerInvariant();
			bool flag = text == "pdb" || text == "mdb";
			string text2 = null;
			foreach (string dependencyDir in DependencyDirs)
			{
				text2 = Path.Combine(dependencyDir, name + ".dll");
				if (!File.Exists(text2))
				{
					text2 = Path.Combine(dependencyDir, name + ".exe");
				}
				if (!File.Exists(text2) && !flag)
				{
					text2 = Path.Combine(dependencyDir, name);
				}
				if (File.Exists(text2))
				{
					break;
				}
				text2 = null;
			}
			if (text2 == null && depRef != null)
			{
				try
				{
					AssemblyDefinition obj = AssemblyResolver.Resolve(depRef);
					value2 = ((obj != null) ? obj.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (text2 == null)
			{
				string[] gACPaths = GACPaths;
				for (int i = 0; i < gACPaths.Length; i++)
				{
					text2 = Path.Combine(gACPaths[i], name);
					if (Directory.Exists(text2))
					{
						string[] directories = Directory.GetDirectories(text2);
						int num = 0;
						int num2 = 0;
						for (int j = 0; j < directories.Length; j++)
						{
							string text3 = directories[j];
							if (text3.StartsWith(text2))
							{
								text3 = text3.Substring(text2.Length + 1);
							}
							Match match = Regex.Match(text3, "\\d+");
							if (match.Success)
							{
								int num3 = int.Parse(match.Value);
								if (num3 > num)
								{
									num = num3;
									num2 = j;
								}
							}
						}
						text2 = Path.Combine(directories[num2], name + ".dll");
						break;
					}
					text2 = null;
				}
			}
			if (text2 == null)
			{
				try
				{
					AssemblyDefinition obj3 = AssemblyResolver.Resolve(AssemblyNameReference.Parse(fullName ?? name));
					value2 = ((obj3 != null) ? obj3.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (value2 == null)
			{
				if (text2 != null && File.Exists(text2))
				{
					value2 = _ReadModule(text2, GenReaderParameters(mainModule: false, text2));
				}
				else if ((value2 = MissingDependencyResolver?.Invoke(this, main, name, fullName)) == null)
				{
					return;
				}
			}
			LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) loaded");
			value.Add(value2);
			if (fullName == null)
			{
				fullName = value2.Assembly.FullName;
			}
			DependencyCache[fullName] = value2;
			DependencyCache[name] = value2;
			MapDependencies(value2);
		}

		public virtual ModuleDefinition DefaultMissingDependencyResolver(MonoModder mod, ModuleDefinition main, string name, string fullName)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (MissingDependencyThrow && Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") == "0")
			{
				Log("[MissingDependencyResolver] [WARNING] Use MMILRT.Modder.MissingDependencyThrow instead of setting the env var MONOMOD_DEPENDENCY_MISSING_THROW");
				MissingDependencyThrow = false;
			}
			if (MissingDependencyThrow || Strict)
			{
				throw new RelinkTargetNotFoundException("MonoMod cannot map dependency " + ((ModuleReference)main).Name + " -> ((" + fullName + "), (" + name + ")) - not found", (IMetadataTokenProvider)(object)main, (IMetadataTokenProvider)null);
			}
			return null;
		}

		public virtual void Write(Stream output = null, string outputPath = null)
		{
			output = output ?? Output;
			outputPath = outputPath ?? OutputPath;
			PatchRefsInType(PatchWasHere());
			if (output != null)
			{
				Log("[Write] Writing modded module into output stream.");
				Module.Write(output, WriterParameters);
			}
			else
			{
				Log("[Write] Writing modded module into output file.");
				Module.Write(outputPath, WriterParameters);
			}
		}

		public virtual ReaderParameters GenReaderParameters(bool mainModule, string path = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			ReaderParameters readerParameters = ReaderParameters;
			ReaderParameters val = new ReaderParameters(readerParameters.ReadingMode);
			val.AssemblyResolver = readerParameters.AssemblyResolver;
			val.MetadataResolver = readerParameters.MetadataResolver;
			val.InMemory = readerParameters.InMemory;
			val.MetadataImporterProvider = readerParameters.MetadataImporterProvider;
			val.ReflectionImporterProvider = readerParameters.ReflectionImporterProvider;
			val.ThrowIfSymbolsAreNotMatching = readerParameters.ThrowIfSymbolsAreNotMatching;
			val.ApplyWindowsRuntimeProjections = readerParameters.ApplyWindowsRuntimeProjections;
			val.SymbolStream = readerParameters.SymbolStream;
			val.SymbolReaderProvider = readerParameters.SymbolReaderProvider;
			val.ReadSymbols = readerParameters.ReadSymbols;
			if (path != null && !File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
			{
				val.ReadSymbols = false;
			}
			return val;
		}

		public virtual void ReadMod(string path)
		{
			if (Directory.Exists(path))
			{
				Log("[ReadMod] Loading mod dir: " + path);
				string text = ((ModuleReference)Module).Name.Substring(0, ((ModuleReference)Module).Name.Length - 3);
				string value = text.Replace(" ", "");
				if (!DependencyDirs.Contains(path))
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(path);
					}
					DependencyDirs.Add(path);
				}
				string[] files = Directory.GetFiles(path);
				foreach (string text2 in files)
				{
					if ((Path.GetFileName(text2).StartsWith(text) || Path.GetFileName(text2).StartsWith(value)) && text2.ToLower().EndsWith(".mm.dll"))
					{
						ReadMod(text2);
					}
				}
				return;
			}
			Log("[ReadMod] Loading mod: " + path);
			ModuleDefinition val = _ReadModule(path, GenReaderParameters(mainModule: false, path));
			string directoryName = Path.GetDirectoryName(path);
			if (!DependencyDirs.Contains(directoryName))
			{
				IAssemblyResolver assemblyResolver2 = AssemblyResolver;
				IAssemblyResolver obj2 = ((assemblyResolver2 is BaseAssemblyResolver) ? assemblyResolver2 : null);
				if (obj2 != null)
				{
					((BaseAssemblyResolver)obj2).AddSearchDirectory(directoryName);
				}
				DependencyDirs.Add(directoryName);
			}
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ReadMod(Stream stream)
		{
			Log($"[ReadMod] Loading mod: stream#{(uint)stream.GetHashCode()}");
			ModuleDefinition val = _ReadModule(stream, GenReaderParameters(mainModule: false));
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ParseRules(ModuleDefinition mod)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			TypeDefinition type = mod.GetType("MonoMod.MonoModRules");
			Type rulesTypeMMILRT = null;
			if (type != null)
			{
				rulesTypeMMILRT = this.ExecuteRules(type);
				mod.Types.Remove(type);
			}
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					ParseRulesInType(current, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void ParseRulesInType(TypeDefinition type, Type rulesTypeMMILRT = null)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_0377: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_0431: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			Extensions.GetPatchFullName((MemberReference)(object)type);
			if (!MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				return;
			}
			CustomAttribute customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomAttributeAttribute");
			CustomAttributeArgument val;
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method2 = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				CustomAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
				{
					method2.Invoke(self, args);
				};
			}
			customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomMethodAttributeAttribute");
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length == 2 && Extensions.IsCompatible(parameters[0].ParameterType, typeof(ILContext)))
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						//IL_0024: Unknown result type (might be due to invalid IL or missing references)
						//IL_002e: Expected O, but got Unknown
						//IL_0029: Unknown result type (might be due to invalid IL or missing references)
						//IL_0033: Expected O, but got Unknown
						//IL_0040: Unknown result type (might be due to invalid IL or missing references)
						//IL_004a: Expected O, but got Unknown
						ILContext il = new ILContext((MethodDefinition)args[0]);
						il.Invoke((Manipulator)delegate
						{
							method.Invoke(self, new object[2]
							{
								il,
								args[1]
							});
						});
						if (il.IsReadOnly)
						{
							il.Dispose();
						}
					};
				}
				else
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						method.Invoke(self, args);
					};
				}
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModHook"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
			{
				ParseLinkTo((MemberReference)(object)type, val2);
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore"))
			{
				return;
			}
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current, val2);
						}
						if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCall"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Call;
						}
						else if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCallvirt"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Callvirt;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<FieldDefinition> enumerator2 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					FieldDefinition current2 = enumerator2.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current2, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current2, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<PropertyDefinition> enumerator3 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					PropertyDefinition current3 = enumerator3.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current3, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current3, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<TypeDefinition> enumerator4 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					TypeDefinition current4 = enumerator4.Current;
					ParseRulesInType(current4, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
		}

		public virtual void ParseLinkFrom(MemberReference target, CustomAttribute hook)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			CustomAttributeArgument val = hook.ConstructorArguments[0];
			string key = (string)((CustomAttributeArgument)(ref val)).Value;
			object value;
			if (target is TypeReference)
			{
				value = Extensions.GetPatchFullName((MemberReference)(TypeReference)target);
			}
			else if (target is MethodReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(MethodReference)target).DeclaringType), Extensions.GetID((MethodReference)target, (string)null, (string)null, false, false));
			}
			else if (target is FieldReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(FieldReference)target).DeclaringType), ((MemberReference)(FieldReference)target).Name);
			}
			else
			{
				if (!(target is PropertyReference))
				{
					return;
				}
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(PropertyReference)target).DeclaringType), ((MemberReference)(PropertyReference)target).Name);
			}
			RelinkMap[key] = value;
		}

		public virtual void ParseLinkTo(MemberReference from, CustomAttribute hook)
		{
			//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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			MemberReference obj = ((from is MethodReference) ? from : null);
			string key = ((obj != null) ? Extensions.GetID((MethodReference)(object)obj, (string)null, (string)null, true, false) : null) ?? Extensions.GetPatchFullName(from);
			CustomAttributeArgument val;
			if (hook.ConstructorArguments.Count == 1)
			{
				Dictionary<string, object> relinkMap = RelinkMap;
				val = hook.ConstructorArguments[0];
				relinkMap[key] = (string)((CustomAttributeArgument)(ref val)).Value;
			}
			else
			{
				Dictionary<string, object> relinkMap2 = RelinkMap;
				val = hook.ConstructorArguments[0];
				string type = (string)((CustomAttributeArgument)(ref val)).Value;
				val = hook.ConstructorArguments[1];
				relinkMap2[key] = new RelinkMapEntry(type, (string)((CustomAttributeArgument)(ref val)).Value);
			}
		}

		public virtual void RunCustomAttributeHandlers(ICustomAttributeProvider cap)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			if (!cap.HasCustomAttributes)
			{
				return;
			}
			CustomAttribute[] array = cap.CustomAttributes.ToArray();
			foreach (CustomAttribute val in array)
			{
				if (CustomAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out var value))
				{
					value?.Invoke(null, new object[2] { cap, val });
				}
				if (cap is MethodReference && CustomMethodAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out value))
				{
					value?.Invoke(null, new object[2]
					{
						(object)(MethodDefinition)cap,
						val
					});
				}
			}
		}

		public virtual void AutoPatch()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			Log("[AutoPatch] Parsing rules in loaded mods");
			foreach (ModuleDefinition mod4 in Mods)
			{
				ModuleDefinition mod = mod4;
				ParseRules(mod);
			}
			Log("[AutoPatch] PrePatch pass");
			foreach (ModuleDefinition mod5 in Mods)
			{
				ModuleDefinition mod2 = mod5;
				PrePatchModule(mod2);
			}
			Log("[AutoPatch] Patch pass");
			foreach (ModuleDefinition mod6 in Mods)
			{
				ModuleDefinition mod3 = mod6;
				PatchModule(mod3);
			}
			Log("[AutoPatch] PatchRefs pass");
			PatchRefs();
			if (PostProcessors != null)
			{
				Delegate[] invocationList = PostProcessors.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Log($"[PostProcessor] PostProcessor pass #{i + 1}");
					((PostProcessor)invocationList[i])?.Invoke(this);
				}
			}
		}

		public virtual IMetadataTokenProvider Relinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return PostRelinker(MainRelinker(mtp, context) ?? mtp, context) ?? throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
			}
			catch (Exception ex)
			{
				throw new RelinkFailedException((string)null, ex, mtp, (IMetadataTokenProvider)(object)context);
			}
		}

		public virtual IMetadataTokenProvider MainRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null);
			if (val != null)
			{
				if (((MemberReference)val).Module == Module)
				{
					return (IMetadataTokenProvider)(object)val;
				}
				if (((MemberReference)val).Module != null && !Mods.Contains((ModuleReference)(object)((MemberReference)val).Module))
				{
					return (IMetadataTokenProvider)(object)Module.ImportReference(val);
				}
				val = (TypeReference)(((object)Extensions.SafeResolve(val)) ?? ((object)val));
				TypeReference val2 = FindTypeDeep(Extensions.GetPatchFullName((MemberReference)(object)val));
				if (val2 == null)
				{
					if (RelinkMap.ContainsKey(((MemberReference)val).FullName))
					{
						return null;
					}
					throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(val2);
			}
			if (mtp is FieldReference || mtp is MethodReference || mtp is PropertyReference || mtp is EventReference)
			{
				return Extensions.ImportReference(Module, mtp);
			}
			throw new InvalidOperationException($"MonoMod default relinker can't handle metadata token providers of the type {((object)mtp).GetType()}");
		}

		public virtual IMetadataTokenProvider PostRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			return ResolveRelinkTarget(mtp) ?? mtp;
		}

		public virtual IMetadataTokenProvider ResolveRelinkTarget(IMetadataTokenProvider mtp, bool relink = true, bool relinkModule = true)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_004b: 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_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Expected O, but got Unknown
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			string text = null;
			string text2;
			if (mtp is TypeReference)
			{
				text2 = ((MemberReference)(TypeReference)mtp).FullName;
			}
			else if (mtp is MethodReference)
			{
				text2 = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, false);
				text = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, true);
			}
			else if (mtp is FieldReference)
			{
				text2 = ((MemberReference)(FieldReference)mtp).FullName;
			}
			else
			{
				if (!(mtp is PropertyReference))
				{
					return null;
				}
				text2 = ((MemberReference)(PropertyReference)mtp).FullName;
			}
			if (RelinkMapCache.TryGetValue(text2, out var value))
			{
				return value;
			}
			if (relink && (RelinkMap.TryGetValue(text2, out var value2) || (text != null && RelinkMap.TryGetValue(text, out value2))))
			{
				if (value2 is IMetadataTokenProvider)
				{
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is RelinkMapEntry)
				{
					string type = ((RelinkMapEntry)value2).Type;
					string findableID = ((RelinkMapEntry)value2).FindableID;
					TypeReference obj = FindTypeDeep(type);
					TypeDefinition val2 = ((obj != null) ? Extensions.SafeResolve(obj) : null);
					if (val2 == null)
					{
						return RelinkMapCache[text2] = ResolveRelinkTarget(mtp, relink: false, relinkModule);
					}
					value2 = Extensions.FindMethod(val2, findableID, true) ?? ((object)Extensions.FindField(val2, findableID)) ?? ((object)(Extensions.FindProperty(val2, findableID) ?? null));
					if (value2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} ({1}, {2}) (remap: {3})", "MonoMod relinker failed finding", type, findableID, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is string && mtp is TypeReference)
				{
					IMetadataTokenProvider val5 = (IMetadataTokenProvider)(object)FindTypeDeep((string)value2);
					if (val5 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", value2, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					value2 = Extensions.ImportReference(Module, ResolveRelinkTarget(val5, relink: false, relinkModule) ?? val5);
				}
				if (value2 is IMetadataTokenProvider)
				{
					Dictionary<string, IMetadataTokenProvider> relinkMapCache = RelinkMapCache;
					string key = text2;
					IMetadataTokenProvider val6 = (IMetadataTokenProvider)value2;
					IMetadataTokenProvider result = val6;
					relinkMapCache[key] = val6;
					return result;
				}
				throw new InvalidOperationException($"MonoMod doesn't support RelinkMap value of type {value2.GetType()} (remap: {mtp})");
			}
			if (relinkModule && mtp is TypeReference)
			{
				if (RelinkModuleMapCache.TryGetValue(text2, out var value3))
				{
					return (IMetadataTokenProvider)(object)value3;
				}
				value3 = (TypeReference)mtp;
				if (RelinkModuleMap.TryGetValue(value3.Scope.Name, out var value4))
				{
					TypeReference type2 = (TypeReference)(object)value4.GetType(((MemberReference)value3).FullName);
					if (type2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", ((MemberReference)value3).FullName, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return (IMetadataTokenProvider)(object)(RelinkModuleMapCache[text2] = Module.ImportReference(type2));
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(value3);
			}
			return null;
		}

		public virtual bool DefaultParser(MonoModder mod, MethodBody body, Instruction instr, ref int instri)
		{
			return true;
		}

		public virtual TypeReference FindType(string name)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, false);
		}

		public virtual TypeReference FindType(string name, bool runtimeName)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, runtimeName);
		}

		protected virtual TypeReference FindType(ModuleDefinition main, string fullName, Stack<ModuleDefinition> crawled)
		{
			TypeReference type;
			if ((type = main.GetType(fullName, false)) != null)
			{
				return type;
			}
			if (fullName.StartsWith("<PrivateImplementationDetails>/"))
			{
				return null;
			}
			if (crawled.Contains(main))
			{
				return null;
			}
			crawled.Push(main);
			foreach (ModuleDefinition item in DependencyMap[main])
			{
				if ((!RemovePatchReferences || !((AssemblyNameReference)item.Assembly.Name).Name.EndsWith(".mm")) && (type = FindType(item, fullName, crawled)) != null)
				{
					return type;
				}
			}
			return null;
		}

		public virtual TypeReference FindTypeDeep(string name)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			TypeReference val = FindType(name, runtimeName: false);
			if (val != null)
			{
				return val;
			}
			Stack<ModuleDefinition> crawled = new Stack<ModuleDefinition>();
			val = null;
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition key = mod;
				foreach (ModuleDefinition item in DependencyMap[key])
				{
					if ((val = FindType(item, name, crawled)) != null)
					{
						IMetadataScope scope = val.Scope;
						AssemblyNameReference dllRef = (AssemblyNameReference)(object)((scope is AssemblyNameReference) ? scope : null);
						if (dllRef != null && !((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference n) => n.Name == dllRef.Name))
						{
							Module.AssemblyReferences.Add(dllRef);
						}
						return Module.ImportReference(val);
					}
				}
			}
			return null;
		}

		public virtual void PrePatchModule(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PrePatchType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<ModuleReference> enumerator2 = mod.ModuleReferences.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					ModuleReference current2 = enumerator2.Current;
					if (!Module.ModuleReferences.Contains(current2))
					{
						Module.ModuleReferences.Add(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<Resource> enumerator3 = mod.Resources.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					Resource current3 = enumerator3.Current;
					if (current3 is EmbeddedResource)
					{
						Module.Resources.Add((Resource)new EmbeddedResource(current3.Name.StartsWith(((AssemblyNameReference)mod.Assembly.Name).Name) ? (((AssemblyNameReference)Module.Assembly.Name).Name + current3.Name.Substring(((AssemblyNameReference)mod.Assembly.Name).Name.Length)) : current3.Name, current3.Attributes, ((EmbeddedResource)current3).GetResourceData()));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
		}

		public virtual void PrePatchType(TypeDefinition type, bool forceAdd = false)
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Expected O, but got Unknown
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Expected O, but got Unknown
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module) || (((MemberReference)type).FullName == "MonoMod.MonoModRules" && !forceAdd))
			{
				return;
			}
			TypeReference val = (forceAdd ? null : Module.GetType(patchFullName, false));
			TypeDefinition val2 = ((val != null) ? Extensions.SafeResolve(val) : null);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModReplace") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					if (val2.DeclaringType == null)
					{
						Module.Types.Remove(val2);
					}
					else
					{
						val2.DeclaringType.NestedTypes.Remove(val2);
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			else if (val != null)
			{
				PrePatchNested(type);
				return;
			}
			LogVerbose("[PrePatchType] Adding " + patchFullName + " to the target module.");
			TypeDefinition val3 = new TypeDefinition(((TypeReference)type).Namespace, ((MemberReference)type).Name, type.Attributes, type.BaseType);
			Enumerator<GenericParameter> enumerator = ((TypeReference)type).GenericParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					GenericParameter current = enumerator.Current;
					((TypeReference)val3).GenericParameters.Add(Extensions.Clone(current));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<InterfaceImplementation> enumerator2 = type.Interfaces.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					InterfaceImplementation current2 = enumerator2.Current;
					val3.Interfaces.Add(current2);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			val3.ClassSize = type.ClassSize;
			if (type.DeclaringType != null)
			{
				val3.DeclaringType = Extensions.Relink((TypeReference)(object)type.DeclaringType, new Relinker(Relinker), (IGenericParameterProvider)(object)val3).Resolve();
				val3.DeclaringType.NestedTypes.Add(val3);
			}
			else
			{
				Module.Types.Add(val3);
			}
			val3.PackingSize = type.PackingSize;
			Extensions.AddRange<SecurityDeclaration>(val3.SecurityDeclarations, (IEnumerable<SecurityDeclaration>)type.SecurityDeclarations);
			val3.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
			val = (TypeReference)(object)val3;
			PrePatchNested(type);
		}

		protected virtual void PrePatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PrePatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchModule(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					if ((((TypeReference)current).Namespace == "MonoMod" || ((TypeReference)current).Namespace.StartsWith("MonoMod.")) && ((MemberReference)current.BaseType).FullName == "System.Attribute")
					{
						PatchType(current);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current2 = enumerator.Current;
					if ((!(((TypeReference)current2).Namespace == "MonoMod") && !((TypeReference)current2).Namespace.StartsWith("MonoMod.")) || !(((MemberReference)current2.BaseType).FullName == "System.Attribute"))
					{
						PatchType(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchType(TypeDefinition type)
		{
			//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_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			TypeReference type2 = Module.GetType(patchFullName, false);
			if (type2 == null)
			{
				return;
			}
			TypeDefinition val = ((type2 != null) ? Extensions.SafeResolve(type2) : null);
			Enumerator<CustomAttribute> enumerator;
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore") && val != null)
				{
					enumerator = type.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				PatchNested(type);
				return;
			}
			if (patchFullName == ((MemberReference)type).FullName)
			{
				LogVerbose("[PatchType] Patching type " + patchFullName);
			}
			else
			{
				LogVerbose("[PatchType] Patching type " + patchFullName + " (prefixed: " + ((MemberReference)type).FullName + ")");
			}
			enumerator = type.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					if (!Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)val, ((MemberReference)current2.AttributeType).FullName))
					{
						val.CustomAttributes.Add(Extensions.Clone(current2));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			HashSet<MethodDefinition> hashSet = new HashSet<MethodDefinition>();
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current3 = enumerator2.Current;
					PatchProperty(val, current3, hashSet);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			HashSet<MethodDefinition> hashSet2 = new HashSet<MethodDefinition>();
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current4 = enumerator3.Current;
					PatchEvent(val, current4, hashSet2);
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current5 = enumerator4.Current;
					if (!hashSet.Contains(current5) && !hashSet2.Contains(current5))
					{
						PatchMethod(val, current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModEnumReplace"))
			{
				int num = 0;
				while (num < val.Fields.Count)
				{
					if (((MemberReference)val.Fields[num]).Name == "value__")
					{
						num++;
					}
					else
					{
						val.Fields.RemoveAt(num);
					}
				}
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current6 = enumerator5.Current;
					PatchField(val, current6);
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			PatchNested(type);
		}

		protected virtual void PatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchProperty(TypeDefinition targetType, PropertyDefinition prop, HashSet<MethodDefinition> propMethods = null)
		{
			//IL_006e: 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_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknown
			//IL_022b: Expected O, but got Unknown
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Expected O, but got Unknown
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Expected O, but got Unknown
			//IL_02b5: Expected O, but got Unknown
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			if (!MatchingConditionals((ICustomAttributeProvider)(object)prop, Module))
			{
				return;
			}
			((MemberReference)prop).Name = Extensions.GetPatchName((MemberReference)(object)prop);
			PropertyDefinition val = Extensions.FindProperty(targetType, ((MemberReference)prop).Name);
			string text = "<" + ((MemberReference)prop).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(prop.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = prop.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (prop.GetMethod != null)
				{
					propMethods?.Add(prop.GetMethod);
				}
				if (prop.SetMethod != null)
				{
					propMethods?.Add(prop.SetMethod);
				}
				enumerator2 = prop.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Properties.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.GetMethod != null)
					{
						targetType.Methods.Remove(val.GetMethod);
					}
					if (val.SetMethod != null)
					{
						targetType.Methods.Remove(val.SetMethod);
					}
					enumerator2 = val.OtherMethods.GetEnumerator();
					try
					{
						while (enumerator2.MoveNext())
						{
							MethodDefinition current3 = enumerator2.Current;
							targetType.Methods.Remove(current3);
						}
					}
					finally
					{
						((IDisposable)enumerator2).Dispose();
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				PropertyDefinition val4 = new PropertyDefinition(((MemberReference)prop).Name, prop.Attributes, ((PropertyReference)prop).PropertyType);
				val = val4;
				PropertyDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				Enumerator<ParameterDefinition> enumerator3 = ((PropertyReference)prop).Parameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						ParameterDefinition current4 = enumerator3.Current;
						((PropertyReference)val5).Parameters.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				val5.DeclaringType = targetType;
				targetType.Properties.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					val3 = val6;
					FieldDefinition val7 = val6;
					targetType.Fields.Add(val7);
				}
			}
			enumerator = prop.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current5 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current5));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition getMethod = prop.GetMethod;
			MethodDefinition getMethod2;
			if (getMethod != null && (getMethod2 = PatchMethod(targetType, getMethod)) != null)
			{
				val.GetMethod = getMethod2;
				propMethods?.Add(getMethod);
			}
			MethodDefinition setMethod = prop.SetMethod;
			if (setMethod != null && (getMethod2 = PatchMethod(targetType, setMethod)) != null)
			{
				val.SetMethod = getMethod2;
				propMethods?.Add(setMethod);
			}
			enumerator2 = prop.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current6 = enumerator2.Current;
					if ((getMethod2 = PatchMethod(targetType, current6)) != null)
					{
						val.OtherMethods.Add(getMethod2);
						propMethods?.Add(current6);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchEvent(TypeDefinition targetType, EventDefinition srcEvent, HashSet<MethodDefinition> propMethods = null)
		{
			//IL_005e: 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_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Expected O, but got Unknown
			//IL_0252: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			((MemberReference)srcEvent).Name = Extensions.GetPatchName((MemberReference)(object)srcEvent);
			EventDefinition val = Extensions.FindEvent(targetType, ((MemberReference)srcEvent).Name);
			string text = "<" + ((MemberReference)srcEvent).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(srcEvent.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = srcEvent.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (srcEvent.AddMethod != null)
				{
					propMethods?.Add(srcEvent.AddMethod);
				}
				if (srcEvent.RemoveMethod != null)
				{
					propMethods?.Add(srcEvent.RemoveMethod);
				}
				if (srcEvent.InvokeMethod != null)
				{
					propMethods?.Add(srcEvent.InvokeMethod);
				}
				enumerator2 = srcEvent.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Events.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.AddMethod != null)
					{
						targetType.Methods.Remove(val.AddMethod);
					}
					if (val.RemoveMethod != null)
					{
						targetType.Methods.Remove(val.RemoveMethod);
					}
					if (val.InvokeMethod != null)
					{
						targetType.Methods.Remove(val.InvokeMethod);
					}
					if (val.OtherMethods != null)
					{
						enumerator2 = val.OtherMethods.GetEnumerator();
						try
						{
							while (enumerator2.MoveNext())
							{
								MethodDefinition current3 = enumerator2.Current;
								targetType.Methods.Remove(current3);
							}
						}
						finally
						{
							((IDisposable)enumerator2).Dispose();
						}
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				EventDefinition val4 = new EventDefinition(((MemberReference)srcEvent).Name, srcEvent.Attributes, ((EventReference)srcEvent).EventType);
				val = val4;
				EventDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val5.DeclaringType = targetType;
				targetType.Events.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					targetType.Fields.Add(val6);
				}
			}
			enumerator = srcEvent.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current4 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current4));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition addMethod = srcEvent.AddMethod;
			MethodDefinition addMethod2;
			if (addMethod != null && (addMethod2 = PatchMethod(targetType, addMethod)) != null)
			{
				val.AddMethod = addMethod2;
				propMethods?.Add(addMethod);
			}
			MethodDefinition removeMethod = srcEvent.RemoveMethod;
			if (removeMethod != null && (addMethod2 = PatchMethod(targetType, removeMethod)) != null)
			{
				val.RemoveMethod = addMethod2;
				propMethods?.Add(removeMethod);
			}
			MethodDefinition invokeMethod = srcEvent.InvokeMethod;
			if (invokeMethod != null && (addMethod2 = PatchMethod(targetType, invokeMethod)) != null)
			{
				val.InvokeMethod = addMethod2;
				propMethods?.Add(invokeMethod);
			}
			enumerator2 = srcEvent.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current5 = enumerator2.Current;
					if ((addMethod2 = PatchMethod(targetType, current5)) != null)
					{
						val.OtherMethods.Add(addMethod2);
						propMethods?.Add(current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchField(TypeDefinition targetType, FieldDefinition field)
		{
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Expected O, but got Unknown
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)field.DeclaringType);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModNoNew") || SkipList.Contains(patchFullName + "::" + ((MemberReference)field).Name) || !MatchingConditionals((ICustomAttributeProvider)(object)field, Module))
			{
				return;
			}
			((MemberReference)field).Name = Extensions.GetPatchName((MemberReference)(object)field);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModReplace"))
			{
				FieldDefinition val = Extensions.FindField(targetType, ((MemberReference)field).Name);
				if (val != null)
				{
					targetType.Fields.Remove(val);
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			FieldDefinition val2 = Extensions.FindField(targetType, ((MemberReference)field).Name);
			Enumerator<CustomAttribute> enumerator;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModIgnore") && val2 != null)
			{
				enumerator = field.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
						{
							val2.CustomAttributes.Add(Extensions.Clone(current));
						}
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			if (val2 == null)
			{
				val2 = new FieldDefinition(((MemberReference)field).Name, field.Attributes, ((FieldReference)field).FieldType);
				val2.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val2.InitialValue = field.InitialValue;
				if (field.HasConstant)
				{
					val2.Constant = field.Constant;
				}
				targetType.Fields.Add(val2);
			}
			enumerator = field.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					val2.CustomAttributes.Add(Extensions.Clone(current2));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual MethodDefinition PatchMethod(TypeDefinition targetType, MethodDefinition method)
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Expected O, but got Unknown
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Unknown result type (might be due to invalid IL or missing references)
			//IL_0511: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Unknown result type (might be due to invalid IL or missing references)
			//IL_0569: Unknown result type (might be due to invalid IL or missing references)
			//IL_0453: Unknown result type (might be due to invalid IL or missing references)
			//IL_0458: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Expected O, but got Unknown
			//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_069a: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a1: Expected O, but got Unknown
			//IL_06be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0630: Unknown result type (might be due to invalid IL or missing references)
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Unknown result type (might be due to invalid IL or missing references)
			//IL_0680: Expected O, but got Unknown
			if (((MemberReference)method).Name.StartsWith("orig_") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginal"))
			{
				return null;
			}
			if (!AllowedSpecialName(method, targetType) || !MatchingConditionals((ICustomAttributeProvider)(object)method, Module))
			{
				return null;
			}
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)targetType);
			if (SkipList.Contains(Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false)))
			{
				return null;
			}
			((MemberReference)method).Name = Extensions.GetPatchName((MemberReference)(object)method);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				if (!method.IsSpecialName && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginalName"))
				{
					CustomAttribute val = new CustomAttribute(GetMonoModOriginalNameCtor());
					val.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)("orig_" + ((MemberReference)method).Name)));
					method.CustomAttributes.Add(val);
				}
				((MemberReference)method).Name = (method.IsStatic ? ".cctor" : ".ctor");
				method.IsSpecialName = true;
				method.IsRuntimeSpecialName = true;
			}
			MethodDefinition val2 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false), true);
			MethodDefinition obj = method;
			string text = patchFullName;
			MethodDefinition val3 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)obj, method.GetOriginalName(), text, true, false), true);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModIgnore"))
			{
				if (val2 != null)
				{
					Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val2.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				return null;
			}
			if (val2 == null && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModNoNew"))
			{
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					targetType.Methods.Remove(val2);
				}
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModReplace"))
			{
				if (val2 != null)
				{
					val2.CustomAttributes.Clear();
					val2.Attributes = method.Attributes;
					val2.IsPInvokeImpl = method.IsPInvokeImpl;
					val2.ImplAttributes = method.ImplAttributes;
				}
			}
			else if (val2 != null && val3 == null)
			{
				val3 = Extensions.Clone(val2, (MethodDefinition)null);
				((MemberReference)val3).Name = method.GetOriginalName();
				val3.Attributes = (MethodAttributes)(val2.Attributes & 0xF7FF & 0xEFFF);
				((MemberReference)val3).MetadataToken = GetMetadataToken((TokenType)100663296);
				val3.IsVirtual = false;
				val3.Overrides.Clear();
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current2 = enumerator2.Current;
						val3.Overrides.Add(current2);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val3.CustomAttributes.Add(new CustomAttribute(GetMonoModOriginalCtor()));
				MethodDefinition val4 = Extensions.FindMethod(method.DeclaringType, Extensions.GetID((MethodReference)(object)method, method.GetOriginalName(), (string)null, true, false), true);
				if (val4 != null)
				{
					Enumerator<CustomAttribute> enumerator = val4.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current3 = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName))
							{
								val3.CustomAttributes.Add(Extensions.Clone(current3));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				targetType.Methods.Add(val3);
			}
			if (val3 != null && method.IsConstructor && method.IsStatic && method.HasBody && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				Collection<Instruction> instructions = method.Body.Instructions;
				ILProcessor iLProcessor = method.Body.GetILProcessor();
				iLProcessor.InsertBefore(instructions[instructions.Count - 1], iLProcessor.Create(OpCodes.Call, (MethodReference)(object)val3));
			}
			if (val2 != null)
			{
				val2.Body = Extensions.Clone(method.Body, val2);
				val2.IsManaged = method.IsManaged;
				val2.IsIL = method.IsIL;
				val2.IsNative = method.IsNative;
				val2.PInvokeInfo = method.PInvokeInfo;
				val2.IsPreserveSig = method.IsPreserveSig;
				val2.IsInternalCall = method.IsInternalCall;
				val2.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current4 = enumerator.Current;
						val2.CustomAttributes.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				method = val2;
			}
			else
			{
				MethodDefinition val5 = new MethodDefinition(((MemberReference)method).Name, method.Attributes, Module.TypeSystem.Void);
				((MemberReference)val5).MetadataToken = GetMetadataToken((TokenType)100663296);
				((MethodReference)val5).CallingConvention = ((MethodReference)method).CallingConvention;
				((MethodReference)val5).ExplicitThis = ((MethodReference)method).ExplicitThis;
				((MethodReference)val5).MethodReturnType = ((MethodReference)method).MethodReturnType;
				val5.Attributes = method.Attributes;
				val5.ImplAttributes = method.ImplAttributes;
				val5.SemanticsAttributes = method.SemanticsAttributes;
				val5.DeclaringType = targetType;
				((MethodReference)val5).ReturnType = ((MethodReference)method).ReturnType;
				val5.Body = Extensions.Clone(method.Body, val5);
				val5.PInvokeInfo = method.PInvokeInfo;
				val5.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<GenericParameter> enumerator3 = ((MethodReference)method).GenericParameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						GenericParameter current5 = enumerator3.Current;
						((MethodReference)val5).GenericParameters.Add(Extensions.Clone(current5));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				Enumerator<ParameterDefinition> enumerator4 = ((MethodReference)method).Parameters.GetEnumerator();
				try
				{
					while (enumerator4.MoveNext())
					{
						ParameterDefinition current6 = enumerator4.Current;
						((MethodReference)val5).Parameters.Add(Extensions.Clone(current6));
					}
				}
				finally
				{
					((IDisposable)enumerator4).Dispose();
				}
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current7 = enumerator.Current;
						val5.CustomAttributes.Add(Extensions.Clone(current7));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current8 = enumerator2.Current;
						val5.Overrides.Add(current8);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				targetType.Methods.Add(val5);
				method = val5;
			}
			if (val3 != null)
			{
				CustomAttribute val6 = new CustomAttribute(GetMonoModOriginalNameCtor());
				val6.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)((MemberReference)val3).Name));
				method.CustomAttributes.Add(val6);
			}
			return method;
		}

		public virtual void PatchRefs()
		{
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			if (!UpgradeMSCORLIB.HasValue)
			{
				Version fckUnity = new Version(2, 0, 5, 0);
				UpgradeMSCORLIB = ((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference x) => x.Version == fckUnity);
			}
			if (UpgradeMSCORLIB.Value)
			{
				List<AssemblyNameReference> list = new List<AssemblyNameReference>();
				for (int i = 0; i < Module.AssemblyReferences.Count; i++)
				{
					AssemblyNameReference val = Module.AssemblyReferences[i];
					if (val.Name == "mscorlib")
					{
						list.Add(val);
					}
				}
				if (list.Count > 1)
				{
					AssemblyNameReference val2 = list.OrderByDescending((AssemblyNameReference x) => x.Version).First();
					if (DependencyCache.TryGetValue(val2.FullName, out var value))
					{
						for (int j = 0; j < Module.AssemblyReferences.Count; j++)
						{
							AssemblyNameReference val3 = Module.AssemblyReferences[j];
							if (val3.Name == "mscorlib" && val2.Version > val3.Version)
							{
								LogVerbose("[PatchRefs] Removing and relinking duplicate mscorlib: " + val3.Version);
								RelinkModuleMap[val3.FullName] = value;
								Module.AssemblyReferences.RemoveAt(j);
								j--;
							}
						}
					}
				}
			}
			Enumerator<TypeDefinition> enumerator = Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefs(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefsInType(TypeDefinition type)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Expected O, but got Unknown
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Expected O, but got Unknown
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Expected O, but got Unknown
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Expected O, but got Unknown
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Expected O, but got Unknown
			LogVerbose($"[VERBOSE] [PatchRefsInType] Patching refs in {type}");
			if (type.BaseType != null)
			{
				type.BaseType = Extensions.Relink(type.BaseType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int i = 0; i < ((TypeReference)type).GenericParameters.Count; i++)
			{
				((TypeReference)type).GenericParameters[i] = Extensions.Relink(((TypeReference)type).GenericParameters[i], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int j = 0; j < type.Interfaces.Count; j++)
			{
				InterfaceImplementation obj = type.Interfaces[j];
				InterfaceImplementation val = new InterfaceImplementation(Extensions.Relink(obj.InterfaceType, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
				Enumerator<CustomAttribute> enumerator = obj.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						val.CustomAttributes.Add(Extensions.Relink(current, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				type.Interfaces[j] = val;
			}
			for (int k = 0; k < type.CustomAttributes.Count; k++)
			{
				type.CustomAttributes[k] = Extensions.Relink(type.CustomAttributes[k], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current2 = enumerator2.Current;
					((PropertyReference)current2).PropertyType = Extensions.Relink(((PropertyReference)current2).PropertyType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int l = 0; l < current2.CustomAttributes.Count; l++)
					{
						current2.CustomAttributes[l] = Extensions.Relink(current2.CustomAttributes[l], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current3 = enumerator3.Current;
					((EventReference)current3).EventType = Extensions.Relink(((EventReference)current3).EventType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int m = 0; m < current3.CustomAttributes.Count; m++)
					{
						current3.CustomAttributes[m] = Extensions.Relink(current3.CustomAttributes[m], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current4 = enumerator4.Current;
					PatchRefsInMethod(current4);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current5 = enumerator5.Current;
					((FieldReference)current5).FieldType = Extensions.Relink(((FieldReference)current5).FieldType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int n = 0; n < current5.CustomAttributes.Count; n++)
					{
						current5.CustomAttributes[n] = Extensions.Relink(current5.CustomAttributes[n], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			for (int num = 0; num < type.NestedTypes.Count; num++)
			{
				PatchRefsInType(type.NestedTypes[num]);
			}
		}

		public virtual void PatchRefsInMethod(MethodDefinition method)
		{
			//IL_0030: Unknown result t

BepInEx/patchers/ValheimModding-HookGenPatcher/BepInEx.MonoMod.HookGenPatcher/MonoMod.RuntimeDetour.HookGen.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("Auto-generate hook helper .dlls, hook arbitrary methods via events: On.Namespace.Type.Method += YourHandlerHere;")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod.RuntimeDetour.HookGen")]
[assembly: AssemblyTitle("MonoMod.RuntimeDetour.HookGen")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	internal static class MMDbgLog
	{
		public static readonly string Tag;

		public static TextWriter Writer;

		public static bool Debugging;

		static MMDbgLog()
		{
			Tag = typeof(MMDbgLog).Assembly.GetName().Name;
			if (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1" || (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG")?.ToLowerInvariant()?.Contains(Tag.ToLowerInvariant())).GetValueOrDefault())
			{
				Start();
			}
		}

		public static void WaitForDebugger()
		{
			if (!Debugging)
			{
				Debugging = true;
				Debugger.Launch();
				Thread.Sleep(6000);
				Debugger.Break();
			}
		}

		public static void Start()
		{
			if (Writer != null)
			{
				return;
			}
			string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH");
			if (text == "-")
			{
				Writer = Console.Out;
				return;
			}
			if (string.IsNullOrEmpty(text))
			{
				text = "mmdbglog.txt";
			}
			text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text));
			try
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
			catch
			{
			}
			try
			{
				string directoryName = Path.GetDirectoryName(text);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8);
			}
			catch
			{
			}
		}

		public static void Log(string str)
		{
			TextWriter writer = Writer;
			if (writer != null)
			{
				writer.WriteLine(str);
				writer.Flush();
			}
		}

		public static T Log<T>(string str, T value)
		{
			TextWriter writer = Writer;
			if (writer == null)
			{
				return value;
			}
			writer.WriteLine(string.Format(str, value));
			writer.Flush();
			return value;
		}
	}
}
namespace MonoMod.RuntimeDetour.HookGen
{
	public class HookGenerator
	{
		private const string ObsoleteMessageBackCompat = "This method only exists for backwards-compatibility purposes.";

		private static readonly Regex NameVerifyRegex;

		private static readonly Dictionary<Type, string> ReflTypeNameMap;

		private static readonly Dictionary<string, string> TypeNameMap;

		public MonoModder Modder;

		public ModuleDefinition OutputModule;

		public string Namespace;

		public string NamespaceIL;

		public bool HookOrig;

		public bool HookPrivate;

		public string HookExtName;

		public ModuleDefinition module_RuntimeDetour;

		public ModuleDefinition module_Utils;

		public TypeReference t_MulticastDelegate;

		public TypeReference t_IAsyncResult;

		public TypeReference t_AsyncCallback;

		public TypeReference t_MethodBase;

		public TypeReference t_RuntimeMethodHandle;

		public TypeReference t_EditorBrowsableState;

		public MethodReference m_Object_ctor;

		public MethodReference m_ObsoleteAttribute_ctor;

		public MethodReference m_EditorBrowsableAttribute_ctor;

		public MethodReference m_GetMethodFromHandle;

		public MethodReference m_Add;

		public MethodReference m_Remove;

		public MethodReference m_Modify;

		public MethodReference m_Unmodify;

		public TypeReference t_ILManipulator;

		static HookGenerator()
		{
			NameVerifyRegex = new Regex("[^a-zA-Z]");
			ReflTypeNameMap = new Dictionary<Type, string>
			{
				{
					typeof(string),
					"string"
				},
				{
					typeof(object),
					"object"
				},
				{
					typeof(bool),
					"bool"
				},
				{
					typeof(byte),
					"byte"
				},
				{
					typeof(char),
					"char"
				},
				{
					typeof(decimal),
					"decimal"
				},
				{
					typeof(double),
					"double"
				},
				{
					typeof(short),
					"short"
				},
				{
					typeof(int),
					"int"
				},
				{
					typeof(long),
					"long"
				},
				{
					typeof(sbyte),
					"sbyte"
				},
				{
					typeof(float),
					"float"
				},
				{
					typeof(ushort),
					"ushort"
				},
				{
					typeof(uint),
					"uint"
				},
				{
					typeof(ulong),
					"ulong"
				},
				{
					typeof(void),
					"void"
				}
			};
			TypeNameMap = new Dictionary<string, string>();
			foreach (KeyValuePair<Type, string> item in ReflTypeNameMap)
			{
				TypeNameMap[item.Key.FullName] = item.Value;
			}
		}

		public HookGenerator(MonoModder modder, string name)
		{
			//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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Expected O, but got Unknown
			//IL_0326: Expected O, but got Unknown
			Modder = modder;
			OutputModule = ModuleDefinition.CreateModule(name, new ModuleParameters
			{
				Architecture = modder.Module.Architecture,
				AssemblyResolver = modder.Module.AssemblyResolver,
				Kind = (ModuleKind)0,
				Runtime = modder.Module.Runtime
			});
			modder.MapDependencies();
			Extensions.AddRange<AssemblyNameReference>(OutputModule.AssemblyReferences, (IEnumerable<AssemblyNameReference>)modder.Module.AssemblyReferences);
			modder.DependencyMap[OutputModule] = new List<ModuleDefinition>(modder.DependencyMap[modder.Module]);
			Namespace = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE");
			if (string.IsNullOrEmpty(Namespace))
			{
				Namespace = "On";
			}
			NamespaceIL = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL");
			if (string.IsNullOrEmpty(NamespaceIL))
			{
				NamespaceIL = "IL";
			}
			HookOrig = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG") == "1";
			HookPrivate = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE") == "1";
			modder.MapDependency(modder.Module, "MonoMod.RuntimeDetour", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.RuntimeDetour", out module_RuntimeDetour))
			{
				throw new FileNotFoundException("MonoMod.RuntimeDetour not found!");
			}
			modder.MapDependency(modder.Module, "MonoMod.Utils", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.Utils", out module_Utils))
			{
				throw new FileNotFoundException("MonoMod.Utils not found!");
			}
			t_MulticastDelegate = OutputModule.ImportReference(modder.FindType("System.MulticastDelegate"));
			t_IAsyncResult = OutputModule.ImportReference(modder.FindType("System.IAsyncResult"));
			t_AsyncCallback = OutputModule.ImportReference(modder.FindType("System.AsyncCallback"));
			t_MethodBase = OutputModule.ImportReference(modder.FindType("System.Reflection.MethodBase"));
			t_RuntimeMethodHandle = OutputModule.ImportReference(modder.FindType("System.RuntimeMethodHandle"));
			t_EditorBrowsableState = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableState"));
			TypeDefinition type = module_RuntimeDetour.GetType("MonoMod.RuntimeDetour.HookGen.HookEndpointManager");
			t_ILManipulator = OutputModule.ImportReference((TypeReference)(object)module_Utils.GetType("MonoMod.Cil.ILContext/Manipulator"));
			m_Object_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.Object").Resolve(), "System.Void .ctor()", true));
			m_ObsoleteAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ObsoleteAttribute").Resolve(), "System.Void .ctor(System.String,System.Boolean)", true));
			m_EditorBrowsableAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ComponentModel.EditorBrowsableAttribute").Resolve(), "System.Void .ctor(System.ComponentModel.EditorBrowsableState)", true));
			ModuleDefinition outputModule = OutputModule;
			MethodReference val = new MethodReference("GetMethodFromHandle", t_MethodBase, t_MethodBase);
			val.Parameters.Add(new ParameterDefinition(t_RuntimeMethodHandle));
			m_GetMethodFromHandle = outputModule.ImportReference(val);
			m_Add = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Add", true));
			m_Remove = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Remove", true));
			m_Modify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Modify", true));
			m_Unmodify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Unmodify", true));
		}

		public void Generate()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = Modder.Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					GenerateFor(current, out var hookType, out var hookILType);
					if (hookType != null && hookILType != null && !((TypeReference)hookType).IsNested)
					{
						OutputModule.Types.Add(hookType);
						OutputModule.Types.Add(hookILType);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void GenerateFor(TypeDefinition type, out TypeDefinition hookType, out TypeDefinition hookILType)
		{
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			hookType = (hookILType = null);
			if (((TypeReference)type).HasGenericParameters || type.IsRuntimeSpecialName || ((MemberReference)type).Name.StartsWith("<") || (!HookPrivate && type.IsNotPublic))
			{
				return;
			}
			Modder.LogVerbose("[HookGen] Generating for type " + ((MemberReference)type).FullName);
			hookType = new TypeDefinition(((TypeReference)type).IsNested ? null : (Namespace + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			hookILType = new TypeDefinition(((TypeReference)type).IsNested ? null : (NamespaceIL + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			bool flag = false;
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					flag |= GenerateFor(hookType, hookILType, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<TypeDefinition> enumerator2 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					TypeDefinition current2 = enumerator2.Current;
					GenerateFor(current2, out var hookType2, out var hookILType2);
					if (hookType2 != null && hookILType2 != null)
					{
						flag = true;
						hookType.NestedTypes.Add(hookType2);
						hookILType.NestedTypes.Add(hookILType2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			if (!flag)
			{
				hookType = (hookILType = null);
			}
		}

		public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method)
		{
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Expected O, but got Unknown
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Expected O, but got Unknown
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_0387: Expected O, but got Unknown
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_039c: Expected O, but got Unknown
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03aa: Expected O, but got Unknown
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Expected O, but got Unknown
			//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0407: Unknown result type (might be due to invalid IL or missing references)
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_044a: Expected O, but got Unknown
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Expected O, but got Unknown
			//IL_0463: Unknown result type (might be due to invalid IL or missing references)
			//IL_046d: Expected O, but got Unknown
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0487: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04af: Expected O, but got Unknown
			//IL_04be: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0501: Expected O, but got Unknown
			//IL_0533: Unknown result type (might be due to invalid IL or missing references)
			//IL_053a: Expected O, but got Unknown
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_0553: Expected O, but got Unknown
			//IL_0557: Unknown result type (might be due to invalid IL or missing references)
			//IL_0561: Expected O, but got Unknown
			//IL_056e: Unknown result type (might be due to invalid IL or missing references)
			//IL_057b: Unknown result type (might be due to invalid IL or missing references)
			//IL_058c: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a3: Expected O, but got Unknown
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0601: Expected O, but got Unknown
			//IL_0610: Unknown result type (might be due to invalid IL or missing references)
			//IL_061a: Expected O, but got Unknown
			//IL_061e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0628: Expected O, but got Unknown
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0642: Unknown result type (might be due to invalid IL or missing references)
			//IL_0653: Unknown result type (might be due to invalid IL or missing references)
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Expected O, but got Unknown
			//IL_0679: Unknown result type (might be due to invalid IL or missing references)
			//IL_0685: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c0: Expected O, but got Unknown
			if (((MethodReference)method).HasGenericParameters || method.IsAbstract || (method.IsSpecialName && !method.IsConstructor))
			{
				return false;
			}
			if (!HookOrig && ((MemberReference)method).Name.StartsWith("orig_"))
			{
				return false;
			}
			if (!HookPrivate && method.IsPrivate)
			{
				return false;
			}
			string name = GetFriendlyName((MethodReference)(object)method);
			bool flag = true;
			if (((MethodReference)method).Parameters.Count == 0)
			{
				flag = false;
			}
			IEnumerable<MethodDefinition> source = null;
			if (flag)
			{
				source = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name && other != method);
				if (source.Count() == 0)
				{
					flag = false;
				}
			}
			if (flag)
			{
				StringBuilder stringBuilder = new StringBuilder();
				for (int parami = 0; parami < ((MethodReference)method).Parameters.Count; parami++)
				{
					ParameterDefinition param = ((MethodReference)method).Parameters[parami];
					if (!TypeNameMap.TryGetValue(((MemberReference)((ParameterReference)param).ParameterType).FullName, out var typeName))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: false);
					}
					if (source.Any(delegate(MethodDefinition other)
					{
						ParameterDefinition val11 = ((IEnumerable<ParameterDefinition>)((MethodReference)other).Parameters).ElementAtOrDefault(parami);
						return val11 != null && GetFriendlyName(((ParameterReference)val11).ParameterType, full: false) == typeName && ((ParameterReference)val11).ParameterType.Namespace != ((ParameterReference)param).ParameterType.Namespace;
					}))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: true);
					}
					stringBuilder.Append("_");
					stringBuilder.Append(typeName.Replace(".", "").Replace("`", ""));
				}
				name += stringBuilder.ToString();
			}
			if (Extensions.FindEvent(hookType, name) != null)
			{
				int num = 1;
				string text;
				while (Extensions.FindEvent(hookType, text = name + "_" + num) != null)
				{
					num++;
				}
				name = text;
			}
			TypeDefinition val = GenerateDelegateFor(method);
			((MemberReference)val).Name = "orig_" + name;
			val.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val);
			TypeDefinition val2 = GenerateDelegateFor(method);
			((MemberReference)val2).Name = "hook_" + name;
			((MethodReference)Extensions.FindMethod(val2, "Invoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			((MethodReference)Extensions.FindMethod(val2, "BeginInvoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			val2.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val2);
			MethodReference val3 = OutputModule.ImportReference((MethodReference)(object)method);
			MethodDefinition val4 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val4).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val4.Body = new MethodBody(val4);
			ILProcessor iLProcessor = val4.Body.GetILProcessor();
			iLProcessor.Emit(OpCodes.Ldtoken, val3);
			iLProcessor.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor.Emit(OpCodes.Ldarg_0);
			GenericInstanceMethod val5 = new GenericInstanceMethod(m_Add);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor.Emit(OpCodes.Ret);
			hookType.Methods.Add(val4);
			MethodDefinition val6 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val6).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val6.Body = new MethodBody(val6);
			ILProcessor iLProcessor2 = val6.Body.GetILProcessor();
			iLProcessor2.Emit(OpCodes.Ldtoken, val3);
			iLProcessor2.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor2.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Remove);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor2.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor2.Emit(OpCodes.Ret);
			hookType.Methods.Add(val6);
			EventDefinition val7 = new EventDefinition(name, (EventAttributes)0, (TypeReference)(object)val2)
			{
				AddMethod = val4,
				RemoveMethod = val6
			};
			hookType.Events.Add(val7);
			MethodDefinition val8 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val8).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val8.Body = new MethodBody(val8);
			ILProcessor iLProcessor3 = val8.Body.GetILProcessor();
			iLProcessor3.Emit(OpCodes.Ldtoken, val3);
			iLProcessor3.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor3.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Modify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor3.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor3.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val8);
			MethodDefinition val9 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val9).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val9.Body = new MethodBody(val9);
			ILProcessor iLProcessor4 = val9.Body.GetILProcessor();
			iLProcessor4.Emit(OpCodes.Ldtoken, val3);
			iLProcessor4.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor4.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Unmodify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor4.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor4.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val9);
			EventDefinition val10 = new EventDefinition(name, (EventAttributes)0, t_ILManipulator)
			{
				AddMethod = val8,
				RemoveMethod = val9
			};
			hookILType.Events.Add(val10);
			return true;
		}

		public TypeDefinition GenerateDelegateFor(MethodDefinition method)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Expected O, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Expected O, but got Unknown
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Expected O, but got Unknown
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Expected O, but got Unknown
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Expected O, but got Unknown
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Expected O, but got Unknown
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Expected O, but got Unknown
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Expected O, but got Unknown
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Expected O, but got Unknown
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Expected O, but got Unknown
			//IL_0367: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Expected O, but got Unknown
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Expected O, but got Unknown
			string name = GetFriendlyName((MethodReference)(object)method);
			int num = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name).ToList().IndexOf(method);
			if (num != 0)
			{
				string suffix = num.ToString();
				do
				{
					name = name + "_" + suffix;
				}
				while (((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Any((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name + suffix));
			}
			name = "d_" + name;
			TypeDefinition val = new TypeDefinition((string)null, (string)null, (TypeAttributes)258, t_MulticastDelegate);
			MethodDefinition val2 = new MethodDefinition(".ctor", (MethodAttributes)6278, OutputModule.TypeSystem.Void)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.Object));
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.IntPtr));
			val2.Body = new MethodBody(val2);
			val.Methods.Add(val2);
			MethodDefinition val3 = new MethodDefinition("Invoke", (MethodAttributes)454, ImportVisible(((MethodReference)method).ReturnType))
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			if (!method.IsStatic)
			{
				TypeReference val4 = ImportVisible((TypeReference)(object)method.DeclaringType);
				if (((TypeReference)method.DeclaringType).IsValueType)
				{
					val4 = (TypeReference)new ByReferenceType(val4);
				}
				((MethodReference)val3).Parameters.Add(new ParameterDefinition("self", (ParameterAttributes)0, val4));
			}
			Enumerator<ParameterDefinition> enumerator = ((MethodReference)method).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current = enumerator.Current;
					((MethodReference)val3).Parameters.Add(new ParameterDefinition(((ParameterReference)current).Name, (ParameterAttributes)(current.Attributes & 0xFFEF & 0xEFFF), ImportVisible(((ParameterReference)current).ParameterType)));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			val3.Body = new MethodBody(val3);
			val.Methods.Add(val3);
			MethodDefinition val5 = new MethodDefinition("BeginInvoke", (MethodAttributes)454, t_IAsyncResult)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			enumerator = ((MethodReference)val3).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current2 = enumerator.Current;
					((MethodReference)val5).Parameters.Add(new ParameterDefinition(((ParameterReference)current2).Name, current2.Attributes, ((ParameterReference)current2).ParameterType));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			((MethodReference)val5).Parameters.Add(new ParameterDefinition("callback", (ParameterAttributes)0, t_AsyncCallback));
			((MethodReference)val5).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, OutputModule.TypeSystem.Object));
			val5.Body = new MethodBody(val5);
			val.Methods.Add(val5);
			MethodDefinition val6 = new MethodDefinition("EndInvoke", (MethodAttributes)454, OutputModule.TypeSystem.Object)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val6).Parameters.Add(new ParameterDefinition("result", (ParameterAttributes)0, t_IAsyncResult));
			val6.Body = new MethodBody(val6);
			val.Methods.Add(val6);
			return val;
		}

		private string GetFriendlyName(MethodReference method)
		{
			string text = ((MemberReference)method).Name;
			if (text.StartsWith("."))
			{
				text = text.Substring(1);
			}
			return text.Replace('.', '_');
		}

		private string GetFriendlyName(TypeReference type, bool full)
		{
			if (type is TypeSpecification)
			{
				StringBuilder stringBuilder = new StringBuilder();
				BuildFriendlyName(stringBuilder, type, full);
				return stringBuilder.ToString();
			}
			if (!full)
			{
				return ((MemberReference)type).Name;
			}
			return ((MemberReference)type).FullName;
		}

		private void BuildFriendlyName(StringBuilder builder, TypeReference type, bool full)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (!(type is TypeSpecification))
			{
				builder.Append((full ? ((MemberReference)type).FullName : ((MemberReference)type).Name).Replace("_", ""));
				return;
			}
			if (type.IsByReference)
			{
				builder.Append("ref");
			}
			else if (type.IsPointer)
			{
				builder.Append("ptr");
			}
			BuildFriendlyName(builder, ((TypeSpecification)type).ElementType, full);
			if (type.IsArray)
			{
				builder.Append("Array");
			}
		}

		private bool IsPublic(TypeDefinition typeDef)
		{
			if (typeDef != null && (typeDef.IsNestedPublic || typeDef.IsPublic))
			{
				return !typeDef.IsNotPublic;
			}
			return false;
		}

		private bool HasPublicArgs(GenericInstanceType typeGen)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeReference> enumerator = typeGen.GenericArguments.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeReference current = enumerator.Current;
					if (current.IsGenericParameter)
					{
						return false;
					}
					GenericInstanceType val = (GenericInstanceType)(object)((current is GenericInstanceType) ? current : null);
					if (val != null && !HasPublicArgs(val))
					{
						return false;
					}
					if (!IsPublic(Extensions.SafeResolve(current)))
					{
						return false;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return true;
		}

		private TypeReference ImportVisible(TypeReference typeRef)
		{
			for (TypeDefinition val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null); val != null; val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null))
			{
				GenericInstanceType val2 = (GenericInstanceType)(object)((typeRef is GenericInstanceType) ? typeRef : null);
				if (val2 == null || HasPublicArgs(val2))
				{
					TypeDefinition val3 = val;
					while (true)
					{
						if (val3 != null)
						{
							if (IsPublic(val3) && (val3 == val || !((TypeReference)val3).HasGenericParameters))
							{
								val3 = val3.DeclaringType;
								continue;
							}
							if (!val.IsEnum)
							{
								break;
							}
							typeRef = ((FieldReference)Extensions.FindField(val, "value__")).FieldType;
						}
						try
						{
							return OutputModule.ImportReference(typeRef);
						}
						catch
						{
							return OutputModule.TypeSystem.Object;
						}
					}
				}
				typeRef = val.BaseType;
			}
			return OutputModule.TypeSystem.Object;
		}

		private CustomAttribute GenerateObsolete(string message, bool error)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_ObsoleteAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.String, (object)message));
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.Boolean, (object)error));
			return val;
		}

		private CustomAttribute GenerateEditorBrowsable(EditorBrowsableState state)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_EditorBrowsableAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(t_EditorBrowsableState, (object)state));
			return val;
		}
	}
	internal class Program
	{
		private static void Main(string[] args)
		{
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Expected O, but got Unknown
			Console.WriteLine("MonoMod.RuntimeDetour.HookGen " + typeof(Program).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod " + typeof(MonoModder).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod.RuntimeDetour " + typeof(Detour).Assembly.GetName().Version);
			if (args.Length == 0)
			{
				Console.WriteLine("No valid arguments (assembly path) passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			int num = 0;
			for (int i = 0; i < args.Length; i++)
			{
				if (args[i] == "--namespace" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE", args[i]);
					continue;
				}
				if (args[i] == "--namespace-il" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL", args[i]);
					continue;
				}
				if (args[i] == "--orig")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG", "1");
					continue;
				}
				if (args[i] == "--private")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
					continue;
				}
				num = i;
				break;
			}
			if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW")))
			{
				Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			}
			if (num >= args.Length)
			{
				Console.WriteLine("No assembly path passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			string text = args[num];
			string text2 = ((args.Length != 1 && num != args.Length - 1) ? args[^1] : null);
			text2 = text2 ?? Path.Combine(Path.GetDirectoryName(text), "MMHOOK_" + Path.ChangeExtension(Path.GetFileName(text), "dll"));
			MonoModder val = new MonoModder
			{
				InputPath = text,
				OutputPath = text2,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				val.Read();
				val.MapDependencies();
				if (File.Exists(text2))
				{
					val.Log("[HookGen] Clearing " + text2);
					File.Delete(text2);
				}
				val.Log("[HookGen] Starting HookGenerator");
				HookGenerator hookGenerator = new HookGenerator(val, Path.GetFileName(text2));
				ModuleDefinition outputModule = hookGenerator.OutputModule;
				try
				{
					hookGenerator.Generate();
					outputModule.Write(text2);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				val.Log("[HookGen] Done.");
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			if (Debugger.IsAttached)
			{
				Console.ReadKey();
			}
		}
	}
}

BepInEx/plugins/Advize-PlantEverything/Advize_PlantEverything.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Advize_PlantEverything.Configuration;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using UnityEngine;
using UnityEngine.UI;

[assembly: AssemblyFileVersion("1.13.7.0")]
[assembly: Guid("85f3bb36-d51d-4e6c-a523-feb593b3156f")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyProduct("Valheim Game Modification")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("Advize_PlantEverything")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.13.7.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<769212b1-5471-4c9e-b5d9-ee47bfb724db>Embedded]
	internal sealed class <769212b1-5471-4c9e-b5d9-ee47bfb724db>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<769212b1-5471-4c9e-b5d9-ee47bfb724db>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <3fbd689e-4b20-4884-b483-91c1a9a80245>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <3fbd689e-4b20-4884-b483-91c1a9a80245>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <3fbd689e-4b20-4884-b483-91c1a9a80245>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<769212b1-5471-4c9e-b5d9-ee47bfb724db>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <5a2974cb-8bd2-4412-94ed-d169ec648517>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <5a2974cb-8bd2-4412-94ed-d169ec648517>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Advize_PlantEverything
{
	[BepInPlugin("advize.PlantEverything", "PlantEverything", "1.13.7")]
	public class PlantEverything : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		public static class ObjectDBAwake
		{
			public static void Postfix()
			{
				Dbgl("ObjectDBAwake");
				InitPrefabRefs();
			}
		}

		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		public static class ZNetSceneAwake
		{
			public static void Postfix(ZNetScene __instance)
			{
				Dbgl("ZNetSceneAwake");
				Dbgl("Performing final mod initialization");
				FinalInit(__instance);
			}
		}

		[HarmonyPatch(typeof(Player), "RemovePiece")]
		public static class PlayerRemovePiece
		{
			public static bool Prefix(Player __instance, ref bool __result)
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: 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)
				if (((Humanoid)__instance).GetRightItem().m_shared.m_name == "$item_cultivator")
				{
					RaycastHit val = default(RaycastHit);
					if (Physics.Raycast(((Component)GameCamera.instance).transform.position, ((Component)GameCamera.instance).transform.forward, ref val, 50f, LayerMask.GetMask(new string[4] { "item", "piece_nonsolid", "Default_small", "Default" })) && Vector3.Distance(((RaycastHit)(ref val)).point, ((Character)__instance).m_eye.position) < __instance.m_maxPlaceDistance)
					{
						Piece componentInParent = ((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<Piece>();
						if (Object.op_Implicit((Object)(object)componentInParent) && componentInParent.m_name.StartsWith("$pe"))
						{
							if (!CanRemove(((Component)componentInParent).gameObject, __instance, isPiece: true))
							{
								return false;
							}
							RemoveObject(((Component)componentInParent).gameObject, __instance);
							__result = true;
						}
					}
					return false;
				}
				return true;
			}

			private static bool CanRemove(GameObject component, Player instance, bool isPiece)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				bool result = true;
				if (isPiece && !component.GetComponent<Piece>().m_canBeRemoved)
				{
					result = false;
				}
				if (!PrivateArea.CheckAccess(component.transform.position, 0f, true, false))
				{
					((Character)instance).Message((MessageType)2, "$msg_privatezone", 0, (Sprite)null);
					result = false;
				}
				if (!Object.op_Implicit((Object)(object)component.GetComponent<ZNetView>()))
				{
					result = false;
				}
				return result;
			}

			private static void RemoveObject(GameObject component, Player player)
			{
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				ZNetView component2 = component.GetComponent<ZNetView>();
				WearNTear component3 = component.GetComponent<WearNTear>();
				if (Object.op_Implicit((Object)(object)component3))
				{
					player.m_removeEffects.Create(component.transform.position, Quaternion.identity, (Transform)null, 1f, -1);
					component3.Remove();
				}
				else
				{
					component2.ClaimOwnership();
					Piece component4 = component.GetComponent<Piece>();
					component4.DropResources();
					component4.m_placeEffect.Create(((Component)component4).transform.position, ((Component)component4).transform.rotation, (Transform)null, 1f, -1);
					if (Object.op_Implicit((Object)(object)component.GetComponentInParent<Pickable>()))
					{
						component2.InvokeRPC("Pick", Array.Empty<object>());
					}
					ZNetScene.instance.Destroy(component.gameObject);
				}
				player.FaceLookDirection();
				((Character)player).m_zanim.SetTrigger(((Humanoid)player).GetRightItem().m_shared.m_attack.m_attackAnimation);
			}
		}

		[HarmonyPatch(typeof(Piece), "SetCreator")]
		public static class PieceSetCreator
		{
			public static void Postfix(Piece __instance)
			{
				if (!__instance.m_name.StartsWith("$pe") && !__instance.m_name.EndsWith("_sapling"))
				{
					return;
				}
				if (config.ResourcesSpawnEmpty && (__instance.m_name.Contains("berryBush") || (__instance.m_name.Contains("Pickable") && !__instance.m_name.Contains("Stone"))))
				{
					((Component)__instance).GetComponent<ZNetView>().InvokeRPC(ZNetView.Everybody, "SetPicked", new object[1] { true });
				}
				if (config.PlaceAnywhere)
				{
					StaticPhysics component = ((Component)__instance).GetComponent<StaticPhysics>();
					if (Object.op_Implicit((Object)(object)component))
					{
						component.m_fall = false;
						((Component)__instance).GetComponent<ZNetView>().GetZDO().Set("pe_placeAnywhere", true);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Piece), "Awake")]
		public static class PieceAwake
		{
			public static void Postfix(Piece __instance)
			{
				CheckZDO((Component)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(TreeBase), "Awake")]
		public static class TreeBaseAwake
		{
			public static void Postfix(TreeBase __instance)
			{
				CheckZDO((Component)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(Plant), "Awake")]
		public static class PlantAwake
		{
			public static void Postfix(Plant __instance)
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				if (!config.EnforceBiomesVanilla)
				{
					__instance.m_biome = (Biome)895;
				}
				if (config.EnableCropOverrides && ((Object)__instance).name.StartsWith("sapling_"))
				{
					__instance.m_minScale = config.CropMinScale;
					__instance.m_maxScale = config.CropMaxScale;
					__instance.m_growTime = config.CropGrowTimeMin;
					__instance.m_growTimeMax = config.CropGrowTimeMax;
					__instance.m_growRadius = config.CropGrowRadius;
					__instance.m_needCultivatedGround = config.CropRequireCultivation;
					((Component)__instance).GetComponentInParent<Piece>().m_cultivatedGroundOnly = config.CropRequireCultivation;
				}
			}
		}

		[HarmonyPatch(typeof(Plant), "HaveRoof")]
		public static class PlantHaveRoof
		{
			public static bool Prefix(Plant __instance, ref bool __result)
			{
				if (!config.CropRequireSunlight && __instance.m_name.StartsWith("$piece_sapling"))
				{
					__result = false;
					return false;
				}
				if (config.PlaceAnywhere && (__instance.m_name.StartsWith("$pe") || __instance.m_name.EndsWith("_sapling")))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Plant), "HaveGrowSpace")]
		public static class PlantHaveGrowSpace
		{
			public static bool Prefix(Plant __instance, ref bool __result)
			{
				if (!config.CropRequireGrowthSpace && __instance.m_name.StartsWith("$piece_sapling"))
				{
					__result = true;
					return false;
				}
				if (config.PlaceAnywhere && (__instance.m_name.StartsWith("$pe") || __instance.m_name.EndsWith("_sapling")))
				{
					__result = true;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Plant), "Grow")]
		public static class PlantGrow
		{
			private static readonly MethodInfo ModifyGrowMethod = AccessTools.Method(typeof(PlantGrow), "ModifyGrow", (Type[])null, (Type[])null);

			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Expected O, but got Unknown
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: Expected O, but got Unknown
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Expected O, but got Unknown
				//IL_0074: Unknown result type (might be due to invalid IL or missing references)
				//IL_007a: Expected O, but got Unknown
				//IL_0091: Unknown result type (might be due to invalid IL or missing references)
				//IL_0097: Expected O, but got Unknown
				return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(true, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((OpCode?)OpCodes.Stloc_3, (object)null, (string)null)
				}).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null)
				}).Advance(-1)
					.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
					{
						new CodeInstruction(OpCodes.Ldarg_0, (object)null)
					})
					.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
					{
						new CodeInstruction(OpCodes.Ldloc_3, (object)null)
					})
					.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
					{
						new CodeInstruction(OpCodes.Call, (object)ModifyGrowMethod)
					})
					.InstructionEnumeration();
			}

			private static void ModifyGrow(Plant plant, TreeBase treeBase)
			{
				if (!Object.op_Implicit((Object)(object)plant) || !Object.op_Implicit((Object)(object)treeBase))
				{
					Dbgl("ModifyGrow not executed, reference is null", forceLog: false, logError: true);
				}
				else if (!Object.op_Implicit((Object)(object)((Component)plant).GetComponent<ZNetView>()))
				{
					Dbgl("ModifyGrow not executed, ZNetView component reference is null", forceLog: false, logError: true);
				}
				else if (((Component)plant).GetComponent<ZNetView>().GetZDO().GetBool("pe_placeAnywhere", false) && Object.op_Implicit((Object)(object)((Component)treeBase).GetComponent<StaticPhysics>()))
				{
					((Component)treeBase).GetComponent<StaticPhysics>().m_fall = false;
					((Component)treeBase).GetComponent<ZNetView>().GetZDO().Set("pe_placeAnywhere", true);
				}
			}
		}

		[HarmonyPatch(typeof(Pickable), "GetHoverText")]
		public static class PickableGetHoverText
		{
			[HarmonyPostfix]
			public static void Postfix(Pickable __instance, ref string __result)
			{
				if (__instance.m_picked && config.EnablePickableTimers && __instance.m_nview.GetZDO() != null && !((Object)__instance).name.ToLower().Contains("core"))
				{
					float growthTime = __instance.m_respawnTimeMinutes * 60;
					DateTime placedTime = new DateTime(__instance.m_nview.GetZDO().GetLong(ZDOVars.s_pickedTime, 0L));
					string text = FormatTimeString(growthTime, placedTime);
					__result = Localization.instance.Localize(__instance.GetHoverName()) + "\n" + text;
				}
			}
		}

		[HarmonyPatch(typeof(Plant), "GetHoverText")]
		public static class PlantGetHoverText
		{
			[HarmonyPostfix]
			public static void Postfix(Plant __instance, ref string __result)
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				if (config.EnablePlantTimers && (int)__instance.m_status == 0 && __instance.m_nview.GetZDO() != null)
				{
					float growTime = __instance.GetGrowTime();
					DateTime placedTime = new DateTime(__instance.m_nview.GetZDO().GetLong(ZDOVars.s_plantTime, ZNet.instance.GetTime().Ticks));
					string text = FormatTimeString(growTime, placedTime);
					__result = __result + "\n" + text;
				}
			}
		}

		internal class LocalizedStrings
		{
			public List<string> localizedStrings = new List<string>();
		}

		internal class PrefabDB
		{
			internal string key;

			internal int biome;

			internal int resourceCost;

			internal int resourceReturn;

			internal bool extraDrops;

			internal bool icon;

			internal GameObject Prefab => prefabRefs[key];
		}

		private class PieceDB : PrefabDB
		{
			private Dictionary<string, int> resources;

			internal int respawnTime;

			internal bool recover;

			internal bool enabled;

			internal Piece piece;

			internal List<Vector3> points;

			internal KeyValuePair<string, int> Resource
			{
				get
				{
					if (Resources.Count <= 0)
					{
						return new KeyValuePair<string, int>(((Object)base.Prefab.GetComponent<Pickable>().m_itemPrefab).name, resourceCost);
					}
					return Resources.First();
				}
				set
				{
					if (resources == null)
					{
						resources = new Dictionary<string, int>();
					}
					if (!resources.ContainsKey(value.Key))
					{
						resources.Add(value.Key, value.Value);
					}
					enabled = true;
				}
			}

			internal Dictionary<string, int> Resources
			{
				get
				{
					return resources ?? new Dictionary<string, int>();
				}
				set
				{
					resources = value;
					enabled = true;
				}
			}

			internal int ResourceCost
			{
				get
				{
					return resourceCost;
				}
				set
				{
					resourceCost = value;
					enabled = value != 0;
				}
			}
		}

		private class SaplingDB : PrefabDB
		{
			internal string source;

			internal string resource;

			internal float growTime;

			internal float growRadius;

			internal float minScale;

			internal float maxScale;

			internal GameObject[] grownPrefabs;
		}

		public const string PluginID = "advize.PlantEverything";

		public const string PluginName = "PlantEverything";

		public const string Version = "1.13.7";

		private readonly Harmony harmony = new Harmony("advize.PlantEverything");

		public static ManualLogSource PELogger = new ManualLogSource(" PlantEverything");

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

		private static List<PieceDB> pieceRefs = new List<PieceDB>();

		private static List<SaplingDB> saplingRefs = new List<SaplingDB>();

		private static bool isInitialized = false;

		private static readonly string modDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

		private static AssetBundle assetBundle;

		private static readonly Dictionary<string, Texture2D> cachedTextures = new Dictionary<string, Texture2D>();

		private static ModConfig config;

		private static readonly Dictionary<string, string> stringDictionary = new Dictionary<string, string>
		{
			{ "AncientSapling", "Ancient Sapling" },
			{ "YggaSapling", "Ygga Sapling" },
			{ "RaspberryBushName", "Raspberry Bush" },
			{ "RaspberryBushDescription", "Plant raspberries to grow raspberry bushes." },
			{ "BlueberryBushName", "Blueberry Bush" },
			{ "BlueberryBushDescription", "Plant blueberries to grow blueberry bushes." },
			{ "CloudberryBushName", "Cloudberry Bush" },
			{ "CloudberryBushDescription", "Plant cloudberries to grow cloudberry bushes." },
			{ "PickableMushroomName", "Pickable Mushrooms" },
			{ "PickableMushroomDescription", "Plant mushrooms to grow more pickable mushrooms." },
			{ "PickableYellowMushroomName", "Pickable Yellow Mushrooms" },
			{ "PickableYellowMushroomDescription", "Plant yellow mushrooms to grow more pickable yellow mushrooms." },
			{ "PickableBlueMushroomName", "Pickable Blue Mushrooms" },
			{ "PickableBlueMushroomDescription", "Plant blue mushrooms to grow more pickable blue mushrooms." },
			{ "PickableThistleName", "Pickable Thistle" },
			{ "PickableThistleDescription", "Plant thistle to grow more pickable thistle." },
			{ "PickableDandelionName", "Pickable Dandelion" },
			{ "PickableDandelionDescription", "Plant dandelion to grow more pickable dandelion." },
			{ "BeechSmallName", "Small Beech Tree" },
			{ "BeechSmallDescription", "Plant a small beech tree." },
			{ "FirSmallName", "Small Fir Tree" },
			{ "FirSmallDescription", "Plant a small fir tree." },
			{ "FirSmallDeadName", "Small Dead Fir Tree" },
			{ "FirSmallDeadDescription", "Plant a small dead fir tree." },
			{ "Bush01Name", "Small Bush 1" },
			{ "Bush01Description", "Plant a small bush." },
			{ "Bush02Name", "Small Bush 2" },
			{ "Bush02Description", "Plant a small bush." },
			{ "PlainsBushName", "Small Plains Bush" },
			{ "PlainsBushDescription", "Plant a bush native to the plains." },
			{ "Shrub01Name", "Small Shrub 1" },
			{ "Shrub01Description", "Plant a small shrub." },
			{ "Shrub02Name", "Small Shrub 2" },
			{ "Shrub02Description", "Plant a small shrub." },
			{ "YggaShootName", "Small Ygga Shoot" },
			{ "YggaShootDescription", "Plant a small ygga shoot." },
			{ "VinesName", "Vines" },
			{ "VinesDescription", "Plant vines." },
			{ "GlowingMushroomName", "Glowing Mushroom" },
			{ "GlowingMushroomDescription", "Plant a large glowing mushroom." },
			{ "PickableBranchName", "Pickable Branch" },
			{ "PickableBranchDescription", "Plant respawning pickable branches." },
			{ "PickableStoneName", "Pickable Stone" },
			{ "PickableStoneDescription", "Plant pickable stone." },
			{ "PickableFlintName", "Pickable Flint" },
			{ "PickableFlintDescription", "Plant respawning pickable flint." }
		};

		public static void CheckZDO(Component instance)
		{
			ZNetView component = instance.GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component) && component.GetZDO() != null && component.GetZDO().GetBool("pe_placeAnywhere", false))
			{
				instance.GetComponent<StaticPhysics>().m_fall = false;
			}
		}

		public static string FormatTimeString(float growthTime, DateTime placedTime)
		{
			TimeSpan timeSpan = ZNet.instance.GetTime() - placedTime;
			TimeSpan timeSpan2 = TimeSpan.FromSeconds((double)growthTime - timeSpan.TotalSeconds);
			double num = (double)(growthTime / 60f) - timeSpan.TotalMinutes;
			double num2 = num / (double)(growthTime / 60f);
			int num3 = Math.Min((int)(timeSpan.TotalSeconds * 100.0 / (double)growthTime), 100);
			string text = "red";
			if (num2 < 0.0)
			{
				text = "#00FFFF";
			}
			else if (num2 < 0.25)
			{
				text = "#32CD32";
			}
			else if (num2 < 0.5)
			{
				text = "yellow";
			}
			else if (num2 < 0.75)
			{
				text = "orange";
			}
			string text2 = ((timeSpan2.Hours > 0) ? $"{timeSpan2.Hours:D2}h {timeSpan2.Minutes:D2}m {timeSpan2.Seconds:D2}s" : ((timeSpan2.Minutes <= 0) ? $"{timeSpan2.Seconds:D2}s" : $"{timeSpan2.Minutes:D2}m {timeSpan2.Seconds:D2}s"));
			if (!config.GrowthAsPercentage)
			{
				if (!(num < 0.0))
				{
					return "(Ready in <color=" + text + ">" + text2 + "</color>)";
				}
				return "(<color=" + text + ">Ready any second now</color>)";
			}
			return $"(<color={text}>{num3}%</color>)";
		}

		public void Awake()
		{
			Logger.Sources.Add((ILogSource)(object)PELogger);
			assetBundle = LoadAssetBundle("planteverything");
			config = new ModConfig(((BaseUnityPlugin)this).Config, new ConfigSync("advize.PlantEverything")
			{
				DisplayName = "PlantEverything",
				CurrentVersion = "1.13.7",
				MinimumRequiredVersion = "1.13.7"
			});
			if (config.EnableLocalization)
			{
				LoadLocalizedStrings();
			}
			harmony.PatchAll();
		}

		private void LoadLocalizedStrings()
		{
			string path = config.Language + "_PlantEverything.json";
			string text = Path.Combine(modDirectory, path);
			try
			{
				foreach (string localizedString in JsonUtility.FromJson<LocalizedStrings>(File.ReadAllText(text)).localizedStrings)
				{
					string[] array = localizedString.Split(new char[1] { ':' });
					stringDictionary.Remove(array[0]);
					stringDictionary.Add(array[0], array[1]);
				}
				Dbgl("Loaded localized strings from " + text);
				return;
			}
			catch
			{
				Dbgl("EnableLocalization is true but unable to load localized text file, generating new one from default English values", forceLog: true);
			}
			SerializeDict();
		}

		private void SerializeDict()
		{
			string text = Path.Combine(modDirectory, "english_PlantEverything.json");
			LocalizedStrings localizedStrings = new LocalizedStrings();
			foreach (KeyValuePair<string, string> item in stringDictionary)
			{
				localizedStrings.localizedStrings.Add(item.Key + ":" + item.Value);
			}
			File.WriteAllText(text, JsonUtility.ToJson((object)localizedStrings, true));
			Dbgl("Saved english localized strings to " + text);
		}

		internal static void Dbgl(string message, bool forceLog = false, bool logError = false)
		{
			if (forceLog || config.EnableDebugMessages)
			{
				if (!logError)
				{
					PELogger.LogInfo((object)message);
				}
				else
				{
					PELogger.LogError((object)message);
				}
			}
		}

		private static AssetBundle LoadAssetBundle(string fileName)
		{
			return AssetBundle.LoadFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("Advize_PlantEverything.Assets." + fileName));
		}

		private static GameObject CreatePrefab(string name)
		{
			GameObject obj = assetBundle.LoadAsset<GameObject>(name);
			obj.SetActive(true);
			return obj;
		}

		private static Sprite CreateSprite(string fileName, Rect spriteSection)
		{
			//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)
			try
			{
				return Sprite.Create(LoadTexture(fileName), spriteSection, Vector2.zero);
			}
			catch
			{
				Dbgl("Unable to load texture", forceLog: true, logError: true);
			}
			return null;
		}

		private static Texture2D LoadTexture(string fileName)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0058: Expected O, but got Unknown
			if (cachedTextures.ContainsKey(fileName))
			{
				return cachedTextures[fileName];
			}
			Stream? manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Advize_PlantEverything.Assets." + fileName);
			byte[] array = new byte[manifestResourceStream.Length];
			manifestResourceStream.Read(array, 0, array.Length);
			Texture2D val = new Texture2D(0, 0);
			ImageConversion.LoadImage(val, array);
			return val;
		}

		private static Piece CreatePiece(string key, Piece component, bool? isGrounded = null, bool canBeRemoved = true)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			component.m_name = "$pe" + key + "Name";
			component.m_description = "$pe" + key + "Description";
			component.m_category = (PieceCategory)0;
			component.m_cultivatedGroundOnly = (key.Contains("berryBush") || key.Contains("Pickable")) && config.RequireCultivation;
			bool num = isGrounded ?? (!config.PlaceAnywhere);
			bool groundOnly = num;
			component.m_groundPiece = num;
			component.m_groundOnly = groundOnly;
			component.m_canBeRemoved = canBeRemoved;
			component.m_targetNonPlayerBuilt = false;
			return component;
		}

		private static void InitPrefabRefs()
		{
			//IL_03e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ea: Expected O, but got Unknown
			Dbgl("InitPrefabRefs");
			if (prefabRefs.Count > 0)
			{
				return;
			}
			prefabRefs.Add("Bush02_en", null);
			prefabRefs.Add("Bush01_heath", null);
			prefabRefs.Add("Bush01", null);
			prefabRefs.Add("GlowingMushroom", null);
			prefabRefs.Add("Pinetree_01", null);
			prefabRefs.Add("FirTree", null);
			prefabRefs.Add("YggaShoot_small1", null);
			prefabRefs.Add("Beech_small1", null);
			prefabRefs.Add("FirTree_small_dead", null);
			prefabRefs.Add("FirTree_small", null);
			prefabRefs.Add("Pickable_Dandelion", null);
			prefabRefs.Add("Sap", null);
			prefabRefs.Add("CloudberryBush", null);
			prefabRefs.Add("vines", null);
			prefabRefs.Add("Cultivator", null);
			prefabRefs.Add("SwampTree1", null);
			prefabRefs.Add("YggaShoot1", null);
			prefabRefs.Add("Beech1", null);
			prefabRefs.Add("Birch2", null);
			prefabRefs.Add("Oak1", null);
			prefabRefs.Add("Birch2_aut", null);
			prefabRefs.Add("Birch1_aut", null);
			prefabRefs.Add("Birch1", null);
			prefabRefs.Add("Pickable_Thistle", null);
			prefabRefs.Add("Pickable_Flint", null);
			prefabRefs.Add("Pickable_Stone", null);
			prefabRefs.Add("FirCone", null);
			prefabRefs.Add("PineCone", null);
			prefabRefs.Add("shrub_2", null);
			prefabRefs.Add("shrub_2_heath", null);
			prefabRefs.Add("BirchSeeds", null);
			prefabRefs.Add("AncientSeed", null);
			prefabRefs.Add("Acorn", null);
			prefabRefs.Add("BeechSeeds", null);
			prefabRefs.Add("Pickable_Branch", null);
			prefabRefs.Add("Pickable_Mushroom", null);
			prefabRefs.Add("BlueberryBush", null);
			prefabRefs.Add("RaspberryBush", null);
			prefabRefs.Add("Pickable_Mushroom_blue", null);
			prefabRefs.Add("Pickable_Mushroom_yellow", null);
			prefabRefs.Add("sapling_seedonion", null);
			prefabRefs.Add("Beech_Sapling", null);
			prefabRefs.Add("PineTree_Sapling", null);
			prefabRefs.Add("FirTree_Sapling", null);
			prefabRefs.Add("sapling_onion", null);
			prefabRefs.Add("sapling_turnip", null);
			prefabRefs.Add("Oak_Sapling", null);
			prefabRefs.Add("sapling_barley", null);
			prefabRefs.Add("sapling_jotunpuffs", null);
			prefabRefs.Add("Birch_Sapling", null);
			prefabRefs.Add("sapling_carrot", null);
			prefabRefs.Add("sapling_seedcarrot", null);
			prefabRefs.Add("sapling_flax", null);
			prefabRefs.Add("sapling_magecap", null);
			prefabRefs.Add("sapling_seedturnip", null);
			prefabRefs.Add("vfx_Place_wood_pole", null);
			prefabRefs.Add("sfx_build_cultivator", null);
			prefabRefs.Add("YggaShoot3", null);
			prefabRefs.Add("YggaShoot2", null);
			Object[] array = Resources.FindObjectsOfTypeAll(typeof(GameObject));
			for (int i = 0; i < array.Length; i++)
			{
				GameObject val = (GameObject)array[i];
				if (prefabRefs.ContainsKey(((Object)val).name) && (!((Object)val).name.Equals("FirTree_small") || val.GetComponents(typeof(Component)).Length >= 2))
				{
					prefabRefs[((Object)val).name] = val;
					if (!prefabRefs.Any((KeyValuePair<string, GameObject> key) => !Object.op_Implicit((Object)(object)key.Value)))
					{
						Dbgl("Found all prefab references");
						break;
					}
				}
			}
			prefabRefs.Add("Ancient_Sapling", CreatePrefab("Ancient_Sapling"));
			prefabRefs.Add("Ygga_Sapling", CreatePrefab("Ygga_Sapling"));
			prefabRefs.Add("Pickable_Dandelion_Picked", CreatePrefab("Pickable_Dandelion_Picked"));
			prefabRefs.Add("Pickable_Thistle_Picked", CreatePrefab("Pickable_Thistle_Picked"));
			prefabRefs.Add("Pickable_Mushroom_Picked", CreatePrefab("Pickable_Mushroom_Picked"));
			prefabRefs.Add("Pickable_Mushroom_yellow_Picked", CreatePrefab("Pickable_Mushroom_yellow_Picked"));
			prefabRefs.Add("Pickable_Mushroom_blue_Picked", CreatePrefab("Pickable_Mushroom_blue_Picked"));
		}

		private static void InitPieceRefs()
		{
			Dbgl("InitPieceRefs");
			if (pieceRefs.Count > 0)
			{
				foreach (PieceDB pieceRef in pieceRefs)
				{
					if (prefabRefs["Cultivator"].GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces.m_pieces.Contains(pieceRef.Prefab))
					{
						prefabRefs["Cultivator"].GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces.m_pieces.Remove(pieceRef.Prefab);
					}
					Player localPlayer = Player.m_localPlayer;
					if (((localPlayer == null) ? null : ((Humanoid)localPlayer).GetRightItem()?.m_shared.m_name) == "$item_cultivator")
					{
						PELogger.LogWarning((object)"Cultivator updated through config change, unequipping cultivator");
						((Humanoid)Player.m_localPlayer).HideHandItems();
					}
					Object.DestroyImmediate((Object)(object)pieceRef.Prefab.GetComponent<Piece>());
				}
				pieceRefs.Clear();
			}
			pieceRefs = GeneratePieceRefs();
		}

		private static Piece GetOrAddPieceComponent(GameObject go)
		{
			return go.GetComponent<Piece>() ?? go.AddComponent<Piece>();
		}

		private static List<PieceDB> GeneratePieceRefs()
		{
			//IL_084c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0866: Unknown result type (might be due to invalid IL or missing references)
			//IL_0880: Unknown result type (might be due to invalid IL or missing references)
			//IL_089a: Unknown result type (might be due to invalid IL or missing references)
			bool enforceBiomes = config.EnforceBiomes;
			List<PieceDB> list = new List<PieceDB>
			{
				new PieceDB
				{
					key = "RaspberryBush",
					ResourceCost = config.RaspberryCost,
					resourceReturn = config.RaspberryReturn,
					respawnTime = config.RaspberryRespawnTime,
					biome = (enforceBiomes ? 1 : 0),
					icon = true,
					recover = config.RecoverResources,
					piece = CreatePiece("RaspberryBush", GetOrAddPieceComponent(prefabRefs["RaspberryBush"]))
				},
				new PieceDB
				{
					key = "BlueberryBush",
					ResourceCost = config.BlueberryCost,
					resourceReturn = config.BlueberryReturn,
					respawnTime = config.BlueberryRespawnTime,
					biome = (enforceBiomes ? 8 : 0),
					icon = true,
					recover = config.RecoverResources,
					piece = CreatePiece("BlueberryBush", GetOrAddPieceComponent(prefabRefs["BlueberryBush"]))
				},
				new PieceDB
				{
					key = "CloudberryBush",
					ResourceCost = config.CloudberryCost,
					resourceReturn = config.CloudberryReturn,
					respawnTime = config.CloudberryRespawnTime,
					biome = (enforceBiomes ? 16 : 0),
					icon = true,
					recover = config.RecoverResources,
					piece = CreatePiece("CloudberryBush", GetOrAddPieceComponent(prefabRefs["CloudberryBush"]))
				},
				new PieceDB
				{
					key = "Pickable_Mushroom",
					ResourceCost = config.MushroomCost,
					resourceReturn = config.MushroomReturn,
					respawnTime = config.MushroomRespawnTime,
					recover = config.RecoverResources,
					piece = CreatePiece("PickableMushroom", GetOrAddPieceComponent(prefabRefs["Pickable_Mushroom"]), true)
				},
				new PieceDB
				{
					key = "Pickable_Mushroom_yellow",
					ResourceCost = config.YellowMushroomCost,
					resourceReturn = config.YellowMushroomReturn,
					respawnTime = config.YellowMushroomRespawnTime,
					recover = config.RecoverResources,
					piece = CreatePiece("PickableYellowMushroom", GetOrAddPieceComponent(prefabRefs["Pickable_Mushroom_yellow"]), true)
				},
				new PieceDB
				{
					key = "Pickable_Mushroom_blue",
					ResourceCost = config.BlueMushroomCost,
					resourceReturn = config.BlueMushroomReturn,
					respawnTime = config.BlueMushroomRespawnTime,
					recover = config.RecoverResources,
					piece = CreatePiece("PickableBlueMushroom", GetOrAddPieceComponent(prefabRefs["Pickable_Mushroom_blue"]), true)
				},
				new PieceDB
				{
					key = "Pickable_Thistle",
					ResourceCost = config.ThistleCost,
					resourceReturn = config.ThistleReturn,
					respawnTime = config.ThistleRespawnTime,
					biome = (enforceBiomes ? 8 : 0),
					recover = config.RecoverResources,
					piece = CreatePiece("PickableThistle", GetOrAddPieceComponent(prefabRefs["Pickable_Thistle"]), true)
				},
				new PieceDB
				{
					key = "Pickable_Dandelion",
					ResourceCost = config.DandelionCost,
					resourceReturn = config.DandelionReturn,
					respawnTime = config.DandelionRespawnTime,
					biome = (enforceBiomes ? 1 : 0),
					recover = config.RecoverResources,
					piece = CreatePiece("PickableDandelion", GetOrAddPieceComponent(prefabRefs["Pickable_Dandelion"]), true)
				}
			};
			if (!config.EnableMiscFlora)
			{
				return list;
			}
			list.AddRange(new List<PieceDB>
			{
				new PieceDB
				{
					key = "Beech_small1",
					Resource = new KeyValuePair<string, int>("BeechSeeds", 1),
					icon = true,
					piece = CreatePiece("BeechSmall", GetOrAddPieceComponent(prefabRefs["Beech_small1"]), null, canBeRemoved: false)
				},
				new PieceDB
				{
					key = "FirTree_small",
					Resource = new KeyValuePair<string, int>("FirCone", 1),
					icon = true,
					piece = CreatePiece("FirSmall", GetOrAddPieceComponent(prefabRefs["FirTree_small"]), null, canBeRemoved: false)
				},
				new PieceDB
				{
					key = "FirTree_small_dead",
					Resource = new KeyValuePair<string, int>("FirCone", 1),
					icon = true,
					piece = CreatePiece("FirSmallDead", GetOrAddPieceComponent(prefabRefs["FirTree_small_dead"]), null, canBeRemoved: false)
				},
				new PieceDB
				{
					key = "Bush01",
					Resource = new KeyValuePair<string, int>("Wood", 2),
					icon = true,
					piece = CreatePiece("Bush01", GetOrAddPieceComponent(prefabRefs["Bush01"]), null, canBeRemoved: false)
				},
				new PieceDB
				{
					key = "Bush01_heath",
					Resource = new KeyValuePair<string, int>("Wood", 2),
					icon = true,
					piece = CreatePiece("Bush02", GetOrAddPieceComponent(prefabRefs["Bush01_heath"]), null, canBeRemoved: false)
				},
				new PieceDB
				{
					key = "Bush02_en",
					Resource = new KeyValuePair<string, int>("Wood", 3),
					icon = true,
					piece = CreatePiece("PlainsBush", GetOrAddPieceComponent(prefabRefs["Bush02_en"]), null, canBeRemoved: false)
				},
				new PieceDB
				{
					key = "shrub_2",
					Resource = new KeyValuePair<string, int>("Wood", 2),
					icon = true,
					piece = CreatePiece("Shrub01", GetOrAddPieceComponent(prefabRefs["shrub_2"]), null, canBeRemoved: false)
				},
				new PieceDB
				{
					key = "shrub_2_heath",
					Resource = new KeyValuePair<string, int>("Wood", 2),
					icon = true,
					piece = CreatePiece("Shrub02", GetOrAddPieceComponent(prefabRefs["shrub_2_heath"]), null, canBeRemoved: false)
				},
				new PieceDB
				{
					key = "YggaShoot_small1",
					Resources = new Dictionary<string, int>
					{
						{ "YggdrasilWood", 1 },
						{ "Wood", 2 }
					},
					icon = true,
					piece = CreatePiece("YggaShoot", GetOrAddPieceComponent(prefabRefs["YggaShoot_small1"]), null, canBeRemoved: false)
				},
				new PieceDB
				{
					key = "vines",
					Resource = new KeyValuePair<string, int>("Wood", 2),
					icon = true,
					recover = true,
					piece = CreatePiece("Vines", GetOrAddPieceComponent(prefabRefs["vines"]), false),
					points = new List<Vector3>
					{
						new Vector3(1f, 0.5f, 0f),
						new Vector3(-1f, 0.5f, 0f),
						new Vector3(1f, -1f, 0f),
						new Vector3(-1f, -1f, 0f)
					}
				},
				new PieceDB
				{
					key = "GlowingMushroom",
					Resources = new Dictionary<string, int>
					{
						{ "MushroomYellow", 3 },
						{ "BoneFragments", 1 },
						{ "Ooze", 1 }
					},
					icon = true,
					recover = true,
					piece = CreatePiece("GlowingMushroom", GetOrAddPieceComponent(prefabRefs["GlowingMushroom"]), true)
				},
				new PieceDB
				{
					key = "Pickable_Branch",
					ResourceCost = config.PickableBranchCost,
					resourceReturn = config.PickableBranchReturn,
					respawnTime = 240,
					recover = config.RecoverResources,
					piece = CreatePiece("PickableBranch", GetOrAddPieceComponent(prefabRefs["Pickable_Branch"]), true)
				},
				new PieceDB
				{
					key = "Pickable_Stone",
					ResourceCost = config.PickableStoneCost,
					resourceReturn = config.PickableStoneReturn,
					respawnTime = 0,
					recover = config.RecoverResources,
					piece = CreatePiece("PickableStone", GetOrAddPieceComponent(prefabRefs["Pickable_Stone"]), true)
				},
				new PieceDB
				{
					key = "Pickable_Flint",
					ResourceCost = config.PickableFlintCost,
					resourceReturn = config.PickableFlintReturn,
					respawnTime = 240,
					recover = config.RecoverResources,
					piece = CreatePiece("PickableFlint", GetOrAddPieceComponent(prefabRefs["Pickable_Flint"]), true)
				}
			});
			return list;
		}

		private static void InitPieces()
		{
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: 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_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_0463: Unknown result type (might be due to invalid IL or missing references)
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_039f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
			Dbgl("InitPieces");
			foreach (PieceDB pieceRef in pieceRefs)
			{
				ItemDrop component = ObjectDB.instance.GetItemPrefab(pieceRef.Resource.Key).GetComponent<ItemDrop>();
				if (pieceRef.Resources.Count > 0)
				{
					List<Requirement> list = new List<Requirement>();
					foreach (string key in pieceRef.Resources.Keys)
					{
						list.Add(new Requirement
						{
							m_resItem = ObjectDB.instance.GetItemPrefab(key).GetComponent<ItemDrop>(),
							m_amount = pieceRef.Resources[key],
							m_recover = pieceRef.recover
						});
					}
					pieceRef.piece.m_resources = list.ToArray();
				}
				else
				{
					pieceRef.piece.m_resources = (Requirement[])(object)new Requirement[1]
					{
						new Requirement
						{
							m_resItem = component,
							m_amount = pieceRef.ResourceCost,
							m_recover = pieceRef.recover
						}
					};
				}
				pieceRef.piece.m_placeEffect.m_effectPrefabs = (EffectData[])(object)new EffectData[2]
				{
					new EffectData
					{
						m_prefab = prefabRefs["vfx_Place_wood_pole"],
						m_enabled = true
					},
					new EffectData
					{
						m_prefab = prefabRefs["sfx_build_cultivator"],
						m_enabled = true
					}
				};
				Pickable component2 = pieceRef.Prefab.GetComponent<Pickable>();
				if (Object.op_Implicit((Object)(object)component2))
				{
					component2.m_respawnTimeMinutes = pieceRef.respawnTime;
					component2.m_amount = pieceRef.resourceReturn;
					pieceRef.piece.m_onlyInBiome = (Biome)pieceRef.biome;
					if (Object.op_Implicit((Object)(object)pieceRef.Prefab.transform.Find("visual")))
					{
						if (config.ShowPickableSpawners)
						{
							Transform val = prefabRefs[pieceRef.key + "_Picked"].transform.Find("PE_Picked");
							if (Object.op_Implicit((Object)(object)val))
							{
								val.SetParent(pieceRef.Prefab.transform);
								((Renderer)((Component)val).gameObject.GetComponent<MeshRenderer>()).sharedMaterials = (pieceRef.key.Equals("Pickable_Thistle") ? ((Renderer)((Component)pieceRef.Prefab.transform.Find("visual").Find("default")).GetComponent<MeshRenderer>()).sharedMaterials : ((Renderer)((Component)pieceRef.Prefab.transform.Find("visual")).GetComponent<MeshRenderer>()).sharedMaterials);
								if (pieceRef.key.Contains("Dandelion"))
								{
									Material val2 = ((Renderer)((Component)pieceRef.Prefab.transform.Find("visual")).GetComponent<MeshRenderer>()).sharedMaterials[0];
									((Renderer)((Component)val).gameObject.GetComponent<MeshRenderer>()).sharedMaterials = (Material[])(object)new Material[2] { val2, val2 };
								}
							}
						}
						else
						{
							Transform val3 = prefabRefs[pieceRef.key].transform.Find("PE_Picked");
							if (Object.op_Implicit((Object)(object)val3))
							{
								val3.SetParent(prefabRefs[pieceRef.key + "_Picked"].transform);
							}
						}
					}
				}
				if (pieceRef.points != null)
				{
					Transform val4 = pieceRef.Prefab.transform.Find("_snappoint");
					if (config.SnappableVines)
					{
						if (!Object.op_Implicit((Object)(object)val4))
						{
							foreach (Vector3 point in pieceRef.points)
							{
								GameObject val5 = new GameObject("_snappoint")
								{
									tag = "snappoint"
								};
								val5.transform.position = point;
								val5.transform.SetParent(pieceRef.Prefab.transform);
								val5.SetActive(false);
							}
						}
					}
					else
					{
						while (Object.op_Implicit((Object)(object)val4))
						{
							Object.DestroyImmediate((Object)(object)((Component)val4).gameObject);
							val4 = pieceRef.Prefab.transform.Find("_snappoint");
						}
					}
				}
				pieceRef.piece.m_icon = (pieceRef.icon ? CreateSprite(pieceRef.key + "PieceIcon.png", new Rect(0f, 0f, 64f, 64f)) : component.m_itemData.GetIcon());
			}
		}

		private static void InitSaplingRefs()
		{
			Dbgl("InitSaplingRefs");
			if (saplingRefs.Count > 0)
			{
				saplingRefs.Clear();
			}
			saplingRefs = GenerateSaplingRefs();
		}

		private static List<SaplingDB> GenerateSaplingRefs()
		{
			List<SaplingDB> list = new List<SaplingDB>();
			list.Add(new SaplingDB
			{
				key = "Ancient_Sapling",
				source = "SwampTree1",
				resource = "AncientSeed",
				resourceCost = 1,
				biome = (config.EnforceBiomes ? 2 : 895),
				icon = true,
				growTime = config.AncientGrowthTime,
				growRadius = config.AncientGrowRadius,
				minScale = config.AncientMinScale,
				maxScale = config.AncientMaxScale,
				grownPrefabs = (GameObject[])(object)new GameObject[1] { prefabRefs["SwampTree1"] }
			});
			list.Add(new SaplingDB
			{
				key = "Ygga_Sapling",
				source = "YggaShoot_small1",
				resource = "Sap",
				resourceCost = 1,
				biome = (config.EnforceBiomes ? 512 : 895),
				icon = true,
				growTime = config.YggaGrowthTime,
				growRadius = config.YggaGrowRadius,
				minScale = config.YggaMinScale,
				maxScale = config.YggaMaxScale,
				grownPrefabs = (GameObject[])(object)new GameObject[3]
				{
					prefabRefs["YggaShoot1"],
					prefabRefs["YggaShoot2"],
					prefabRefs["YggaShoot3"]
				}
			});
			return list;
		}

		private static void InitSaplings()
		{
			//IL_0320: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_0329: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a4: Unknown result type (might be due to invalid IL or missing references)
			Dbgl("InitSaplings");
			ModifyTreeDrops();
			foreach (SaplingDB item in new List<SaplingDB>
			{
				new SaplingDB
				{
					key = "Beech_Sapling",
					growTime = config.BeechGrowthTime,
					growRadius = config.BeechGrowRadius,
					minScale = config.BeechMinScale,
					maxScale = config.BeechMaxScale
				},
				new SaplingDB
				{
					key = "PineTree_Sapling",
					growTime = config.PineGrowthTime,
					growRadius = config.PineGrowRadius,
					minScale = config.PineMinScale,
					maxScale = config.PineMaxScale
				},
				new SaplingDB
				{
					key = "FirTree_Sapling",
					growTime = config.FirGrowthTime,
					growRadius = config.FirGrowRadius,
					minScale = config.FirMinScale,
					maxScale = config.FirMaxScale
				},
				new SaplingDB
				{
					key = "Birch_Sapling",
					growTime = config.BirchGrowthTime,
					growRadius = config.BirchGrowRadius,
					minScale = config.BirchMinScale,
					maxScale = config.BirchMaxScale
				},
				new SaplingDB
				{
					key = "Oak_Sapling",
					growTime = config.OakGrowthTime,
					growRadius = config.OakGrowRadius,
					minScale = config.OakMinScale,
					maxScale = config.OakMaxScale
				}
			})
			{
				Plant component = item.Prefab.GetComponent<Plant>();
				component.m_growTime = (component.m_growTimeMax = item.growTime);
				component.m_growRadius = item.growRadius;
				component.m_minScale = item.minScale;
				component.m_maxScale = item.maxScale;
				component.m_destroyIfCantGrow = (item.Prefab.GetComponent<Piece>().m_groundOnly = !config.PlaceAnywhere);
			}
			foreach (SaplingDB saplingRef in saplingRefs)
			{
				Plant component2 = saplingRef.Prefab.GetComponent<Plant>();
				Piece component3 = saplingRef.Prefab.GetComponent<Piece>();
				component2.m_growTime = (component2.m_growTimeMax = saplingRef.growTime);
				component2.m_grownPrefabs = saplingRef.grownPrefabs;
				component2.m_minScale = saplingRef.minScale;
				component2.m_maxScale = saplingRef.maxScale;
				component2.m_growRadius = saplingRef.growRadius;
				component3.m_resources[0].m_resItem = prefabRefs[saplingRef.resource].GetComponent<ItemDrop>();
				component3.m_resources[0].m_amount = saplingRef.resourceCost;
				int biome = saplingRef.biome;
				Biome onlyInBiome = (Biome)biome;
				component2.m_biome = (Biome)biome;
				component3.m_onlyInBiome = onlyInBiome;
				component2.m_destroyIfCantGrow = (component3.m_groundOnly = !config.PlaceAnywhere);
				if (isInitialized)
				{
					continue;
				}
				string[] array = new string[2] { "healthy", "unhealthy" };
				Transform val = prefabRefs["Birch_Sapling"].transform.Find(array[0]);
				string[] array2 = array;
				foreach (string text in array2)
				{
					((Component)saplingRef.Prefab.transform.Find(text)).gameObject.GetComponent<MeshFilter>().mesh = ((Component)val.Find("Birch_Sapling")).gameObject.GetComponent<MeshFilter>().mesh;
				}
				if (saplingRef.source.StartsWith("Swamp"))
				{
					Material[] array3 = (Material[])(object)new Material[1] { ((Renderer)((Component)prefabRefs[saplingRef.source].transform.Find("swamptree1")).gameObject.GetComponent<MeshRenderer>()).sharedMaterials[0] };
					array3[0].shader = Shader.Find("Custom/Piece");
					array2 = array;
					foreach (string text2 in array2)
					{
						((Renderer)((Component)saplingRef.Prefab.transform.Find(text2)).gameObject.GetComponent<MeshRenderer>()).sharedMaterials = array3;
					}
				}
				else if (saplingRef.source.StartsWith("Ygga"))
				{
					string[] array4 = new string[6] { "birchleafs002", "birchleafs003", "birchleafs008", "birchleafs009", "birchleafs010", "birchleafs011" };
					Material[] sharedMaterials = (Material[])(object)new Material[1] { ((Renderer)((Component)prefabRefs[saplingRef.source].transform.Find("beech")).gameObject.GetComponent<MeshRenderer>()).sharedMaterials[0] };
					Material[] sharedMaterials2 = (Material[])(object)new Material[1] { ((Renderer)((Component)prefabRefs[saplingRef.source].transform.Find("beech")).gameObject.GetComponent<MeshRenderer>()).sharedMaterials[1] };
					array2 = array;
					foreach (string text3 in array2)
					{
						((Renderer)((Component)saplingRef.Prefab.transform.Find(text3)).gameObject.GetComponent<MeshRenderer>()).sharedMaterials = sharedMaterials2;
					}
					array2 = array4;
					foreach (string text4 in array2)
					{
						string[] array5 = array;
						foreach (string text5 in array5)
						{
							((Component)((Component)saplingRef.Prefab.transform.Find(text5)).transform.Find(text4)).gameObject.GetComponent<MeshFilter>().mesh = ((Component)val.Find(text4)).gameObject.GetComponent<MeshFilter>().mesh;
							((Renderer)((Component)((Component)saplingRef.Prefab.transform.Find(text5)).transform.Find(text4)).gameObject.GetComponent<MeshRenderer>()).sharedMaterials = sharedMaterials;
						}
					}
				}
				component3.m_icon = (saplingRef.icon ? CreateSprite(saplingRef.key + "PieceIcon.png", new Rect(0f, 0f, 64f, 64f)) : component3.m_resources[0].m_resItem.m_itemData.GetIcon());
				component3.m_placeEffect.m_effectPrefabs[0].m_prefab = prefabRefs["vfx_Place_wood_pole"];
				component3.m_placeEffect.m_effectPrefabs[1].m_prefab = prefabRefs["sfx_build_cultivator"];
				saplingRef.Prefab.GetComponent<Destructible>().m_hitEffect.m_effectPrefabs[0].m_prefab = prefabRefs["Birch_Sapling"].GetComponent<Destructible>().m_hitEffect.m_effectPrefabs[0].m_prefab;
				saplingRef.Prefab.GetComponent<Destructible>().m_hitEffect.m_effectPrefabs[1].m_prefab = prefabRefs["Birch_Sapling"].GetComponent<Destructible>().m_hitEffect.m_effectPrefabs[1].m_prefab;
			}
			isInitialized = true;
		}

		private static void InitCrops()
		{
			//IL_0349: Unknown result type (might be due to invalid IL or missing references)
			//IL_0430: Unknown result type (might be due to invalid IL or missing references)
			//IL_0460: Unknown result type (might be due to invalid IL or missing references)
			Dbgl("InitCrops");
			bool enableCropOverrides = config.EnableCropOverrides;
			foreach (PrefabDB item in new List<PrefabDB>
			{
				new PrefabDB
				{
					key = "sapling_barley",
					resourceCost = ((!enableCropOverrides) ? 1 : config.BarleyCost),
					resourceReturn = (enableCropOverrides ? config.BarleyReturn : 2)
				},
				new PrefabDB
				{
					key = "sapling_carrot",
					resourceCost = ((!enableCropOverrides) ? 1 : config.CarrotCost),
					resourceReturn = ((!enableCropOverrides) ? 1 : config.CarrotReturn)
				},
				new PrefabDB
				{
					key = "sapling_flax",
					resourceCost = ((!enableCropOverrides) ? 1 : config.FlaxCost),
					resourceReturn = (enableCropOverrides ? config.FlaxReturn : 2)
				},
				new PrefabDB
				{
					key = "sapling_onion",
					resourceCost = ((!enableCropOverrides) ? 1 : config.OnionCost),
					resourceReturn = ((!enableCropOverrides) ? 1 : config.OnionReturn)
				},
				new PrefabDB
				{
					key = "sapling_seedcarrot",
					resourceCost = ((!enableCropOverrides) ? 1 : config.SeedCarrotCost),
					resourceReturn = (enableCropOverrides ? config.SeedCarrotReturn : 3)
				},
				new PrefabDB
				{
					key = "sapling_seedonion",
					resourceCost = ((!enableCropOverrides) ? 1 : config.SeedOnionCost),
					resourceReturn = (enableCropOverrides ? config.SeedOnionReturn : 3)
				},
				new PrefabDB
				{
					key = "sapling_seedturnip",
					resourceCost = ((!enableCropOverrides) ? 1 : config.SeedTurnipCost),
					resourceReturn = (enableCropOverrides ? config.SeedTurnipReturn : 3)
				},
				new PrefabDB
				{
					key = "sapling_turnip",
					resourceCost = ((!enableCropOverrides) ? 1 : config.TurnipCost),
					resourceReturn = ((!enableCropOverrides) ? 1 : config.TurnipReturn)
				},
				new PrefabDB
				{
					key = "sapling_magecap",
					resourceCost = ((!enableCropOverrides) ? 1 : config.MagecapCost),
					resourceReturn = ((!enableCropOverrides) ? 1 : config.MagecapReturn),
					extraDrops = true
				},
				new PrefabDB
				{
					key = "sapling_jotunpuffs",
					resourceCost = ((!enableCropOverrides) ? 1 : config.JotunPuffsCost),
					resourceReturn = ((!enableCropOverrides) ? 1 : config.JotunPuffsReturn),
					extraDrops = true
				}
			})
			{
				Piece component = item.Prefab.GetComponent<Piece>();
				Plant component2 = item.Prefab.GetComponent<Plant>();
				Pickable component3 = component2.m_grownPrefabs[0].GetComponent<Pickable>();
				component.m_resources[0].m_amount = item.resourceCost;
				component2.m_destroyIfCantGrow = (item.Prefab.GetComponent<Piece>().m_groundOnly = !config.PlaceAnywhere);
				if (!config.EnforceBiomesVanilla)
				{
					component2.m_biome = (Biome)895;
				}
				component2.m_minScale = (enableCropOverrides ? config.CropMinScale : 0.9f);
				component2.m_maxScale = (enableCropOverrides ? config.CropMaxScale : 1.1f);
				component2.m_growTime = (enableCropOverrides ? config.CropGrowTimeMin : 4000f);
				component2.m_growTimeMax = (enableCropOverrides ? config.CropGrowTimeMax : 5000f);
				component2.m_growRadius = (enableCropOverrides ? config.CropGrowRadius : 0.5f);
				component2.m_needCultivatedGround = (component.m_cultivatedGroundOnly = !enableCropOverrides || config.CropRequireCultivation);
				component3.m_amount = item.resourceReturn;
				component3.m_extraDrops.m_drops.Clear();
				if (item.extraDrops && !enableCropOverrides)
				{
					component3.m_extraDrops.m_drops.Add(new DropData
					{
						m_item = component3.m_itemPrefab,
						m_stackMin = 1,
						m_stackMax = 1,
						m_weight = 0f
					});
				}
			}
		}

		private static void InitCultivator()
		{
			Dbgl("InitCultivator");
			ItemDrop component = prefabRefs["Cultivator"].GetComponent<ItemDrop>();
			for (int i = 0; i < saplingRefs.Count; i++)
			{
				if (!component.m_itemData.m_shared.m_buildPieces.m_pieces.Contains(saplingRefs[i].Prefab))
				{
					component.m_itemData.m_shared.m_buildPieces.m_pieces.Add(saplingRefs[i].Prefab);
				}
			}
			for (int j = 0; j < pieceRefs.Count; j++)
			{
				if (pieceRefs[j].enabled && !component.m_itemData.m_shared.m_buildPieces.m_pieces.Contains(pieceRefs[j].Prefab))
				{
					component.m_itemData.m_shared.m_buildPieces.m_pieces.Add(pieceRefs[j].Prefab);
				}
			}
			component.m_itemData.m_shared.m_buildPieces.m_canRemovePieces = true;
		}

		private static void FinalInit(ZNetScene instance)
		{
			InitPieceRefs();
			InitPieces();
			InitSaplingRefs();
			InitSaplings();
			InitCrops();
			InitCultivator();
			if (stringDictionary.Count > 0)
			{
				InitLocalization();
			}
			foreach (GameObject item in new List<GameObject>
			{
				prefabRefs["Ancient_Sapling"],
				prefabRefs["Ygga_Sapling"]
			})
			{
				if (!instance.m_prefabs.Contains(item))
				{
					instance.m_prefabs.Add(item);
					instance.m_namedPrefabs.Add(instance.GetPrefabHash(item), item);
				}
			}
		}

		private static void ModifyTreeDrops()
		{
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			if (!config.EnableSeedOverrides)
			{
				return;
			}
			foreach (KeyValuePair<GameObject, GameObject> item2 in new Dictionary<GameObject, GameObject>
			{
				{
					prefabRefs["Birch1"],
					prefabRefs["BirchSeeds"]
				},
				{
					prefabRefs["Birch2"],
					prefabRefs["BirchSeeds"]
				},
				{
					prefabRefs["Birch2_aut"],
					prefabRefs["BirchSeeds"]
				},
				{
					prefabRefs["Birch1_aut"],
					prefabRefs["BirchSeeds"]
				},
				{
					prefabRefs["Oak1"],
					prefabRefs["Acorn"]
				},
				{
					prefabRefs["SwampTree1"],
					prefabRefs["AncientSeed"]
				},
				{
					prefabRefs["Beech1"],
					prefabRefs["BeechSeeds"]
				},
				{
					prefabRefs["Pinetree_01"],
					prefabRefs["PineCone"]
				},
				{
					prefabRefs["FirTree"],
					prefabRefs["FirCone"]
				}
			})
			{
				TreeBase component = item2.Key.GetComponent<TreeBase>();
				DropData item = default(DropData);
				bool flag = false;
				foreach (DropData drop in component.m_dropWhenDestroyed.m_drops)
				{
					if (((object)drop.m_item).Equals((object?)item2.Value))
					{
						flag = true;
						item = drop;
						break;
					}
				}
				if (flag)
				{
					component.m_dropWhenDestroyed.m_drops.Remove(item);
				}
				item.m_item = item2.Value;
				item.m_stackMin = config.SeedDropMin;
				item.m_stackMax = config.SeedDropMax;
				item.m_weight = 1f;
				component.m_dropWhenDestroyed.m_dropMin = config.TreeDropMin;
				component.m_dropWhenDestroyed.m_dropMax = config.TreeDropMax;
				component.m_dropWhenDestroyed.m_drops.Add(item);
				component.m_dropWhenDestroyed.m_dropChance = Mathf.Clamp(config.DropChance, 0f, 1f);
				component.m_dropWhenDestroyed.m_oneOfEach = config.OneOfEach;
			}
		}

		internal static void CoreSettingChanged(object o, EventArgs e)
		{
			Dbgl("Config setting changed, re-initializing mod");
			InitPieceRefs();
			InitPieces();
			InitSaplingRefs();
			InitSaplings();
			InitCrops();
			InitCultivator();
		}

		internal static void PickableSettingChanged(object o, EventArgs e)
		{
			Dbgl("Config setting changed, re-initializing pieces");
			InitPieceRefs();
			InitPieces();
			InitCultivator();
		}

		internal static void SaplingSettingChanged(object o, EventArgs e)
		{
			Dbgl("Config setting changed, re-initializing saplings");
			InitSaplingRefs();
			InitSaplings();
		}

		internal static void SeedSettingChanged(object o, EventArgs e)
		{
			Dbgl("Config setting changed, modifying TreeBase drop tables");
			ModifyTreeDrops();
		}

		internal static void CropSettingChanged(object o, EventArgs e)
		{
			Dbgl("Config setting changed, re-initializing crops");
			InitCrops();
		}

		public static void InitLocalization()
		{
			Dbgl("InitLocalization");
			foreach (KeyValuePair<string, string> item in stringDictionary)
			{
				Traverse.Create((object)Localization.instance).Method("AddWord", new object[2]
				{
					"pe" + item.Key,
					item.Value
				}).GetValue(new object[2]
				{
					"pe" + item.Key,
					item.Value
				});
			}
			stringDictionary.Clear();
		}
	}
}
namespace Advize_PlantEverything.Configuration
{
	internal class ModConfig
	{
		internal class ConfigurationManagerAttributes
		{
			public bool? Browsable;

			[<3fbd689e-4b20-4884-b483-91c1a9a80245>Nullable(2)]
			public string Category;

			public int? Order;

			public bool? ReadOnly;
		}

		[<3fbd689e-4b20-4884-b483-91c1a9a80245>Nullable(0)]
		[<5a2974cb-8bd2-4412-94ed-d169ec648517>NullableContext(2)]
		internal class ConfigManagerHelper
		{
			private static Assembly BepinexConfigManager => AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<5a2974cb-8bd2-4412-94ed-d169ec648517>NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager");

			private static Type ConfigManagerType => BepinexConfigManager?.GetType("ConfigurationManager.ConfigurationManager");

			private static object ConfigManager
			{
				get
				{
					if (!(ConfigManagerType == null))
					{
						return Chainloader.ManagerObject.GetComponent(ConfigManagerType);
					}
					return null;
				}
			}

			internal static void ReloadConfigDisplay()
			{
				ConfigManager?.GetType().GetMethod("BuildSettingList").Invoke(ConfigManager, Array.Empty<object>());
			}
		}

		private readonly ConfigFile ConfigFile;

		private readonly ConfigSync ConfigSync;

		private readonly ConfigEntry<bool> serverConfigLocked;

		internal readonly ConfigEntry<int> nexusID;

		private readonly ConfigEntry<bool> enableDebugMessages;

		private readonly ConfigEntry<bool> showPickableSpawners;

		private readonly ConfigEntry<bool> enableMiscFlora;

		private readonly ConfigEntry<bool> snappableVines;

		private readonly ConfigEntry<bool> enableLocalization;

		private readonly ConfigEntry<string> language;

		private readonly ConfigEntry<bool> requireCultivation;

		private readonly ConfigEntry<bool> placeAnywhere;

		private readonly ConfigEntry<bool> enforceBiomes;

		private readonly ConfigEntry<bool> enforceBiomesVanilla;

		private readonly ConfigEntry<bool> recoverResources;

		private readonly ConfigEntry<bool> resourcesSpawnEmpty;

		private readonly ConfigEntry<int> raspberryCost;

		private readonly ConfigEntry<int> blueberryCost;

		private readonly ConfigEntry<int> cloudberryCost;

		private readonly ConfigEntry<int> raspberryRespawnTime;

		private readonly ConfigEntry<int> blueberryRespawnTime;

		private readonly ConfigEntry<int> cloudberryRespawnTime;

		private readonly ConfigEntry<int> raspberryReturn;

		private readonly ConfigEntry<int> blueberryReturn;

		private readonly ConfigEntry<int> cloudberryReturn;

		private readonly ConfigEntry<bool> enableCropOverrides;

		private readonly ConfigEntry<bool> cropRequireCultivation;

		private readonly ConfigEntry<bool> cropRequireSunlight;

		private readonly ConfigEntry<bool> cropRequireGrowthSpace;

		private readonly ConfigEntry<float> cropMinScale;

		private readonly ConfigEntry<float> cropMaxScale;

		private readonly ConfigEntry<float> cropGrowTimeMin;

		private readonly ConfigEntry<float> cropGrowTimeMax;

		private readonly ConfigEntry<float> cropGrowRadius;

		private readonly ConfigEntry<int> barleyCost;

		private readonly ConfigEntry<int> barleyReturn;

		private readonly ConfigEntry<int> carrotCost;

		private readonly ConfigEntry<int> carrotReturn;

		private readonly ConfigEntry<int> flaxCost;

		private readonly ConfigEntry<int> flaxReturn;

		private readonly ConfigEntry<int> onionCost;

		private readonly ConfigEntry<int> onionReturn;

		private readonly ConfigEntry<int> seedCarrotCost;

		private readonly ConfigEntry<int> seedCarrotReturn;

		private readonly ConfigEntry<int> seedOnionCost;

		private readonly ConfigEntry<int> seedOnionReturn;

		private readonly ConfigEntry<int> seedTurnipCost;

		private readonly ConfigEntry<int> seedTurnipReturn;

		private readonly ConfigEntry<int> turnipCost;

		private readonly ConfigEntry<int> turnipReturn;

		private readonly ConfigEntry<int> magecapCost;

		private readonly ConfigEntry<int> magecapReturn;

		private readonly ConfigEntry<int> jotunPuffsCost;

		private readonly ConfigEntry<int> jotunPuffsReturn;

		private readonly ConfigEntry<int> pickableBranchCost;

		private readonly ConfigEntry<int> pickableBranchReturn;

		private readonly ConfigEntry<int> pickableStoneCost;

		private readonly ConfigEntry<int> pickableStoneReturn;

		private readonly ConfigEntry<int> pickableFlintCost;

		private readonly ConfigEntry<int> pickableFlintReturn;

		private readonly ConfigEntry<int> mushroomCost;

		private readonly ConfigEntry<int> yellowMushroomCost;

		private readonly ConfigEntry<int> blueMushroomCost;

		private readonly ConfigEntry<int> mushroomRespawnTime;

		private readonly ConfigEntry<int> yellowMushroomRespawnTime;

		private readonly ConfigEntry<int> blueMushroomRespawnTime;

		private readonly ConfigEntry<int> mushroomReturn;

		private readonly ConfigEntry<int> yellowMushroomReturn;

		private readonly ConfigEntry<int> blueMushroomReturn;

		private readonly ConfigEntry<int> thistleCost;

		private readonly ConfigEntry<int> dandelionCost;

		private readonly ConfigEntry<int> thistleRespawnTime;

		private readonly ConfigEntry<int> dandelionRespawnTime;

		private readonly ConfigEntry<int> thistleReturn;

		private readonly ConfigEntry<int> dandelionReturn;

		private readonly ConfigEntry<float> birchMinScale;

		private readonly ConfigEntry<float> birchMaxScale;

		private readonly ConfigEntry<float> oakMinScale;

		private readonly ConfigEntry<float> oakMaxScale;

		private readonly ConfigEntry<float> ancientMinScale;

		private readonly ConfigEntry<float> ancientMaxScale;

		private readonly ConfigEntry<float> birchGrowthTime;

		private readonly ConfigEntry<float> oakGrowthTime;

		private readonly ConfigEntry<float> ancientGrowthTime;

		private readonly ConfigEntry<float> birchGrowRadius;

		private readonly ConfigEntry<float> oakGrowRadius;

		private readonly ConfigEntry<float> ancientGrowRadius;

		private readonly ConfigEntry<float> beechGrowthTime;

		private readonly ConfigEntry<float> pineGrowthTime;

		private readonly ConfigEntry<float> firGrowthTime;

		private readonly ConfigEntry<float> beechMinScale;

		private readonly ConfigEntry<float> beechMaxScale;

		private readonly ConfigEntry<float> pineMinScale;

		private readonly ConfigEntry<float> pineMaxScale;

		private readonly ConfigEntry<float> firMinScale;

		private readonly ConfigEntry<float> firMaxScale;

		private readonly ConfigEntry<float> beechGrowRadius;

		private readonly ConfigEntry<float> pineGrowRadius;

		private readonly ConfigEntry<float> firGrowRadius;

		private readonly ConfigEntry<float> yggaMinScale;

		private readonly ConfigEntry<float> yggaMaxScale;

		private readonly ConfigEntry<float> yggaGrowthTime;

		private readonly ConfigEntry<float> yggaGrowRadius;

		private readonly ConfigEntry<bool> enableSeedOverrides;

		private readonly ConfigEntry<int> seedDropMin;

		private readonly ConfigEntry<int> seedDropMax;

		private readonly ConfigEntry<int> treeDropMin;

		private readonly ConfigEntry<int> treeDropMax;

		private readonly ConfigEntry<float> dropChance;

		private readonly ConfigEntry<bool> oneOfEach;

		private readonly ConfigEntry<bool> enablePickableTimers;

		private readonly ConfigEntry<bool> enablePlantTimers;

		private readonly ConfigEntry<bool> growthAsPercentage;

		private readonly ConfigurationManagerAttributes seedSettingAtrributes = new ConfigurationManagerAttributes();

		private readonly List<ConfigurationManagerAttributes> cropSettingAttributes = new List<ConfigurationManagerAttributes>
		{
			new ConfigurationManagerAttributes(),
			new ConfigurationManagerAttributes
			{
				Order = 26
			},
			new ConfigurationManagerAttributes
			{
				Order = 25
			},
			new ConfigurationManagerAttributes
			{
				Order = 24
			}
		};

		internal bool EnableDebugMessages => enableDebugMessages.Value;

		internal bool ShowPickableSpawners => showPickableSpawners.Value;

		internal bool EnableMiscFlora => enableMiscFlora.Value;

		internal bool SnappableVines => snappableVines.Value;

		internal bool EnableLocalization => enableLocalization.Value;

		internal string Language => language.Value;

		internal bool RequireCultivation => requireCultivation.Value;

		internal bool PlaceAnywhere => placeAnywhere.Value;

		internal bool EnforceBiomes => enforceBiomes.Value;

		internal bool EnforceBiomesVanilla => enforceBiomesVanilla.Value;

		internal bool RecoverResources => recoverResources.Value;

		internal bool ResourcesSpawnEmpty => resourcesSpawnEmpty.Value;

		internal int RaspberryCost => raspberryCost.Value;

		internal int BlueberryCost => blueberryCost.Value;

		internal int CloudberryCost => cloudberryCost.Value;

		internal int RaspberryRespawnTime => raspberryRespawnTime.Value;

		internal int BlueberryRespawnTime => blueberryRespawnTime.Value;

		internal int CloudberryRespawnTime => cloudberryRespawnTime.Value;

		internal int RaspberryReturn => raspberryReturn.Value;

		internal int BlueberryReturn => blueberryReturn.Value;

		internal int CloudberryReturn => cloudberryReturn.Value;

		internal bool EnableCropOverrides => enableCropOverrides.Value;

		internal float CropMinScale => cropMinScale.Value;

		internal float CropMaxScale => cropMaxScale.Value;

		internal float CropGrowTimeMin => Mathf.Max(cropGrowTimeMin.Value, 10f);

		internal float CropGrowTimeMax => Mathf.Max(cropGrowTimeMax.Value, 10f);

		internal float CropGrowRadius => cropGrowRadius.Value;

		internal bool CropRequireCultivation => cropRequireCultivation.Value;

		internal bool CropRequireSunlight => cropRequireSunlight.Value;

		internal bool CropRequireGrowthSpace => cropRequireGrowthSpace.Value;

		internal int BarleyCost => barleyCost.Value;

		internal int BarleyReturn => barleyReturn.Value;

		internal int CarrotCost => carrotCost.Value;

		internal int CarrotReturn => carrotReturn.Value;

		internal int FlaxCost => flaxCost.Value;

		internal int FlaxReturn => flaxReturn.Value;

		internal int OnionCost => onionCost.Value;

		internal int OnionReturn => onionReturn.Value;

		internal int SeedCarrotCost => seedCarrotCost.Value;

		internal int SeedCarrotReturn => seedCarrotReturn.Value;

		internal int SeedOnionCost => seedOnionCost.Value;

		internal int SeedOnionReturn => seedOnionReturn.Value;

		internal int SeedTurnipCost => seedTurnipCost.Value;

		internal int SeedTurnipReturn => seedTurnipReturn.Value;

		internal int TurnipCost => turnipCost.Value;

		internal int TurnipReturn => turnipReturn.Value;

		internal int MagecapCost => magecapCost.Value;

		internal int MagecapReturn => magecapReturn.Value;

		internal int JotunPuffsCost => jotunPuffsCost.Value;

		internal int JotunPuffsReturn => jotunPuffsReturn.Value;

		internal int PickableBranchCost => pickableBranchCost.Value;

		internal int PickableBranchReturn => pickableBranchReturn.Value;

		internal int PickableStoneCost => pickableStoneCost.Value;

		internal int PickableStoneReturn => pickableStoneReturn.Value;

		internal int PickableFlintCost => pickableFlintCost.Value;

		internal int PickableFlintReturn => pickableFlintReturn.Value;

		internal int MushroomCost => mushroomCost.Value;

		internal int YellowMushroomCost => yellowMushroomCost.Value;

		internal int BlueMushroomCost => blueMushroomCost.Value;

		internal int MushroomRespawnTime => mushroomRespawnTime.Value;

		internal int YellowMushroomRespawnTime => yellowMushroomRespawnTime.Value;

		internal int BlueMushroomRespawnTime => blueMushroomRespawnTime.Value;

		internal int MushroomReturn => mushroomReturn.Value;

		internal int YellowMushroomReturn => yellowMushroomReturn.Value;

		internal int BlueMushroomReturn => blueMushroomReturn.Value;

		internal int ThistleCost => thistleCost.Value;

		internal int DandelionCost => dandelionCost.Value;

		internal int ThistleRespawnTime => thistleRespawnTime.Value;

		internal int DandelionRespawnTime => dandelionRespawnTime.Value;

		internal int ThistleReturn => thistleReturn.Value;

		internal int DandelionReturn => dandelionReturn.Value;

		internal float BirchMinScale => birchMinScale.Value;

		internal float BirchMaxScale => birchMaxScale.Value;

		internal float OakMinScale => oakMinScale.Value;

		internal float OakMaxScale => oakMaxScale.Value;

		internal float AncientMinScale => ancientMinScale.Value;

		internal float AncientMaxScale => ancientMaxScale.Value;

		internal float BirchGrowthTime => Mathf.Max(birchGrowthTime.Value, 10f);

		internal float OakGrowthTime => Mathf.Max(oakGrowthTime.Value, 10f);

		internal float AncientGrowthTime => Mathf.Max(ancientGrowthTime.Value, 10f);

		internal float BirchGrowRadius => birchGrowRadius.Value;

		internal float OakGrowRadius => oakGrowRadius.Value;

		internal float AncientGrowRadius => ancientGrowRadius.Value;

		internal float BeechGrowthTime => Mathf.Max(beechGrowthTime.Value, 10f);

		internal float PineGrowthTime => Mathf.Max(pineGrowthTime.Value, 10f);

		internal float FirGrowthTime => Mathf.Max(firGrowthTime.Value, 10f);

		internal float BeechMinScale => beechMinScale.Value;

		internal float BeechMaxScale => beechMaxScale.Value;

		internal float PineMinScale => pineMinScale.Value;

		internal float PineMaxScale => pineMaxScale.Value;

		internal float FirMinScale => firMinScale.Value;

		internal float FirMaxScale => firMaxScale.Value;

		internal float BeechGrowRadius => beechGrowRadius.Value;

		internal float PineGrowRadius => pineGrowRadius.Value;

		internal float FirGrowRadius => firGrowRadius.Value;

		internal float YggaMinScale => yggaMinScale.Value;

		internal float YggaMaxScale => yggaMaxScale.Value;

		internal float YggaGrowthTime => yggaGrowthTime.Value;

		internal float YggaGrowRadius => yggaGrowRadius.Value;

		internal bool EnableSeedOverrides => enableSeedOverrides.Value;

		internal int SeedDropMin => seedDropMin.Value;

		internal int SeedDropMax => seedDropMax.Value;

		internal int TreeDropMin => treeDropMin.Value;

		internal int TreeDropMax => treeDropMax.Value;

		internal float DropChance => dropChance.Value;

		internal bool OneOfEach => oneOfEach.Value;

		internal bool EnablePickableTimers => enablePickableTimers.Value;

		internal bool EnablePlantTimers => enablePlantTimers.Value;

		internal bool GrowthAsPercentage => growthAsPercentage.Value;

		private ConfigEntry<T> Config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ConfigFile.Bind<T>(group, name, value, description);
			ConfigSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> Config<T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return Config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		internal ModConfig(ConfigFile configFile, ConfigSync configSync)
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Expected O, but got Unknown
			//IL_0385: Unknown result type (might be due to invalid IL or missing references)
			//IL_0390: Expected O, but got Unknown
			//IL_03c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cc: Expected O, but got Unknown
			//IL_03fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0408: Expected O, but got Unknown
			//IL_0439: Unknown result type (might be due to invalid IL or missing references)
			//IL_0444: Expected O, but got Unknown
			//IL_0475: Unknown result type (might be due to invalid IL or missing references)
			//IL_0480: Expected O, but got Unknown
			//IL_04b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bc: Expected O, but got Unknown
			//IL_04e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f4: Expected O, but got Unknown
			//IL_0521: Unknown result type (might be due to invalid IL or missing references)
			//IL_052c: Expected O, but got Unknown
			//IL_0559: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Expected O, but got Unknown
			//IL_0591: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Expected O, but got Unknown
			//IL_05c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d4: Expected O, but got Unknown
			//IL_0601: Unknown result type (might be due to invalid IL or missing references)
			//IL_060c: Expected O, but got Unknown
			//IL_0639: Unknown result type (might be due to invalid IL or missing references)
			//IL_0644: Expected O, but got Unknown
			//IL_0671: Unknown result type (might be due to invalid IL or missing references)
			//IL_067c: Expected O, but got Unknown
			//IL_06a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b4: Expected O, but got Unknown
			//IL_06e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ec: Expected O, but got Unknown
			//IL_0719: Unknown result type (might be due to invalid IL or missing references)
			//IL_0724: Expected O, but got Unknown
			//IL_0751: Unknown result type (might be due to invalid IL or missing references)
			//IL_075c: Expected O, but got Unknown
			//IL_0789: Unknown result type (might be due to invalid IL or missing references)
			//IL_0794: Expected O, but got Unknown
			//IL_07c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_07cc: Expected O, but got Unknown
			//IL_07f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0804: Expected O, but got Unknown
			//IL_0831: Unknown result type (might be due to invalid IL or missing references)
			//IL_083c: Expected O, but got Unknown
			//IL_0869: Unknown result type (might be due to invalid IL or missing references)
			//IL_0874: Expected O, but got Unknown
			//IL_08a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_08ac: Expected O, but got Unknown
			//IL_08d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_08e4: Expected O, but got Unknown
			//IL_0911: Unknown result type (might be due to invalid IL or missing references)
			//IL_091c: Expected O, but got Unknown
			//IL_0949: Unknown result type (might be due to invalid IL or missing references)
			//IL_0954: Expected O, but got Unknown
			//IL_0981: Unknown result type (might be due to invalid IL or missing references)
			//IL_098c: Expected O, but got Unknown
			//IL_09b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_09c4: Expected O, but got Unknown
			//IL_1008: Unknown result type (might be due to invalid IL or missing references)
			//IL_1013: Expected O, but got Unknown
			//IL_103a: Unknown result type (might be due to invalid IL or missing references)
			//IL_1045: Expected O, but got Unknown
			//IL_106c: Unknown result type (might be due to invalid IL or missing references)
			//IL_1077: Expected O, but got Unknown
			//IL_109e: Unknown result type (might be due to invalid IL or missing references)
			//IL_10a9: Expected O, but got Unknown
			//IL_10d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_10db: Expected O, but got Unknown
			//IL_1106: Unknown result type (might be due to invalid IL or missing references)
			//IL_1111: Expected O, but got Unknown
			//IL_1138: Unknown result type (might be due to invalid IL or missing references)
			//IL_1143: Expected O, but got Unknown
			ConfigFile = configFile;
			ConfigSync = configSync;
			serverConfigLocked = Config("General", "LockConfiguration", value: false, "If on, the configuration is locked and can be changed by server admins only.");
			nexusID = Config("General", "NexusID", 1042, new ConfigDescription("Nexus mod ID for updates.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Category = "Internal",
					ReadOnly = true
				}
			}), synchronizedSetting: false);
			enableDebugMessages = Config("General", "EnableDebugMessages", value: false, "Enable mod debug messages in console", synchronizedSetting: false);
			showPickableSpawners = Config("General", "ShowPickableSpawners", value: true, "Continue to show mushroom, thistle, and dandelion spawners after being picked. (Requires world reload on client to take effect)", synchronizedSetting: false);
			enableMiscFlora = Config("General", "EnableMiscFlora", value: true, "Enables small trees, bushes, shrubs, vines, and large mushrooms.");
			snappableVines = Config("General", "SnappableVines", value: true, "Enables snap points when placing vines adjacently", synchronizedSetting: false);
			enableLocalization = Config("General", "EnableLocalization", value: false, "Enable this to attempt to load localized text data for the language set in the following setting", synchronizedSetting: false);
			language = Config("General", "Language", "english", "Language to be used. If EnableLocalization is enabled, game will attempt to load localized text from a file named {language}_PlantEverything.json", synchronizedSetting: false);
			requireCultivation = Config("Difficulty", "RequireCultivation", value: false, "Pickable resources can only be planted on cultivated ground");
			placeAnywhere = Config("Difficulty", "PlaceAnywhere", value: false, "Allow resources to be placed anywhere (not just on the ground). Does not apply to mushrooms or flowers");
			enforceBiomes = Config("Difficulty", "EnforceBiomes", value: false, "Restrict modded plantables to being placed in their respective biome");
			enforceBiomesVanilla = Config("Difficulty", "EnforceBiomesVanilla", value: true, "Restrict vanilla plantables to being placed in their respective biome");
			recoverResources = Config("Difficulty", "RecoverResources", value: false, "Recover resources when pickables are removed with the cultivator. Applies to berries, mushrooms, and flowers");
			resourcesSpawnEmpty = Config("Difficulty", "ResourcesSpawnEmpty", value: false, "Specifies whether resources should spawn empty or full. Applies to berry bushes, mushrooms, flowers, and debris");
			raspberryCost = Config("Berries", "RaspberryCost", 5, "Number of raspberries required to place a raspberry bush. Set to 0 to disable the ability to plant this resource");
			blueberryCost = Config("Berries", "BlueberryCost", 5, "Number of blueberries required to place a blueberry bush. Set to 0 to disable the ability to plant this resource");
			cloudberryCost = Config("Berries", "CloudberryCost", 5, "Number of cloudberries required to place a cloudberry bush. Set to 0 to disable the ability to plant this resource");
			raspberryRespawnTime = Config("Berries", "RaspberryRespawnTime", 300, "Number of minutes it takes for a raspberry bush to respawn berries");
			blueberryRespawnTime = Config("Berries", "BlueberryRespawnTime", 300, "Number of minutes it takes for a blueberry bush to respawn berries");
			cloudberryRespawnTime = Config("Berries", "CloudberryRespawnTime", 300, "Number of minutes it takes for a cloudberry bush to respawn berries");
			raspberryReturn = Config("Berries", "RaspberryReturn", 1, "Number of berries a raspberry bush will spawn");
			blueberryReturn = Config("Berries", "BlueberryReturn", 1, "Number of berries a blueberry bush will spawn");
			cloudberryReturn = Config("Berries", "CloudberryReturn", 1, "Number of berries a cloudberry bush will spawn");
			enableCropOverrides = Config("Crops", "EnableCropOverrides", value: false, new ConfigDescription("Enables the [Crops] section of this config", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 27
				}
			}));
			cropMinScale = Config("Crops", "CropMinScale", 0.9f, new ConfigDescription("The minimum scaling factor used to scale crops upon growth", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropMaxScale = Config("Crops", "CropMaxScale", 1.1f, new ConfigDescription("The maximum scaling factor used to scale crops upon growth", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropGrowTimeMin = Config("Crops", "CropGrowTimeMin", 4000f, new ConfigDescription("Minimum number of seconds it takes for crops to grow (will take at least 10 seconds after planting to grow)", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropGrowTimeMax = Config("Crops", "CropGrowTimeMax", 5000f, new ConfigDescription("Maximum number of seconds it takes for crops to grow (will take at least 10 seconds after planting to grow)", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropGrowRadius = Config("Crops", "CropGrowRadius", 0.5f, new ConfigDescription("Radius of free space required for crops to grow", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropRequireCultivation = Config("Crops", "CropsRequireCultivation", value: true, new ConfigDescription("Crops can only be planted on cultivated ground", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[1] }));
			cropRequireSunlight = Config("Crops", "CropsRequireSunlight", value: true, new ConfigDescription("Crops can only grow under an open sky", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[2] }));
			cropRequireGrowthSpace = Config("Crops", "CropsRequireGrowthSpace", value: true, new ConfigDescription("Crops require space to grow. This setting overrides the CropGrowRadius setting but without altering it, allowing grid spacing mods to continue functioning", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[3] }));
			barleyCost = Config("Crops", "BarleyCost", 1, new ConfigDescription("Resource cost of planting barley", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			barleyReturn = Config("Crops", "BarleyReturn", 2, new ConfigDescription("Resources gained upon harvesting barley (does not apply to wild barley)", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			carrotCost = Config("Crops", "CarrotCost", 1, new ConfigDescription("Resource cost of planting carrots", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			carrotReturn = Config("Crops", "CarrotReturn", 1, new ConfigDescription("Resources gained upon harvesting carrots", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			flaxCost = Config("Crops", "FlaxCost", 1, new ConfigDescription("Resource cost of planting flax", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			flaxReturn = Config("Crops", "FlaxReturn", 2, new ConfigDescription("Resources gained upon harvesting flax (does not apply to wild flax)", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			onionCost = Config("Crops", "OnionCost", 1, new ConfigDescription("Resource cost of planting onions", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			onionReturn = Config("Crops", "OnionReturn", 1, new ConfigDescription("Resources gained upon harvesting onions", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedCarrotCost = Config("Crops", "SeedCarrotCost", 1, new ConfigDescription("Resource cost of planting seed carrots", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedCarrotReturn = Config("Crops", "SeedCarrotReturn", 3, new ConfigDescription("Resources gained upon harvesting seed carrots", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedOnionCost = Config("Crops", "SeedOnionCost", 1, new ConfigDescription("Resource cost of planting seed onions", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedOnionReturn = Config("Crops", "SeedOnionReturn", 3, new ConfigDescription("Resources gained upon harvesting seed onions", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedTurnipCost = Config("Crops", "SeedTurnipCost", 1, new ConfigDescription("Resource cost of planting seed turnips", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedTurnipReturn = Config("Crops", "SeedTurnipReturn", 3, new ConfigDescription("Resources gained upon harvesting seed turnips", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			turnipCost = Config("Crops", "TurnipCost", 1, new ConfigDescription("Resource cost of planting turnips", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			turnipReturn = Config("Crops", "TurnipReturn", 1, new ConfigDescription("Resources gained upon harvesting turnips", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			magecapCost = Config("Crops", "MagecapCost", 1, new ConfigDescription("Resource cost of planting magecap", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			magecapReturn = Config("Crops", "MagecapReturn", 3, new ConfigDescription("Resources gained upon harvesting magecap", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			jotunPuffsCost = Config("Crops", "JotunPuffsCost", 1, new ConfigDescription("Resource cost of planting Jotun puffs", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			jotunPuffsReturn = Config("Crops", "JotunPuffsReturn", 3, new ConfigDescription("Resources gained upon harvesting Jotun puffs", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			pickableBranchCost = Config("Debris", "PickableBranchCost", 5, "Amount of wood required to place branch debris. Set to 0 to disable the ability to plant this resource");
			pickableBranchReturn = Config("Debris", "PickableBranchReturn", 1, "Amount of wood that branch debris drops when picked");
			pickableStoneCost = Config("Debris", "PickableStoneCost", 1, "Amount of stone required to place stone debris. Set to 0 to disable the ability to plant this resource");
			pickableStoneReturn = Config("Debris", "PickableStoneReturn", 1, "Amount of stones that stone debris drops when picked");
			pickableFlintCost = Config("Debris", "PickableFlintCost", 5, "Amount of flint required to place flint debris. Set to 0 to disable the ability to plant this resource");
			pickableFlintReturn = Config("Debris", "PickableFlintReturn", 1, "Amount of flint that flint debris drops when picked");
			mushroomCost = Config("Mushrooms", "MushroomCost", 5, "Number of mushrooms required to place a pickable mushroom spawner. Set to 0 to disable the ability to plant this resource");
			yellowMushroomCost = Config("Mushrooms", "YellowMushroomCost", 5, "Number of yellow mushrooms required to place a pickable yellow mushroom spawner. Set to 0 to disable the ability to plant this resource");
			blueMushroomCost = Config("Mushrooms", "BlueMushroomCost", 5, "Number of blue mushrooms required to place a pickable blue mushroom spawner. Set to 0 to disable the ability to plant this resource");
			mushroomRespawnTime = Config("Mushrooms", "MushroomRespawnTime", 240, "Number of minutes it takes for mushrooms to respawn");
			yellowMushroomRespawnTime = Config("Mushrooms", "YellowMushroomRespawnTime", 240, "Number of minutes it takes for yellow mushrooms to respawn");
			blueMushroomRespawnTime = Config("Mushrooms", "BlueMushroomRespawnTime", 240, "Number of minutes it takes for blue mushrooms to respawn");
			mushroomReturn = Config("Mushrooms", "MushroomReturn", 1, "Number of mushrooms a pickable mushroom spawner will spawn");
			yellowMushroomReturn = Config("Mushrooms", "YellowMushroomReturn", 1, "Number of yellow mushrooms a pickable yellow mushroom spawner will spawn");
			blueMushroomReturn = Config("Mushrooms", "BlueMushroomReturn", 1, "Number of blue mushrooms a pickable blue mushroom spawner will spawn");
			thistleCost = Config("Flowers", "ThistleCost", 5, "Number of thistle required to place a pickable thistle spawner. Set to 0 to disable the ability to plant this resource");
			dandelionCost = Config("Flowers", "DandelionCost", 5, "Number of dandelion required to place a pickable dandelion spawner. Set to 0 to disable the ability to plant this resource");
			thistleRespawnTime = Config("Flowers", "ThistleRespawnTime", 240, "Number of minutes it takes for thistle to respawn");
			dandelionRespawnTime = Config("Flowers", "DandelionRespawnTime", 240, "Number of minutes it takes for dandelion to respawn");
			thistleReturn = Config("Flowers", "ThistleReturn", 1, "Number of thistle a pickable thistle spawner will spawn");
			dandelionReturn = Config("Flowers", "DandelionReturn", 1, "Number of dandelion a pickable dandelion spawner will spawn");
			birchMinScale = Config("Saplings", "BirchMinScale", 0.5f, "The minimum scaling factor used to scale a birch tree upon growth");
			birchMaxScale = Config("Saplings", "BirchMaxScale", 1f, "The maximum scaling factor used to scale a birch tree upon growth");
			oakMinScale = Config("Saplings", "OakMinScale", 0.7f, "The minimum scaling factor used to scale an oak tree upon growth");
			oakMaxScale = Config("Saplings", "OakMaxScale", 0.9f, "The maximum scaling factor used to scale an oak tree upon growth");
			ancientMinScale = Config("Saplings", "AncientMinScale", 0.5f, "The minimum scaling factor used to scale an ancient tree upon growth");
			ancientMaxScale = Config("Saplings", "AncientMaxScale", 2f, "The maximum scaling factor used to scale an ancient tree upon growth");
			birchGrowthTime = Config("Saplings", "BirchGrowthTime", 3000f, "Number of seconds it takes for a birch tree to grow from a birch sapling (will take at least 10 seconds after planting to grow)");
			oakGrowthTime = Config("Saplings", "OakGrowthTime", 3000f, "Number of seconds it takes for an oak tree to grow from an oak sapling (will take at least 10 seconds after planting to grow)");
			ancientGrowthTime = Config("Saplings", "AncientGrowthTime", 3000f, "Number of seconds it takes for an ancient tree to grow from an ancient sapling (will take at least 10 seconds after planting to grow)");
			birchGrowRadius = Config("Saplings", "BirchGrowRadius", 2f, "Radius of free space required for a birch sapling to grow");
			oakGrowRadius = Config("Saplings", "OakGrowRadius", 3f, "Radius of free space required for an oak sapling to grow");
			ancientGrowRadius = Config("Saplings", "AncientGrowRadius", 2f, "Radius of free space required for an ancient sapling to grow");
			beechGrowthTime = Config("Saplings", "BeechGrowthTime", 3000f, "Number of seconds it takes for a beech tree to grow from a beech sapling (will take at least 10 seconds after planting to grow)");
			pineGrowthTime = Config("Saplings", "PineGrowthTime", 3000f, "Number of seconds it takes for a pine tree to grow from a pine sapling (will take at least 10 seconds after planting to grow)");
			firGrowthTime = Config("Saplings", "FirGrowthTime", 3000f, "Number of seconds it takes for a fir tree to grow from a fir sapling (will take at least 10 seconds after planting to grow)");
			beechMinScale = Config("Saplings", "BeechMinScale", 0.8f, "The minimum scaling factor used to scale a beech tree upon growth");
			beechMaxScale = Config("Saplings", "BeechMaxScale", 1.5f, "The maximum scaling factor used to scale a beech tree upon growth");
			pineMinScale = Config("Saplings", "PineMinScale", 1.5f, "The minimum scaling factor used to scale a pine tree upon growth");
			pineMaxScale = Config("Saplings", "PineMaxScale", 2.5f, "The maximum scaling factor used to scale a pine tree upon growth");
			firMinScale = Config("Saplings", "FirMinScale", 1f, "The minimum scaling factor used to scale a fir tree upon growth");
			firMaxScale = Config("Saplings", "FirMaxScale", 2.5f, "The maximum scaling factor used to scale a fir tree upon growth");
			beechGrowRadius = Config("Saplings", "BeechGrowRadius", 2f, "Radius of free space required for a beech sapling to grow");
			pineGrowRadius = Config("Saplings", "PineGrowRadius", 2f, "Radius of free space required for a pine sapling to grow");
			firGrowRadius = Config("Saplings", "FirGrowRadius", 2f, "Radius of free space required for a fir sapling to grow");
			yggaMinScale = Config("Saplings", "YggaMinScale", 0.5f, "The minimum scaling factor used to scale a ygga tree upon growth");
			yggaMaxScale = Config("Saplings", "YggaMaxScale", 2f, "The minimum scaling factor used to scale a ygga tree upon growth");
			yggaGrowthTime = Config("Saplings", "YggaGrowthTime", 3000f, "Number of seconds it takes for a ygga tree to grow from a ygga sapling (will take at least 10 seconds after planting to grow)");
			yggaGrowRadius = Config("Saplings", "YggaGrowRadius", 2f, "Radius of free space required for a ygga sapling to grow");
			enableSeedOverrides = Config("Seeds", "EnableSeedOverrides", value: false, new ConfigDescription("Enables the [Seeds] section of this config", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 10
				}
			}));
			seedDropMin = Config("Seeds", "seedDropMin", 1, new ConfigDescription("Determines minimum amount of seeds that can drop when trees drop seeds", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			seedDropMax = Config("Seeds", "seedDropMax", 2, new ConfigDescription("Determines maximum amount of seeds that can drop when trees drop seeds", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			treeDropMin = Config("Seeds", "treeDropMin", 1, new ConfigDescription("Determines minimum amount of times a destroyed tree will attempt to select a drop from its drop table", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			treeDropMax = Config("Seeds", "treeDropMax", 3, new ConfigDescription("Determines (maximum amount of times - 1) a destroyed tree will attempt to select a drop from its drop table", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			dropChance = Config("Seeds", "dropChance", 0.5f, new ConfigDescription("Chance that items will drop from trees when destroyed. Default value 0.5f (50%). Set between 0 and 1f", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			oneOfEach = Config("Seeds", "oneOfEach", value: false, new ConfigDescription("When enabled, destroyed trees will not drop the same item from its drop table more than once", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			enablePickableTimers = Config("UI", "EnablePickableTimers", value: true, "Enables display of growth time remaining on pickable resources.", synchronizedSetting: false);
			enablePlantTimers = Config("UI", "EnablePlantTimers", value: true, "Enables display of growth time remaining on planted resources, such as crops and saplings.", synchronizedSetting: false);
			growthAsPercentage = Config("UI", "GrowthAsPercentage", value: false, "Enables display of growth time as a percentage instead of time remaining.", synchronizedSetting: false);
			showPickableSpawners.SettingChanged += PlantEverything.CoreSettingChanged;
			enableMiscFlora.SettingChanged += PlantEverything.CoreSettingChanged;
			snappableVines.SettingChanged += PlantEverything.CoreSettingChanged;
			requireCultivation.SettingChanged += PlantEverything.CoreSettingChanged;
			placeAnywhere.SettingChanged += PlantEverything.CoreSettingChanged;
			enforceBiomes.SettingChanged += PlantEverything.CoreSettingChanged;
			recoverResources.SettingChanged += PlantEverything.CoreSettingChanged;
			raspberryCost.SettingChanged += PlantEverything.PickableSettingChanged;
			blueberryCost.SettingChanged += PlantEverything.PickableSettingChanged;
			cloudberryCost.SettingChanged += PlantEverything.PickableSettingChanged;
			raspberryRespawnTime.SettingChanged += PlantEverything.PickableSettingChanged;
			blueberryRespawnTime.SettingChanged += PlantEverything.PickableSettingChanged;
			cloudberryRespawnTime.SettingChanged += PlantEverything.PickableSettingChanged;
			raspberryReturn.SettingChanged += PlantEverything.PickableSettingChanged;
			blueberryReturn.SettingChanged += PlantEverything.PickableSettingChanged;
			cloudberryReturn.SettingChanged += PlantEverything.PickableSettingChanged;
			enableCropOverrides.SettingChanged += PlantEverything.CropSettingChanged;
			cropMinScale.SettingChanged += PlantEverything.CropSettingChanged;
			cropMaxScale.SettingChanged += PlantEverything.CropSettingChanged;
			cropGrowTimeMin.SettingChanged += PlantEverything.CropSettingChanged;
			cropGrowTimeMax.SettingChanged += PlantEverything.CropSettingChanged;
			cropGrowRadius.SettingChanged += PlantEverything.CropSettingChanged;
			cropRequireCultivation.SettingChanged += PlantEverything.CropSettingChanged;
			barleyCost.SettingChanged += PlantEverything.CropSettingChanged;
			barleyReturn.SettingChanged += PlantEverything.CropSettingChanged;
			carrotCost.SettingChanged += PlantEverything.CropSettingChanged;
			carrotReturn.SettingChanged += PlantEverything.CropSettingChanged;
			flaxCost.SettingChanged += PlantEverything.CropSettingChanged;
			flaxReturn.SettingChanged += PlantEverything.CropSettingChanged;
			onionCost.SettingChanged += PlantEverything.CropSettingChanged;
			onionReturn.SettingChanged += PlantEverything.CropSettingChanged;
			seedCarrotCost.SettingChanged += PlantEverything.CropSettingChanged;
			seedCarrotReturn.SettingChanged += PlantEverything.CropSettingChanged;
			seedOnionCost.SettingChanged += PlantEverything.CropSettingChanged;
			seedOnionReturn.SettingChanged += PlantEverything.CropSettingChanged;
			seedTurnipCost.SettingChanged += PlantEverything.CropSettingChanged;
			seedTurnipReturn.SettingChanged += PlantEverything.Cro

BepInEx/plugins/AeehyehssReeper-ChaosArmor/ChaosArmor.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BlacksmithTools;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: AssemblyProduct("ChaosArmor")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCompany("ChaosArmor")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyTitle("ChaosArmor")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace ChaosArmor
{
	[BepInPlugin("ReepusDeepusDelmeepus4902761.ChaosArmor", "ChaosArmor", "12.3.1")]
	public class ReepusDeepusDelmeepusChaosArmor : BaseUnityPlugin
	{
		[HarmonyPatch]
		public static class ObjectDBPatch
		{
			[HarmonyPatch(typeof(ObjectDB), "Awake")]
			[HarmonyPriority(0)]
			[HarmonyPostfix]
			public static void Patch_ObjectDBAwake(ObjectDB __instance)
			{
				StatusEffect statusEffect = __instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode(shieldVanilla));
				staffShield = (SE_Shield)(object)((statusEffect is SE_Shield) ? statusEffect : null);
			}
		}

		[HarmonyPatch]
		public static class ZNetScenePatch
		{
			[HarmonyPostfix]
			[HarmonyPatch(typeof(ZNetScene), "Awake")]
			public static void Patch_ZNetSceneAwake(ZNetScene __instance)
			{
				__instance.m_prefabs.Add(Clanka.prefabStep);
				__instance.m_prefabs.Add(Clanka.prefabRun);
				__instance.m_prefabs.Add(Clanka.prefabJump);
				__instance.m_prefabs.Add(Clanka.prefabDodge);
				__instance.m_prefabs.Add(Clanka.prefabLand);
				__instance.m_prefabs.Add(Clanka.prefabBootStep);
			}
		}

		[HarmonyPatch]
		public static class AudioManPatch
		{
			private static void SetAudioMixerGroup(GameObject prefab, AudioMixerGroup group)
			{
				AudioSource component = prefab.GetComponent<AudioSource>();
				component.outputAudioMixerGroup = group;
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(AudioMan), "Awake")]
			public static void Patch_AudioManAwake(AudioMan __instance)
			{
				if (!((Object)(object)Clanka.prefabStep == (Object)null))
				{
					AudioMixerGroup group = __instance.m_ambientMixer.audioMixer.FindMatchingGroups("Effects/SFX").FirstOrDefault();
					SetAudioMixerGroup(Clanka.prefabStep, group);
					SetAudioMixerGroup(Clanka.prefabRun, group);
					SetAudioMixerGroup(Clanka.prefabDodge, group);
					SetAudioMixerGroup(Clanka.prefabLand, group);
					SetAudioMixerGroup(Clanka.prefabJump, group);
					SetAudioMixerGroup(Clanka.prefabBootRun, group);
					SetAudioMixerGroup(Clanka.prefabBootStep, group);
				}
			}
		}

		private const string ModName = "ChaosArmor";

		private const string ModVersion = "12.3.1";

		private const string ModGUID = "ReepusDeepusDelmeepus4902761.ChaosArmor";

		private const string T0Chest = "T0ChaosPlateArmor";

		private const string T1Chest = "T1ChaosPlateArmor";

		private const string T2Chest = "T2ChaosPlateArmor";

		private const string T3Chest = "ChaosPlateArmorBody";

		private const string T4Chest = "EliteChaosPlateArmor";

		private const string T5Chest = "EliteChaosPlateArmorTzeentch";

		private const string T0CUNTLegs = "T0ChaosPlateLegs";

		private const string T1CUNTLegs = "T1ChaosPlateLegs";

		private const string T2CUNTLegs = "T2ChaosPlateLegs";

		private const string T3CUNTLegs = "ChaosPlateLegs";

		private const string T4CUNTLegs = "EliteChaosPlateLegs";

		private static string shieldVanilla = "Staff_shield";

		public static int T1Hash;

		public static int T2Hash;

		public static int T3Hash;

		public static int T4Hash;

		public static int T5Hash;

		public static HashSet<int> clankyPrefabNames = new HashSet<int>();

		public static SE_Shield staffShield;

		private static ConfigEntry<bool> doTheRoar;

		private static SE_Stats T3SetStatus;

		private static SE_Stats T4SetStatus;

		private Assembly assembly;

		private Localization LocalizationClusterfuck;

		public static bool DoTheRoar => doTheRoar.Value;

		public void Awake()
		{
			//IL_131f: Unknown result type (might be due to invalid IL or missing references)
			//IL_1324: Unknown result type (might be due to invalid IL or missing references)
			//IL_132b: Unknown result type (might be due to invalid IL or missing references)
			//IL_133b: Expected O, but got Unknown
			//IL_133b: Unknown result type (might be due to invalid IL or missing references)
			//IL_1340: Unknown result type (might be due to invalid IL or missing references)
			//IL_1347: Unknown result type (might be due to invalid IL or missing references)
			//IL_1357: Expected O, but got Unknown
			//IL_1375: Unknown result type (might be due to invalid IL or missing references)
			//IL_137c: Expected O, but got Unknown
			assembly = Assembly.GetExecutingAssembly();
			T1Hash = StringExtensionMethods.GetStableHashCode("T1ChaosPlateArmor");
			T2Hash = StringExtensionMethods.GetStableHashCode("T2ChaosPlateArmor");
			T3Hash = StringExtensionMethods.GetStableHashCode("ChaosPlateArmorBody");
			T4Hash = StringExtensionMethods.GetStableHashCode("EliteChaosPlateArmor");
			T5Hash = StringExtensionMethods.GetStableHashCode("EliteChaosPlateArmorTzeentch");
			clankyPrefabNames.Add(StringExtensionMethods.GetStableHashCode("T0ChaosPlateArmor"));
			clankyPrefabNames.Add(T1Hash);
			clankyPrefabNames.Add(T2Hash);
			clankyPrefabNames.Add(T3Hash);
			clankyPrefabNames.Add(T4Hash);
			clankyPrefabNames.Add(StringExtensionMethods.GetStableHashCode("T0ChaosPlateLegs"));
			clankyPrefabNames.Add(StringExtensionMethods.GetStableHashCode("T1ChaosPlateLegs"));
			clankyPrefabNames.Add(StringExtensionMethods.GetStableHashCode("T2ChaosPlateLegs"));
			clankyPrefabNames.Add(StringExtensionMethods.GetStableHashCode("ChaosPlateLegs"));
			clankyPrefabNames.Add(StringExtensionMethods.GetStableHashCode("EliteChaosPlateLegs"));
			LoadTranslations();
			SetStatusEffects();
			Item item = new Item("chaosarmor", "T0ChaosPlateArmor");
			item.Name.English("Scrap Breastplate");
			item.Description.English("A plain breastplate cast from metal, warped and dented from what feels like a lifetime of use. It's barely holding together, yet something feels strangely familiar about the make, barren as it is now. A strange icon is clasped over it.");
			item.Crafting.Add(CraftingTable.Forge, 1);
			item.RequiredItems.Add("Bronze", 5);
			item.RequiredItems.Add("TrophyFrostTroll", 1);
			item.RequiredItems.Add("LeatherScraps", 9);
			item.RequiredUpgradeItems.Add("Bronze", 3);
			RegisterTranslations(item);
			Item item2 = new Item("chaosarmor", "T0ChaosPlateHelm");
			item2.Name.English("Scrap Helmet");
			item2.Description.English("A full helm cast from metal with a narrow visor. The wear of elements and war have taken a toll upon its integrity, but perhaps the familiarity of all-encasing metal is comfort enough for some.");
			item2.Crafting.Add(CraftingTable.Forge, 1);
			item2.RequiredItems.Add("Bronze", 6);
			item2.RequiredItems.Add("TrollHide", 3);
			item2.RequiredUpgradeItems.Add("Bronze", 4);
			RegisterTranslations(item2);
			Item item3 = new Item("chaosarmor", "T0ChaosPlateLegs");
			item3.Name.English("Scrap greaves");
			item3.Description.English("Unremarkable breeches and boots reinforced with well-worn metal. What little plating remains is battered almost beyond use, but its weight offers an anchor in unfamiliar lands.");
			item3.Crafting.Add(CraftingTable.Forge, 1);
			item3.RequiredItems.Add("Bronze", 4);
			item3.RequiredItems.Add("TrollHide", 2);
			item3.RequiredUpgradeItems.Add("Bronze", 2);
			RegisterTranslations(item3);
			Item item4 = new Item("chaosarmor", "T1ChaosPlateArmor");
			item4.Name.English("Half plate harness");
			item4.Description.English("A battered suit of heavy plate. The eight-spoked star clasped over the breastplate is dull and rusted. Reduces knockback from incoming attacks.");
			item4.Crafting.Add(CraftingTable.Forge, 1);
			item4.RequiredItems.Add("Iron", 25);
			item4.RequiredItems.Add("T0ChaosPlateArmor", 1);
			item4.RequiredItems.Add("LeatherScraps", 9);
			item4.RequiredUpgradeItems.Add("Iron", 5);
			item4.CraftAmount = 1;
			RegisterTranslations(item4);
			Item item5 = new Item("chaosarmor", "T1ChaosPlateHelm");
			item5.Name.English("Grave-iron plate helm");
			item5.Description.English("An iron plate helm, shrouded in funeral rags. Time will tell if the looming shadow of death comes for you or your foes.");
			item5.Crafting.Add(CraftingTable.Forge, 1);
			item5.RequiredItems.Add("Iron", 25);
			item5.RequiredItems.Add("T0ChaosPlateHelm", 1);
			item5.RequiredItems.Add("TrophyWraith", 1);
			item5.RequiredUpgradeItems.Add("Iron", 3);
			item5.CraftAmount = 1;
			RegisterTranslations(item5);
			Item item6 = new Item("chaosarmor", "T1ChaosPlateLegs");
			item6.Name.English("Battered plate leggings");
			item6.Description.English("Thick leather leggings reinforced with metal. The armor plates are heavy, anchoring the boots to the earth with stains and scars that cannot be erased.");
			item6.Crafting.Add(CraftingTable.Forge, 1);
			item6.RequiredItems.Add("Iron", 20);
			item6.RequiredItems.Add("LeatherScraps", 4);
			item6.RequiredItems.Add("T0ChaosPlateLegs", 1);
			item6.RequiredUpgradeItems.Add("Iron", 3);
			item6.RequiredUpgradeItems.Add("TrollHide", 5);
			item6.CraftAmount = 1;
			RegisterTranslations(item6);
			Item item7 = new Item("chaosarmor", "T2ChaosPlateArmor");
			item7.Name.English("Three quarters plate harness");
			item7.Description.English("A battered suit of heavy plate, cast from blackened silver. The eight-spoked star clasped over the breastplate catches the sun's rays with an uncanny, icy glint. Reduces knockback from incoming attacks.");
			item7.Crafting.Add(CraftingTable.Forge, 1);
			item7.RequiredItems.Add("Silver", 30);
			item7.RequiredItems.Add("Obsidian", 15);
			item7.RequiredItems.Add("FreezeGland", 5);
			item7.RequiredItems.Add("T1ChaosPlateArmor", 1);
			item7.RequiredUpgradeItems.Add("Silver", 10);
			item7.RequiredUpgradeItems.Add("FreezeGland", 5);
			item7.CraftAmount = 1;
			RegisterTranslations(item7);
			Item item8 = new Item("chaosarmor", "T2ChaosPlateHelm");
			item8.Name.English("Profaned plate helm");
			item8.Description.English("An icy plate helm, brazenly wreathed in tooth and cloth. Whether it is worn in ghastly tribute to the wolfmen or in bloody defiance is up to you.");
			item8.Crafting.Add(CraftingTable.Forge, 1);
			item8.RequiredItems.Add("Silver", 20);
			item8.RequiredItems.Add("TrophyCultist", 1);
			item8.RequiredItems.Add("FreezeGland", 5);
			item8.RequiredItems.Add("T1ChaosPlateHelm", 1);
			item8.RequiredUpgradeItems.Add("Silver", 5);
			item8.RequiredUpgradeItems.Add("FreezeGland", 5);
			item8.CraftAmount = 1;
			RegisterTranslations(item8);
			Item item9 = new Item("chaosarmor", "T2ChaosPlateLegs");
			item9.Name.English("Refurbished plate leggings");
			item9.Description.English("Thick leather leggings reinforced with blackened silver. The armor plates are heavy, anchoring the boots to the earth with stains and scars that cannot be erased.");
			item9.Crafting.Add(CraftingTable.Forge, 1);
			item9.RequiredItems.Add("Silver", 20);
			item9.RequiredItems.Add("FreezeGland", 5);
			item9.RequiredItems.Add("Obsidian", 15);
			item9.RequiredItems.Add("T1ChaosPlateLegs", 1);
			item9.RequiredUpgradeItems.Add("Silver", 5);
			item9.RequiredUpgradeItems.Add("FreezeGland", 5);
			item9.CraftAmount = 1;
			RegisterTranslations(item9);
			Item item10 = new Item("chaosarmor", "ChaosPlateArmorBody");
			item10.Name.English("Dormant plate harness");
			item10.Description.English("A full harness of heavy plate, too cumbersome to be carried by an ordinary body of mere flesh and bone. A sheath of rigid fibre is carefully woven beneath the plate- long-dead as it may be, twitches of vigor seem to pulse through at the tune of your own movements. Significantly reduces knockback from incoming attacks. Slightly reduces stagger taken.");
			item10.Crafting.Add(CraftingTable.Forge, 1);
			item10.RequiredItems.Add("BlackMetal", 30);
			item10.RequiredItems.Add("YmirRemains", 5);
			item10.RequiredItems.Add("TrophySGolem", 1);
			item10.RequiredItems.Add("T2ChaosPlateArmor", 1);
			item10.RequiredUpgradeItems.Add("BlackMetal", 10);
			item10.CraftAmount = 1;
			try
			{
				ItemDrop component = item10.Prefab.GetComponent<ItemDrop>();
				component.m_itemData.m_shared.m_setName = "ChaosT3Set";
				component.m_itemData.m_shared.m_setStatusEffect = (StatusEffect)(object)T3SetStatus;
				component.m_itemData.m_shared.m_setSize = 2;
			}
			catch (Exception ex)
			{
				Debug.LogError((object)ex);
			}
			RegisterTranslations(item10);
			Item item11 = new Item("chaosarmor", "ChaosPlateHelm");
			item11.Name.English("Dormant plate helm");
			item11.Description.English("A vicious-looking casque. The alloy plate that encloses it seems corroded and stained, even though the structure yet holds steady. An uncanny air of familiarity echoes within its confines.");
			item11.Crafting.Add(CraftingTable.Forge, 1);
			item11.RequiredItems.Add("BlackMetal", 15);
			item11.RequiredItems.Add("YmirRemains", 2);
			item11.RequiredItems.Add("TrophySerpent", 1);
			item11.RequiredItems.Add("T2ChaosPlateHelm", 1);
			item11.RequiredUpgradeItems.Add("BlackMetal", 5);
			item11.CraftAmount = 1;
			RegisterTranslations(item11);
			Item item12 = new Item("chaosarmor", "ChaosPlateLegs");
			item12.Name.English("Dormant plate greaves");
			item12.Description.English("Heavy greaves seemingly unfit for ordinary humans. Breeches of woven linen hide a grotesque array of rigid fibre underneath, perhaps the only reason you are able to move around in the metal boots that anchor you.");
			item12.Crafting.Add(CraftingTable.Forge, 1);
			item12.RequiredItems.Add("BlackMetal", 20);
			item12.RequiredItems.Add("LinenThread", 15);
			item12.RequiredItems.Add("YmirRemains", 5);
			item12.RequiredItems.Add("T2ChaosPlateLegs", 1);
			item12.RequiredUpgradeItems.Add("BlackMetal", 5);
			item12.CraftAmount = 1;
			RegisterTranslations(item12);
			try
			{
				ItemDrop component2 = item12.Prefab.GetComponent<ItemDrop>();
				component2.m_itemData.m_shared.m_setName = "ChaosT3Set";
				component2.m_itemData.m_shared.m_setStatusEffect = (StatusEffect)(object)T3SetStatus;
				component2.m_itemData.m_shared.m_setSize = 2;
			}
			catch (Exception ex2)
			{
				Debug.LogError((object)ex2);
			}
			Item item13 = new Item("chaosarmor", "EliteChaosPlateArmor");
			item13.Name.English("Animated plate harness");
			item13.Description.English("A full harness of deep-forged plate, far too cumbersome to be borne on human flesh and bone. A chained underlay of long-dead muscle courses with uncanny vigor, reanimated and bound to your own movements. All but negates knockback from incoming attacks. Slightly reduces stagger taken.");
			item13.Crafting.Add(CraftingTable.BlackForge, 1);
			item13.RequiredItems.Add("BlackMetal", 20);
			item13.RequiredItems.Add("BlackCore", 1);
			item13.RequiredItems.Add("Eitr", 9);
			item13.RequiredItems.Add("ChaosPlateArmorBody", 1);
			item13.RequiredUpgradeItems.Add("BlackMetal", 10);
			item13.CraftAmount = 1;
			RegisterTranslations(item13);
			try
			{
				ItemDrop component3 = item13.Prefab.GetComponent<ItemDrop>();
				component3.m_itemData.m_shared.m_setName = "ChaosT4Set";
				component3.m_itemData.m_shared.m_setStatusEffect = (StatusEffect)(object)T4SetStatus;
				component3.m_itemData.m_shared.m_setSize = 2;
			}
			catch (Exception ex3)
			{
				Debug.LogError((object)ex3);
			}
			Item item14 = new Item("chaosarmor", "EliteChaosPlateHelm");
			item14.Name.English("Abyssal plate helm");
			item14.Description.English("Shrouded in darkness as your plated skin may be, the horned proof of your bloody victories will ensure your place in the eyes of the gods.");
			item14.Crafting.Add(CraftingTable.BlackForge, 1);
			item14.RequiredItems.Add("BlackMetal", 15);
			item14.RequiredItems.Add("TrophySeekerBrute", 1);
			item14.RequiredItems.Add("Eitr", 3);
			item14.RequiredItems.Add("ChaosPlateHelm", 1);
			item14.RequiredUpgradeItems.Add("BlackMetal", 5);
			item14.RequiredUpgradeItems.Add("TrophySeekerBrute", 1);
			item14.CraftAmount = 1;
			RegisterTranslations(item14);
			Item item15 = new Item("chaosarmor", "ChaosPlateHelmAlt");
			item15.Name.English("Tenebrous plate helm");
			item15.Description.English("Dragged out from the murky shadows, visions of a distant and dark millennium glimmer like embers in the helm's eyeslits. What has been seen cannot be unseen.");
			item15.Crafting.Add(CraftingTable.BlackForge, 1);
			item15.RequiredItems.Add("Eitr", 9);
			item15.RequiredItems.Add("YagluthDrop", 1);
			item15.RequiredItems.Add("ChaosPlateHelm", 1);
			item15.RequiredUpgradeItems.Add("BlackMetal", 5);
			item15.CraftAmount = 1;
			RegisterTranslations(item15);
			Item item16 = new Item("chaosarmor", "EliteChaosPlateLegs");
			item16.Name.English("Animated plate greaves");
			item16.Description.English("Fully plated leggings. Chain hosen covers the gaps left by impassive metal, shrouding the twitching muscle beneath from prying eyes.");
			item16.Crafting.Add(CraftingTable.BlackForge, 1);
			item16.RequiredItems.Add("BlackMetal", 20);
			item16.RequiredItems.Add("Eitr", 9);
			item16.RequiredItems.Add("ChaosPlateLegs", 1);
			item16.RequiredUpgradeItems.Add("BlackMetal", 10);
			item16.CraftAmount = 1;
			RegisterTranslations(item16);
			try
			{
				ItemDrop component4 = item16.Prefab.GetComponent<ItemDrop>();
				component4.m_itemData.m_shared.m_setName = "ChaosT4Set";
				component4.m_itemData.m_shared.m_setStatusEffect = (StatusEffect)(object)T4SetStatus;
				component4.m_itemData.m_shared.m_setSize = 2;
			}
			catch (Exception ex4)
			{
				Debug.LogError((object)ex4);
			}
			Item item17 = new Item("chaosarmor", "EliteChaosPlateArmorTzeentch");
			item17.Name.English("Arcane plate harness");
			item17.Description.English("Reanimated plate harness, further enhanced by dynamos and armatures nearly beyond comprehension. Reactive shielding and additional Eitr regeneration triggers upon receiving sufficient damage in a single strike.");
			item17.Crafting.Add(CraftingTable.BlackForge, 1);
			item17.RequiredItems.Add("Copper", 20);
			item17.RequiredItems.Add("TrophySeekerQueen", 1);
			item17.RequiredItems.Add("QueenDrop", 3);
			item17.RequiredItems.Add("SerpentScale", 28);
			item17.RequiredItems.Add("EliteChaosPlateArmor", 1);
			item17.RequiredUpgradeItems.Add("QueenDrop", 1);
			item17.CraftAmount = 1;
			RegisterTranslations(item17);
			try
			{
				ItemDrop component5 = item17.Prefab.GetComponent<ItemDrop>();
				component5.m_itemData.m_shared.m_setName = "ChaosT5Set";
				component5.m_itemData.m_shared.m_setStatusEffect = (StatusEffect)(object)T4SetStatus;
				component5.m_itemData.m_shared.m_setSize = 2;
			}
			catch (Exception ex5)
			{
				Debug.LogError((object)ex5);
			}
			Item item18 = new Item("chaosarmor", "ChaosPlateHelmAltTzeentch");
			item18.Name.English("Arcane breather helm");
			item18.Description.English("Dragged out from the murky shadows, visions of a distant and dark millennium glimmer like embers in the helm's eyeslits. What has been seen cannot be unseen.");
			item18.Crafting.Add(CraftingTable.BlackForge, 1);
			item18.RequiredItems.Add("Eitr", 9);
			item18.RequiredItems.Add("QueenDrop", 3);
			item18.RequiredItems.Add("ChaosPlateHelmAlt", 1);
			item18.RequiredUpgradeItems.Add("QueenDrop", 1);
			item18.CraftAmount = 1;
			RegisterTranslations(item18);
			Item item19 = new Item("chaosarmor", "EliteChaosPlateHelmTzeentch");
			item19.Name.English("Arcane plate helm");
			item19.Description.English("Shrouded in darkness as your plated skin may be, the horned proof of your bloody victories will ensure your place in the eyes of the gods.");
			item19.Crafting.Add(CraftingTable.BlackForge, 1);
			item19.RequiredItems.Add("TrophySeekerQueen", 1);
			item19.RequiredItems.Add("QueenDrop", 3);
			item19.RequiredItems.Add("EliteChaosPlateHelm", 1);
			item19.RequiredUpgradeItems.Add("QueenDrop", 1);
			item19.RequiredUpgradeItems.Add("TrophySeekerBrute", 1);
			item19.CraftAmount = 1;
			RegisterTranslations(item19);
			Item item20 = new Item("chaosarmor", "EliteChaosPlateHelmTzeentchBoss");
			item20.Name.English("Arcane channeler helm");
			item20.Description.English("Tingly.");
			item20.Crafting.Add(CraftingTable.BlackForge, 1);
			item20.RequiredItems.Add("TrophyCultist", 1);
			item20.RequiredItems.Add("EliteChaosPlateHelmTzeentch", 1);
			item20.RequiredUpgradeItems.Add("QueenDrop", 1);
			item20.CraftAmount = 1;
			RegisterTranslations(item20);
			Item item21 = new Item("chaosarmor", "EliteChaosPlateLegsTzeentch");
			item21.Name.English("Arcane plate greaves");
			item21.Description.English("Reanimated plate leggings, housing a complex array of arcane circuits.");
			item21.Crafting.Add(CraftingTable.BlackForge, 1);
			item21.RequiredItems.Add("Copper", 20);
			item21.RequiredItems.Add("QueenDrop", 3);
			item21.RequiredItems.Add("EliteChaosPlateLegs", 1);
			item21.RequiredUpgradeItems.Add("QueenDrop", 1);
			item21.CraftAmount = 1;
			RegisterTranslations(item21);
			try
			{
				ItemDrop component6 = item21.Prefab.GetComponent<ItemDrop>();
				component6.m_itemData.m_shared.m_setName = "ChaosT5Set";
				component6.m_itemData.m_shared.m_setStatusEffect = (StatusEffect)(object)T4SetStatus;
				component6.m_itemData.m_shared.m_setSize = 2;
			}
			catch (Exception ex6)
			{
				Debug.LogError((object)ex6);
			}
			AssetBundle value = null;
			PrefabManager.BundleId bundleId = default(PrefabManager.BundleId);
			bundleId.folderName = "assets";
			bundleId.assetBundleFileName = "chaosarmor";
			PrefabManager.BundleId key = bundleId;
			if (!PrefabManager.bundleCache.TryGetValue(key, out value))
			{
				AssetBundle[] source = Resources.FindObjectsOfTypeAll<AssetBundle>();
				Debug.LogWarning((object)$"unable to find assetbundle in ItemManager cache, attempting manual retrieval: {source.Count()} assetbundles found in resources");
				value = ((IEnumerable<AssetBundle>)source).FirstOrDefault((Func<AssetBundle, bool>)((AssetBundle a) => ((Object)a).name == "chaosarmor")) ?? AssetBundle.LoadFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ".assets.chaosarmor"));
			}
			if ((Object)(object)value != (Object)null)
			{
				Clanka.prefabStep = value.LoadAsset<GameObject>("sfx_reepus_footstepClankChaos");
				Clanka.prefabRun = value.LoadAsset<GameObject>("sfx_reepus_footstepClank2Chaos");
				Clanka.prefabDodge = value.LoadAsset<GameObject>("sfx_reepus_dodgeChaos");
				Clanka.prefabLand = value.LoadAsset<GameObject>("sfx_reepus_landChaos");
				Clanka.prefabJump = value.LoadAsset<GameObject>("sfx_reepus_jumpClankChaos");
				Clanka.prefabBootStep = value.LoadAsset<GameObject>("sfx_reepus_footstepBootWalkChaos");
				Clanka.prefabBootRun = value.LoadAsset<GameObject>("sfx_reepus_footstepBootRunChaos");
				Clanka.jumpData = new EffectData
				{
					m_enabled = true,
					m_prefab = Clanka.prefabJump
				};
				Clanka.dodgeData = new EffectData
				{
					m_enabled = true,
					m_prefab = Clanka.prefabDodge
				};
			}
			else
			{
				Debug.LogWarning((object)"Failed to load clanking");
			}
			ConfigFile val = new ConfigFile(Path.Combine(Paths.ConfigPath, "ReepusDelmeepus.ChaosArmorClank.cfg"), true);
			doTheRoar = val.Bind<bool>("General", "do the clank", true, "Make player go clank-clank if chaos armor is equipped. Not synced with server.");
			RegisterBlacksmithTools();
			Harmony.CreateAndPatchAll(assembly, (string)null);
		}

		private void SetStatusEffects()
		{
			try
			{
				T3SetStatus = ScriptableObject.CreateInstance<SE_Stats>();
				((Object)T3SetStatus).name = "ChaosT3SetEffect";
				T3SetStatus.m_staminaRegenMultiplier = 1.05f;
				T3SetStatus.m_addMaxCarryWeight = 16f;
				T4SetStatus = ScriptableObject.CreateInstance<SE_Stats>();
				((Object)T4SetStatus).name = "ChaosT4SetEffect";
				T4SetStatus.m_staminaRegenMultiplier = 1.15f;
				T4SetStatus.m_addMaxCarryWeight = 32f;
			}
			catch (Exception ex)
			{
				Debug.LogError((object)ex);
			}
		}

		private void LoadTranslations()
		{
			try
			{
				string directoryName = Path.GetDirectoryName(assembly.Location);
				string path = Path.Combine(directoryName, "Localization.yml");
				string text = "am I ever going to fix this, probably not";
				text = File.ReadAllText(path);
				StringReader input = new StringReader(text);
				Deserializer deserializer = new Deserializer();
				LocalizationClusterfuck = deserializer.Deserialize<Localization>(input);
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("Localization file was not loaded cuz mod author is a lazy ass who still won't change the hardcoded directory: " + ex.Message));
			}
		}

		private void RegisterTranslations(Item item)
		{
			if (LocalizationClusterfuck == null)
			{
				return;
			}
			foreach (string key in LocalizationClusterfuck.Localizations.Keys)
			{
				try
				{
					item.Name.addForLang(key, LocalizationClusterfuck.Localizations[key][((Object)item.Prefab).name]["Name"]);
					item.Description.addForLang(key, LocalizationClusterfuck.Localizations[key][((Object)item.Prefab).name]["Description"]);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)("fucked something up registering translations for " + key + " on " + ((Object)item.Prefab).name + ": " + ex.Message));
				}
			}
		}

		private void RegisterBlacksmithTools()
		{
			try
			{
				BodypartSystem.bodypartSettings.Add("T0ChaosPlateArmor", new List<bodyPart>
				{
					(bodyPart)1,
					(bodyPart)2,
					(bodyPart)3,
					(bodyPart)4,
					(bodyPart)5,
					(bodyPart)6,
					(bodyPart)7
				});
				BodypartSystem.bodypartSettings.Add("T1ChaosPlateArmor", new List<bodyPart>
				{
					(bodyPart)1,
					(bodyPart)2,
					(bodyPart)3,
					(bodyPart)4,
					(bodyPart)5,
					(bodyPart)6,
					(bodyPart)7
				});
				BodypartSystem.bodypartSettings.Add("T2ChaosPlateArmor", new List<bodyPart>
				{
					(bodyPart)1,
					(bodyPart)2,
					(bodyPart)3,
					(bodyPart)4,
					(bodyPart)5,
					(bodyPart)6,
					(bodyPart)7
				});
				BodypartSystem.bodypartSettings.Add("ChaosPlateArmorBody", new List<bodyPart>
				{
					(bodyPart)1,
					(bodyPart)2,
					(bodyPart)3,
					(bodyPart)4,
					(bodyPart)5,
					(bodyPart)6,
					(bodyPart)7
				});
				BodypartSystem.bodypartSettings.Add("EliteChaosPlateArmor", new List<bodyPart>
				{
					(bodyPart)1,
					(bodyPart)2,
					(bodyPart)3,
					(bodyPart)4,
					(bodyPart)5,
					(bodyPart)6,
					(bodyPart)7
				});
				BodypartSystem.bodypartSettings.Add("EliteChaosPlateArmorTzeentch", new List<bodyPart>
				{
					(bodyPart)1,
					(bodyPart)2,
					(bodyPart)3,
					(bodyPart)4,
					(bodyPart)5,
					(bodyPart)6,
					(bodyPart)7
				});
				BodypartSystem.bodypartSettings.Add("T0ChaosPlateLegs", new List<bodyPart>
				{
					(bodyPart)11,
					(bodyPart)8,
					(bodyPart)12,
					(bodyPart)13,
					(bodyPart)9,
					(bodyPart)10
				});
				BodypartSystem.bodypartSettings.Add("T1ChaosPlateLegs", new List<bodyPart>
				{
					(bodyPart)11,
					(bodyPart)8,
					(bodyPart)12,
					(bodyPart)13,
					(bodyPart)9,
					(bodyPart)10
				});
				BodypartSystem.bodypartSettings.Add("T2ChaosPlateLegs", new List<bodyPart>
				{
					(bodyPart)11,
					(bodyPart)8,
					(bodyPart)12,
					(bodyPart)13,
					(bodyPart)9,
					(bodyPart)10
				});
				BodypartSystem.bodypartSettings.Add("ChaosPlateLegs", new List<bodyPart>
				{
					(bodyPart)11,
					(bodyPart)8,
					(bodyPart)12,
					(bodyPart)13,
					(bodyPart)9,
					(bodyPart)10
				});
				BodypartSystem.bodypartSettings.Add("EliteChaosPlateLegs", new List<bodyPart>
				{
					(bodyPart)11,
					(bodyPart)8,
					(bodyPart)12,
					(bodyPart)13,
					(bodyPart)9,
					(bodyPart)10
				});
				BodypartSystem.bodypartSettings.Add("EliteChaosPlateLegsTzeentch", new List<bodyPart>
				{
					(bodyPart)11,
					(bodyPart)8,
					(bodyPart)12,
					(bodyPart)13,
					(bodyPart)9,
					(bodyPart)10
				});
			}
			catch (Exception)
			{
				Debug.LogWarning((object)"Blacksmith's Tools failed to register but Chaos Armor should still be functional; keep an eye out for updates to Blacksmith's Tools");
			}
		}
	}
	internal class Localization
	{
		public Dictionary<string, Dictionary<string, Dictionary<string, string>>> Localizations;
	}
	public class Clanka : MonoBehaviour
	{
		public static GameObject prefabStep;

		public static GameObject prefabRun;

		public static GameObject prefabJump;

		public static GameObject prefabDodge;

		public static GameObject prefabLand;

		public static GameObject prefabBootStep;

		public static GameObject prefabBootRun;

		public static EffectData jumpData;

		public static EffectData dodgeData;

		private Player wearer;

		public void Start()
		{
			if (ReepusDeepusDelmeepusChaosArmor.DoTheRoar && !((Object)(object)prefabStep == (Object)null))
			{
				Transform root = ((Component)this).transform.root;
				object obj;
				if (root == null)
				{
					obj = null;
				}
				else
				{
					GameObject gameObject = ((Component)root).gameObject;
					obj = ((gameObject != null) ? gameObject.GetComponent<Player>() : null);
				}
				wearer = (Player)obj;
				if ((Object)(object)wearer != (Object)null)
				{
					MakePlayerClanky(wearer);
				}
			}
		}

		public void OnDisable()
		{
			if (ReepusDeepusDelmeepusChaosArmor.DoTheRoar && !((Object)(object)prefabStep == (Object)null))
			{
				if ((Object)(object)wearer != (Object)null && !ReepusDeepusDelmeepusChaosArmor.clankyPrefabNames.Contains(((Humanoid)wearer).m_visEquipment?.m_currentChestItemHash ?? (-1)) && !ReepusDeepusDelmeepusChaosArmor.clankyPrefabNames.Contains(((Humanoid)wearer).m_visEquipment?.m_currentLegItemHash ?? (-1)))
				{
					UnclankPlayer(wearer);
				}
				wearer = null;
			}
		}

		private static void MakePlayerClanky(Player player)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Invalid comparison between Unknown and I4
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Invalid comparison between Unknown and I4
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Invalid comparison between Unknown and I4
			FootStep component = ((Component)player).GetComponent<FootStep>();
			if ((Object)(object)component == (Object)null || ((Character)player).m_jumpEffects == null || player.m_dodgeEffects == null)
			{
				return;
			}
			foreach (StepEffect effect in component.m_effects)
			{
				HashSet<GameObject> hashSet = new HashSet<GameObject>(effect.m_effectPrefabs);
				bool flag = false;
				MotionType motionType = effect.m_motionType;
				MotionType val = motionType;
				if (((int)val == 2 || (int)val == 8) ? (hashSet.Add(prefabRun) | hashSet.Add(prefabBootRun)) : (((int)val != 32) ? (hashSet.Add(prefabStep) | hashSet.Add(prefabBootStep)) : (hashSet.Add(prefabLand) | hashSet.Add(prefabBootRun))))
				{
					effect.m_effectPrefabs = hashSet.ToArray();
				}
			}
			HashSet<EffectData> hashSet2 = new HashSet<EffectData>(((Character)player).m_jumpEffects.m_effectPrefabs);
			bool flag2 = hashSet2.Add(jumpData);
			HashSet<EffectData> hashSet3 = new HashSet<EffectData>(player.m_dodgeEffects.m_effectPrefabs);
			bool flag3 = hashSet3.Add(dodgeData);
			if (flag2)
			{
				((Character)player).m_jumpEffects.m_effectPrefabs = hashSet2.ToArray();
			}
			if (flag3)
			{
				player.m_dodgeEffects.m_effectPrefabs = hashSet3.ToArray();
			}
		}

		private static void UnclankPlayer(Player player)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Invalid comparison between Unknown and I4
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Invalid comparison between Unknown and I4
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Invalid comparison between Unknown and I4
			FootStep component = ((Component)player).GetComponent<FootStep>();
			if ((Object)(object)component == (Object)null || ((Character)player).m_jumpEffects == null || player.m_dodgeEffects == null)
			{
				return;
			}
			foreach (StepEffect effect in component.m_effects)
			{
				HashSet<GameObject> hashSet = new HashSet<GameObject>(effect.m_effectPrefabs);
				bool flag = false;
				MotionType motionType = effect.m_motionType;
				MotionType val = motionType;
				if (((int)val == 2 || (int)val == 8) ? (hashSet.Remove(prefabRun) | hashSet.Remove(prefabBootRun)) : (((int)val != 32) ? (hashSet.Remove(prefabStep) | hashSet.Remove(prefabBootStep)) : (hashSet.Remove(prefabLand) | hashSet.Remove(prefabBootRun))))
				{
					effect.m_effectPrefabs = hashSet.ToArray();
				}
			}
			HashSet<EffectData> hashSet2 = new HashSet<EffectData>(((Character)player).m_jumpEffects.m_effectPrefabs);
			bool flag2 = hashSet2.Remove(jumpData);
			HashSet<EffectData> hashSet3 = new HashSet<EffectData>(player.m_dodgeEffects.m_effectPrefabs);
			bool flag3 = hashSet3.Remove(dodgeData);
			if (flag2)
			{
				((Character)player).m_jumpEffects.m_effectPrefabs = hashSet2.ToArray();
			}
			if (flag3)
			{
				player.m_dodgeEffects.m_effectPrefabs = hashSet3.ToArray();
			}
		}
	}
	public class EitrDynamo : MonoBehaviour
	{
		private Humanoid wearer;

		private const string shieldName = "TzeentchReactiveShield";

		private int shieldHash;

		public void Start()
		{
			Transform root = ((Component)this).transform.root;
			object obj;
			if (root == null)
			{
				obj = null;
			}
			else
			{
				GameObject gameObject = ((Component)root).gameObject;
				obj = ((gameObject != null) ? gameObject.GetComponent<Player>() : null);
			}
			wearer = (Humanoid)obj;
			if ((Object)(object)wearer != (Object)null)
			{
				shieldHash = StringExtensionMethods.GetStableHashCode("TzeentchReactiveShield");
				Humanoid obj2 = wearer;
				((Character)obj2).m_onDamaged = (Action<float, Character>)Delegate.Combine(((Character)obj2).m_onDamaged, new Action<float, Character>(OnDamaged));
			}
		}

		public void OnDisable()
		{
			if ((Object)(object)wearer != (Object)null)
			{
				Humanoid obj = wearer;
				((Character)obj).m_onDamaged = (Action<float, Character>)Delegate.Remove(((Character)obj).m_onDamaged, new Action<float, Character>(OnDamaged));
			}
			wearer = null;
		}

		public void OnDamaged(float dmg, Character idfkLol)
		{
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			bool flag = ((Character)wearer).HaveEitr(0f);
			float maxEitr = ((Character)wearer).GetMaxEitr();
			float maxHealth = ((Character)wearer).GetMaxHealth();
			float num = Math.Max(25f, maxHealth / 4f);
			float num2 = (flag ? (((Character)wearer).GetEitrPercentage() * ((Character)wearer).GetMaxEitr()) : 0f);
			if (maxEitr > 0f)
			{
				if (dmg > Math.Min(50f, maxHealth / 3f))
				{
					((Character)wearer).AddEitr(70f);
				}
				else if (dmg > 30f)
				{
					((Character)wearer).AddEitr(40f);
				}
				else if (dmg < 20f && !((Character)wearer).m_blocking)
				{
					((Character)wearer).AddEitr(3f);
				}
				else
				{
					((Character)wearer).AddEitr(25f);
				}
			}
			bool flag2 = ((Character)wearer).GetHealth() <= num;
			bool flag3 = dmg < 10f;
			SEMan sEMan = ((Character)wearer).GetSEMan();
			if (flag3 && (!flag2 || sEMan.HaveStatusEffect(shieldHash)))
			{
				return;
			}
			SE_Shield val = ScriptableObject.CreateInstance<SE_Shield>();
			((Object)val).name = "TzeentchReactiveShield";
			((StatusEffect)val).m_nameHash = shieldHash;
			((StatusEffect)val).m_ttl = ((flag3 && flag2) ? 5f : (20f + 0.35f * num2));
			val.m_levelUpSkillOnBreak = (SkillType)10;
			val.m_levelUpSkillFactor = 0.5f;
			val.m_absorbDamagePerSkillLevel = 1f;
			val.m_absorbDamage = ((flag3 && flag2) ? 5f : (0.5f * num2));
			if ((Object)(object)ReepusDeepusDelmeepusChaosArmor.staffShield != (Object)null)
			{
				((StatusEffect)val).m_startEffects.m_effectPrefabs = ((StatusEffect)ReepusDeepusDelmeepusChaosArmor.staffShield).m_startEffects.m_effectPrefabs.Concat(ReepusDeepusDelmeepusChaosArmor.staffShield.m_hitEffects.m_effectPrefabs).ToArray();
				val.m_breakEffects = ReepusDeepusDelmeepusChaosArmor.staffShield.m_breakEffects;
				val.m_hitEffects = ReepusDeepusDelmeepusChaosArmor.staffShield.m_hitEffects;
				((StatusEffect)val).m_stopEffects = ReepusDeepusDelmeepusChaosArmor.staffShield.m_breakEffects;
			}
			float num3 = Math.Min(75f, maxHealth / 2f);
			float num4 = Math.Min(25f, maxHealth / 3f);
			if (dmg >= num3)
			{
				val.m_absorbDamage += 120f;
			}
			else
			{
				float num5 = dmg;
				if (num5 < num3 && num5 >= num4)
				{
					val.m_absorbDamage += 70f;
				}
				else
				{
					float num6 = dmg;
					if (num6 < num4 && num6 >= 10f)
					{
						val.m_absorbDamage += 30f;
					}
				}
			}
			val.m_absorbDamage = Math.Min(val.m_absorbDamage, 500f);
			((StatusEffect)val).m_ttl = Math.Min(((StatusEffect)val).m_ttl, 100f);
			sEMan.AddStatusEffect((StatusEffect)(object)val, false, 0, 0f);
		}
	}
	public static class PoiseBois
	{
		[HarmonyPatch(typeof(Character), "RPC_Damage")]
		public static class ReduceDamageTaken
		{
			[UsedImplicitly]
			private static void Prefix(Character __instance, HitData hit)
			{
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val != null && (Object)(object)hit.GetAttacker() != (Object)(object)__instance)
				{
					if (((Humanoid)val).m_visEquipment.m_currentChestItemHash == ReepusDeepusDelmeepusChaosArmor.T4Hash || ((Humanoid)val).m_visEquipment.m_currentChestItemHash == ReepusDeepusDelmeepusChaosArmor.T5Hash)
					{
						hit.m_pushForce *= 0.15f;
						hit.m_staggerMultiplier *= 0.75f;
					}
					else if (((Humanoid)val).m_visEquipment.m_currentChestItemHash == ReepusDeepusDelmeepusChaosArmor.T3Hash)
					{
						hit.m_pushForce *= 0.4f;
						hit.m_staggerMultiplier *= 0.85f;
					}
					else if (((Humanoid)val).m_visEquipment.m_currentChestItemHash == ReepusDeepusDelmeepusChaosArmor.T2Hash || ((Humanoid)val).m_visEquipment.m_currentChestItemHash == ReepusDeepusDelmeepusChaosArmor.T1Hash)
					{
						hit.m_pushForce *= 0.65f;
					}
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<72963668-473b-473d-9d74-30fb47ec35c4>Embedded]
	internal sealed class <72963668-473b-473d-9d74-30fb47ec35c4>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<72963668-473b-473d-9d74-30fb47ec35c4>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <b98f41fe-cc42-4143-abec-caa2245befde>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <b98f41fe-cc42-4143-abec-caa2245befde>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <b98f41fe-cc42-4143-abec-caa2245befde>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<72963668-473b-473d-9d74-30fb47ec35c4>Embedded]
	[CompilerGenerated]
	internal sealed class <0d49a340-51cb-4233-91da-521dfe94608c>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <0d49a340-51cb-4233-91da-521dfe94608c>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace ItemManager
{
	[PublicAPI]
	internal enum CraftingTable
	{
		Disabled,
		Inventory,
		[InternalName("piece_workbench")]
		Workbench,
		[InternalName("piece_cauldron")]
		Cauldron,
		[InternalName("forge")]
		Forge,
		[InternalName("piece_artisanstation")]
		ArtisanTable,
		[InternalName("piece_stonecutter")]
		StoneCutter,
		[InternalName("piece_magetable")]
		MageTable,
		[InternalName("blackforge")]
		BlackForge,
		Custom
	}
	[PublicAPI]
	internal enum ConversionPiece
	{
		Disabled,
		[InternalName("smelter")]
		Smelter,
		[InternalName("charcoal_kiln")]
		CharcoalKiln,
		[InternalName("blastfurnace")]
		BlastFurnace,
		[InternalName("windmill")]
		Windmill,
		[InternalName("piece_spinningwheel")]
		SpinningWheel,
		[InternalName("eitrrefinery")]
		EitrRefinery,
		Custom
	}
	[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(1)]
	[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
	internal class InternalName : Attribute
	{
		public readonly string internalName;

		public InternalName(string internalName)
		{
			this.internalName = internalName;
		}
	}
	[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
	[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(1)]
	[PublicAPI]
	internal class RequiredResourceList
	{
		public readonly List<Requirement> Requirements = new List<Requirement>();

		public bool Free = false;

		public void Add(string itemName, int amount)
		{
			Requirements.Add(new Requirement
			{
				itemName = itemName,
				amount = amount
			});
		}

		public void Add(string itemName, ConfigEntry<int> amountConfig)
		{
			Requirements.Add(new Requirement
			{
				itemName = itemName,
				amountConfig = amountConfig
			});
		}
	}
	[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
	[PublicAPI]
	[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(1)]
	internal class CraftingStationList
	{
		public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>();

		public void Add(CraftingTable table, int level)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = table,
				level = level
			});
		}

		public void Add(string customTable, int level)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = CraftingTable.Custom,
				level = level,
				custom = customTable
			});
		}
	}
	[PublicAPI]
	[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
	[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(1)]
	internal class ItemRecipe
	{
		public readonly RequiredResourceList RequiredItems = new RequiredResourceList();

		public readonly RequiredResourceList RequiredUpgradeItems = new RequiredResourceList();

		public readonly CraftingStationList Crafting = new CraftingStationList();

		public int CraftAmount = 1;

		public bool RequireOnlyOneIngredient = false;

		public float QualityResultAmountMultiplier = 1f;

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		public ConfigEntryBase RecipeIsActive = null;
	}
	internal struct Requirement
	{
		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(1)]
		public string itemName;

		public int amount;

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		public ConfigEntry<int> amountConfig;
	}
	internal struct CraftingStationConfig
	{
		public CraftingTable Table;

		public int level;

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		public string custom;
	}
	[Flags]
	internal enum Configurability
	{
		Disabled = 0,
		Recipe = 1,
		Stats = 2,
		Drop = 4,
		Full = 7
	}
	[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
	[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(1)]
	[PublicAPI]
	internal class DropTargets
	{
		public readonly List<DropTarget> Drops = new List<DropTarget>();

		public void Add(string creatureName, float chance, int min = 1, int? max = null, bool levelMultiplier = true)
		{
			Drops.Add(new DropTarget
			{
				creature = creatureName,
				chance = chance,
				min = min,
				max = (max ?? min),
				levelMultiplier = levelMultiplier
			});
		}
	}
	internal struct DropTarget
	{
		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(1)]
		public string creature;

		public int min;

		public int max;

		public float chance;

		public bool levelMultiplier;
	}
	internal enum Toggle
	{
		On = 1,
		Off = 0
	}
	[PublicAPI]
	[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
	[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(1)]
	internal class Item
	{
		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
		private class ItemConfig
		{
			[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(new byte[] { 2, 1 })]
			public ConfigEntry<string> craft;

			[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(new byte[] { 2, 1 })]
			public ConfigEntry<string> upgrade;

			public ConfigEntry<CraftingTable> table = null;

			public ConfigEntry<int> tableLevel = null;

			public ConfigEntry<string> customTable = null;

			[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
			public ConfigEntry<int> maximumTableLevel;

			public ConfigEntry<Toggle> requireOneIngredient = null;

			public ConfigEntry<float> qualityResultAmountMultiplier = null;
		}

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
		[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(2)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			public string Category;

			[UsedImplicitly]
			[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(new byte[] { 2, 1 })]
			public Action<ConfigEntryBase> CustomDrawer;

			public Func<bool> browsability;
		}

		[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)]
		[PublicAPI]
		public enum DamageModifier
		{
			Normal,
			Resistant,
			Weak,
			Immune,
			Ignore,
			VeryResistant,
			VeryWeak,
			None
		}

		[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)]
		private delegate void setDmgFunc(ref DamageTypes dmg, float value);

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
		private class SerializedRequirements
		{
			public readonly List<Requirement> Reqs;

			public SerializedRequirements(List<Requirement> reqs)
			{
				Reqs = reqs;
			}

			public SerializedRequirements(string reqs)
			{
				Reqs = reqs.Split(new char[1] { ',' }).Select([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (string r) =>
				{
					string[] array = r.Split(new char[1] { ':' });
					Requirement result = default(Requirement);
					result.itemName = array[0];
					result.amount = ((array.Length <= 1 || !int.TryParse(array[1], out var result2)) ? 1 : result2);
					return result;
				}).ToList();
			}

			public override string ToString()
			{
				return string.Join(",", Reqs.Select([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}"));
			}

			[return: <b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
			public static ItemDrop fetchByName(ObjectDB objectDB, string name)
			{
				GameObject itemPrefab = objectDB.GetItemPrefab(name);
				ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val == (Object)null)
				{
					Debug.LogWarning((object)("The required item '" + name + "' does not exist."));
				}
				return val;
			}

			public static Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade)
			{
				//IL_00db: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f2: Expected O, but got Unknown
				//IL_00f7: Expected O, but got Unknown
				Dictionary<string, Requirement> dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func<Requirement, string>)([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (Requirement r) => r.itemName), (Func<Requirement, Requirement>)([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (Requirement r) =>
				{
					//IL_000e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0013: Unknown result type (might be due to invalid IL or missing references)
					//IL_0030: 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)
					ItemDrop val4 = ResItem(r);
					return (val4 == null) ? ((Requirement)null) : new Requirement
					{
						m_amount = (r.amountConfig?.Value ?? r.amount),
						m_resItem = val4,
						m_amountPerLevel = 0
					};
				}));
				foreach (Requirement item in upgrade.Reqs.Where((Requirement r) => r.itemName != ""))
				{
					if (!dictionary.TryGetValue(item.itemName, out var value) || value == null)
					{
						ItemDrop val = ResItem(item);
						if (val != null)
						{
							string itemName = item.itemName;
							Requirement val2 = new Requirement
							{
								m_resItem = val,
								m_amount = 0
							};
							Requirement val3 = val2;
							dictionary[itemName] = val2;
							value = val3;
						}
					}
					if (value != null)
					{
						value.m_amountPerLevel = item.amountConfig?.Value ?? item.amount;
					}
				}
				return dictionary.Values.Where([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (Requirement v) => v != null).ToArray();
				[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(2)]
				ItemDrop ResItem(Requirement r)
				{
					return fetchByName(objectDB, r.itemName);
				}
			}
		}

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(0)]
		private class SerializedDrop
		{
			public readonly List<DropTarget> Drops;

			public SerializedDrop(List<DropTarget> drops)
			{
				Drops = drops;
			}

			public SerializedDrop(string drops)
			{
				Drops = ((drops == "") ? ((IEnumerable<string>)Array.Empty<string>()) : ((IEnumerable<string>)drops.Split(new char[1] { ',' }))).Select([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (string r) =>
				{
					string[] array = r.Split(new char[1] { ':' });
					if (array.Length <= 2 || !int.TryParse(array[2], out var result))
					{
						result = 1;
					}
					if (array.Length <= 3 || !int.TryParse(array[3], out var result2))
					{
						result2 = result;
					}
					bool levelMultiplier = array.Length <= 4 || array[4] != "0";
					DropTarget result3 = default(DropTarget);
					result3.creature = array[0];
					result3.chance = ((array.Length > 1 && float.TryParse(array[1], out var result4)) ? result4 : 1f);
					result3.min = result;
					result3.max = result2;
					result3.levelMultiplier = levelMultiplier;
					return result3;
				}).ToList();
			}

			public override string ToString()
			{
				return string.Join(",", Drops.Select([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (DropTarget r) => $"{r.creature}:{r.chance.ToString(CultureInfo.InvariantCulture)}:{r.min}:" + ((r.min == r.max) ? "" : $"{r.max}") + (r.levelMultiplier ? "" : ":0")));
			}

			[return: <b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
			private static Character fetchByName(ZNetScene netScene, string name)
			{
				GameObject prefab = netScene.GetPrefab(name);
				Character val = ((prefab != null) ? prefab.GetComponent<Character>() : null);
				if ((Object)(object)val == (Object)null)
				{
					Debug.LogWarning((object)("The drop target character '" + name + "' does not exist."));
				}
				return val;
			}

			public Dictionary<Character, Drop> toCharacterDrops(ZNetScene netScene, GameObject item)
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: 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_007a: Expected O, but got Unknown
				Dictionary<Character, Drop> dictionary = new Dictionary<Character, Drop>();
				foreach (DropTarget drop in Drops)
				{
					Character val = fetchByName(netScene, drop.creature);
					if (val != null)
					{
						dictionary[val] = new Drop
						{
							m_prefab = item,
							m_amountMin = drop.min,
							m_amountMax = drop.max,
							m_chance = drop.chance,
							m_levelMultiplier = drop.levelMultiplier
						};
					}
				}
				return dictionary;
			}
		}

		private static readonly List<Item> registeredItems = new List<Item>();

		private static readonly Dictionary<ItemDrop, Item> itemDropMap = new Dictionary<ItemDrop, Item>();

		private static Dictionary<Item, Dictionary<string, List<Recipe>>> activeRecipes = new Dictionary<Item, Dictionary<string, List<Recipe>>>();

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(new byte[] { 1, 1, 2 })]
		private static Dictionary<Recipe, ConfigEntryBase> hiddenCraftRecipes = new Dictionary<Recipe, ConfigEntryBase>();

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(new byte[] { 1, 1, 2 })]
		private static Dictionary<Recipe, ConfigEntryBase> hiddenUpgradeRecipes = new Dictionary<Recipe, ConfigEntryBase>();

		private static Dictionary<Item, Dictionary<string, ItemConfig>> itemCraftConfigs = new Dictionary<Item, Dictionary<string, ItemConfig>>();

		private static Dictionary<Item, ConfigEntry<string>> itemDropConfigs = new Dictionary<Item, ConfigEntry<string>>();

		private Dictionary<CharacterDrop, Drop> characterDrops = new Dictionary<CharacterDrop, Drop>();

		private readonly Dictionary<ConfigEntryBase, Action> statsConfigs = new Dictionary<ConfigEntryBase, Action>();

		public static Configurability DefaultConfigurability = Configurability.Full;

		public Configurability? Configurable = null;

		private Configurability configurationVisible = Configurability.Full;

		public readonly GameObject Prefab;

		[Description("Specifies the maximum required crafting station level to upgrade and repair the item.\nDefault is calculated from crafting station level and maximum quality.")]
		public int MaximumRequiredStationLevel = int.MaxValue;

		[Description("Assigns the item as a drop item to a creature.\nUses a creature name, a drop chance and a minimum and maximum amount.")]
		public readonly DropTargets DropsFrom = new DropTargets();

		internal List<Conversion> Conversions = new List<Conversion>();

		internal List<ItemConversion> conversions = new List<ItemConversion>();

		public Dictionary<string, ItemRecipe> Recipes = new Dictionary<string, ItemRecipe>();

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		private LocalizeKey _name;

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		private LocalizeKey _description;

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		private static object configManager;

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		private static Localization _english;

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static bool hasConfigSync = true;

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		private static object _configSync;

		private Configurability configurability => Configurable ?? DefaultConfigurability;

		[Description("Specifies the resources needed to craft the item.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the item should need.")]
		public RequiredResourceList RequiredItems => this[""].RequiredItems;

		[Description("Specifies the resources needed to upgrade the item.\nUse .Add to add resources with their internal ID and an amount. This amount will be multipled by the item quality level.\nUse one .Add for each resource type the upgrade should need.")]
		public RequiredResourceList RequiredUpgradeItems => this[""].RequiredUpgradeItems;

		[Description("Specifies the crafting station needed to craft the item.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.\nUse one .Add for each crafting station.")]
		public CraftingStationList Crafting => this[""].Crafting;

		[Description("Specifies a config entry which toggles whether a recipe is active.")]
		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		public ConfigEntryBase RecipeIsActive
		{
			[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(2)]
			get
			{
				return this[""].RecipeIsActive;
			}
			[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(2)]
			set
			{
				this[""].RecipeIsActive = value;
			}
		}

		[Description("Specifies the number of items that should be given to the player with a single craft of the item.\nDefaults to 1.")]
		public int CraftAmount
		{
			get
			{
				return this[""].CraftAmount;
			}
			set
			{
				this[""].CraftAmount = value;
			}
		}

		public bool RequireOnlyOneIngredient
		{
			get
			{
				return this[""].RequireOnlyOneIngredient;
			}
			set
			{
				this[""].RequireOnlyOneIngredient = value;
			}
		}

		public float QualityResultAmountMultiplier
		{
			get
			{
				return this[""].QualityResultAmountMultiplier;
			}
			set
			{
				this[""].QualityResultAmountMultiplier = value;
			}
		}

		public ItemRecipe this[string name]
		{
			get
			{
				if (Recipes.TryGetValue(name, out var value))
				{
					return value;
				}
				return Recipes[name] = new ItemRecipe();
			}
		}

		public LocalizeKey Name
		{
			get
			{
				LocalizeKey name = _name;
				if (name != null)
				{
					return name;
				}
				SharedData shared = Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
				if (shared.m_name.StartsWith("$"))
				{
					_name = new LocalizeKey(shared.m_name);
				}
				else
				{
					string text = "$item_" + ((Object)Prefab).name.Replace(" ", "_");
					_name = new LocalizeKey(text).English(shared.m_name);
					shared.m_name = text;
				}
				return _name;
			}
		}

		public LocalizeKey Description
		{
			get
			{
				LocalizeKey description = _description;
				if (description != null)
				{
					return description;
				}
				SharedData shared = Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
				if (shared.m_description.StartsWith("$"))
				{
					_description = new LocalizeKey(shared.m_description);
				}
				else
				{
					string text = "$itemdesc_" + ((Object)Prefab).name.Replace(" ", "_");
					_description = new LocalizeKey(text).English(shared.m_description);
					shared.m_description = text;
				}
				return _description;
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Expected O, but got Unknown
				if (_plugin == null)
				{
					IEnumerable<TypeInfo> source;
					try
					{
						source = Assembly.GetExecutingAssembly().DefinedTypes.ToList();
					}
					catch (ReflectionTypeLoadException ex)
					{
						source = from t in ex.Types
							where t != null
							select t.GetTypeInfo();
					}
					_plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
				}
				return _plugin;
			}
		}

		[<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(2)]
		private static object configSync
		{
			[<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(2)]
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " ItemManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		public Item(string assetBundleFileName, string prefabName, string folderName = "assets")
			: this(PrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName)
		{
		}

		public Item(AssetBundle bundle, string prefabName)
			: this(PrefabManager.RegisterPrefab(bundle, prefabName, addToObjectDb: true), skipRegistering: true)
		{
		}

		public Item(GameObject prefab, bool skipRegistering = false)
		{
			if (!skipRegistering)
			{
				PrefabManager.RegisterPrefab(prefab, addToObjectDb: true);
			}
			Prefab = prefab;
			registeredItems.Add(this);
			itemDropMap[Prefab.GetComponent<ItemDrop>()] = this;
		}

		public void ToggleConfigurationVisibility(Configurability visible)
		{
			configurationVisible = visible;
			if (itemDropConfigs.TryGetValue(this, out var value))
			{
				Toggle((ConfigEntryBase)(object)value, Configurability.Drop);
			}
			if (itemCraftConfigs.TryGetValue(this, out var value2))
			{
				foreach (ItemConfig value4 in value2.Values)
				{
					ToggleObj(value4, Configurability.Recipe);
				}
			}
			foreach (Conversion conversion in Conversions)
			{
				if (conversion.config != null)
				{
					ToggleObj(conversion.config, Configurability.Recipe);
				}
			}
			foreach (KeyValuePair<ConfigEntryBase, Action> statsConfig in statsConfigs)
			{
				Toggle(statsConfig.Key, Configurability.Stats);
				if ((visible & Configurability.Stats) != 0)
				{
					statsConfig.Value();
				}
			}
			reloadConfigDisplay();
			void Toggle(ConfigEntryBase cfg, Configurability check)
			{
				object[] tags = cfg.Description.Tags;
				foreach (object obj2 in tags)
				{
					if (obj2 is ConfigurationManagerAttributes configurationManagerAttributes)
					{
						configurationManagerAttributes.Browsable = (visible & check) != 0 && (configurationManagerAttributes.browsability == null || configurationManagerAttributes.browsability());
					}
				}
			}
			void ToggleObj(object obj, Configurability check)
			{
				FieldInfo[] fields = obj.GetType().GetFields();
				foreach (FieldInfo fieldInfo in fields)
				{
					object? value3 = fieldInfo.GetValue(obj);
					ConfigEntryBase val = (ConfigEntryBase)((value3 is ConfigEntryBase) ? value3 : null);
					if (val != null)
					{
						Toggle(val, check);
					}
				}
			}
		}

		internal static void reloadConfigDisplay()
		{
			configManager?.GetType().GetMethod("BuildSettingList").Invoke(configManager, Array.Empty<object>());
		}

		internal static void Patch_FejdStartup()
		{
			//IL_1010: Unknown result type (might be due to invalid IL or missing references)
			//IL_1015: Unknown result type (might be due to invalid IL or missing references)
			//IL_10dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_10e0: Invalid comparison between Unknown and I4
			//IL_0cdb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ce5: Expected O, but got Unknown
			//IL_10e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_10e5: Invalid comparison between Unknown and I4
			//IL_10e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_10eb: Invalid comparison between Unknown and I4
			//IL_1251: Unknown result type (might be due to invalid IL or missing references)
			//IL_1254: Invalid comparison between Unknown and I4
			//IL_10ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_10f0: Invalid comparison between Unknown and I4
			//IL_0377: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Expected O, but got Unknown
			//IL_1256: Unknown result type (might be due to invalid IL or missing references)
			//IL_1259: Invalid comparison between Unknown and I4
			//IL_10f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_10f6: Invalid comparison between Unknown and I4
			//IL_0e09: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e13: Expected O, but got Unknown
			//IL_0eb5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ebf: Expected O, but got Unknown
			//IL_125b: Unknown result type (might be due to invalid IL or missing references)
			//IL_125e: Invalid comparison between Unknown and I4
			//IL_10f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_10fb: Invalid comparison between Unknown and I4
			//IL_0f6a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f74: Expected O, but got Unknown
			//IL_146e: Unknown result type (might be due to invalid IL or missing references)
			//IL_1471: Invalid comparison between Unknown and I4
			//IL_1260: Unknown result type (might be due to invalid IL or missing references)
			//IL_1264: Invalid comparison between Unknown and I4
			//IL_10fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_1101: Invalid comparison between Unknown and I4
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0484: Expected O, but got Unknown
			//IL_1473: Unknown result type (might be due to invalid IL or missing references)
			//IL_1477: Invalid comparison between Unknown and I4
			//IL_1266: Unknown result type (might be due to invalid IL or missing references)
			//IL_126a: Invalid comparison between Unknown and I4
			//IL_1103: Unknown result type (might be due to invalid IL or missing references)
			//IL_1107: Invalid comparison between Unknown and I4
			//IL_1479: Unknown result type (might be due to invalid IL or missing references)
			//IL_147c: Invalid comparison between Unknown and I4
			//IL_1109: Unknown result type (might be due to invalid IL or missing references)
			//IL_110c: Invalid comparison between Unknown and I4
			//IL_05c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d3: Expected O, but got Unknown
			//IL_1560: Unknown result type (might be due to invalid IL or missing references)
			//IL_1565: Unknown result type (might be due to invalid IL or missing references)
			//IL_1567: Unknown result type (might be due to invalid IL or missing references)
			//IL_156a: Invalid comparison between Unknown and I4
			//IL_147e: Unknown result type (might be due to invalid IL or missing references)
			//IL_1482: Invalid comparison between Unknown and I4
			//IL_110e: Unknown result type (might be due to invalid IL or missing references)
			//IL_1112: Invalid comparison between Unknown and I4
			//IL_156c: Unknown result type (might be due to invalid IL or missing references)
			//IL_1570: Invalid comparison between Unknown and I4
			//IL_1484: Unknown result type (might be due to invalid IL or missing references)
			//IL_1488: Invalid comparison between Unknown and I4
			//IL_1114: Unknown result type (might be due to invalid IL or missing references)
			//IL_1118: Invalid comparison between Unknown and I4
			//IL_07b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_07bc: Expected O, but got Unknown
			//IL_0707: Unknown result type (might be due to invalid IL or missing references)
			//IL_0711: Expected O, but got Unknown
			//IL_15e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_15e9: Invalid comparison between Unknown and I4
			//IL_15eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_15ee: Invalid comparison between Unknown and I4
			//IL_08cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d6: Expected O, but got Unknown
			//IL_15f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_15f4: Invalid comparison between Unknown and I4
			//IL_1747: Unknown result type (might be due to invalid IL or missing references)
			//IL_174a: Invalid comparison between Unknown and I4
			//IL_15f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_15f9: Invalid comparison between Unknown and I4
			//IL_15fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_15ff: Invalid comparison between Unknown and I4
			//IL_1601: Unknown result type (might be due to invalid IL or missing references)
			//IL_1605: Invalid comparison between Unknown and I4
			//IL_1959: Unknown result type (might be due to invalid IL or missing references)
			//IL_1960: Invalid comparison between Unknown and I4
			//IL_1a35: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a3a: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a3c: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a40: Invalid comparison between Unknown and I4
			//IL_1a42: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a46: Invalid comparison between Unknown and I4
			//IL_16b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_16bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_1abc: Unknown result type (might be due to invalid IL or missing references)
			//IL_1abf: Invalid comparison between Unknown and I4
			//IL_1ac1: Unknown result type (might be due to invalid IL or missing references)
			//IL_1ac5: Invalid comparison between Unknown and I4
			//IL_1ac7: Unknown result type (might be due to invalid IL or missing references)
			//IL_1acb: Invalid comparison between Unknown and I4
			//IL_1acd: Unknown result type (might be due to invalid IL or missing references)
			//IL_1ad0: Invalid comparison between Unknown and I4
			//IL_1f58: Unknown result type (might be due to invalid IL or missing references)
			//IL_1f5b: Invalid comparison between Unknown and I4
			Type type = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager");
			configManager = ((type == null) ? null : Chainloader.ManagerObject.GetComponent(type));
			if (DefaultConfigurability != 0)
			{
				bool saveOnConfigSet = plugin.Config.SaveOnConfigSet;
				plugin.Config.SaveOnConfigSet = false;
				foreach (Item item3 in registeredItems.Where([<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (Item i) => i.configurability != Configurability.Disabled))
				{
					Item item2 = item3;
					string name2 = item2.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name;
					string englishName = new Regex("['[\"\\]]").Replace(english.Localize(name2), "").Trim();
					string localizedName = Localization.instance.Localize(name2).Trim();
					if ((item2.configurability & Configurability.Recipe) != 0)
					{
						itemCraftConfigs[item2] = new Dictionary<string, ItemConfig>();
						foreach (string item4 in item2.Recipes.Keys.DefaultIfEmpty(""))
						{
							string configKey = item4;
							int order = 0;
							string text = ((configKey == "") ? "" : (" (" + configKey + ")"));
							if (!item2.Recipes.ContainsKey(configKey) || item2.Recipes[configKey].Crafting.Stations.Count <= 0)
							{
								continue;
							}
							ItemConfig itemConfig2 = (itemCraftConfigs[item2][configKey] = new ItemConfig());
							ItemConfig cfg = itemConfig2;
							List<ConfigurationManagerAttributes> hideWhenNoneAttributes = new List<ConfigurationManagerAttributes>();
							cfg.table = config(englishName, "Crafting Station" + text, item2.Recipes[configKey].Crafting.Stations.First().Table, new ConfigDescription("Crafting station where " + englishName + " is available.", (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Order = (order -= 1),
									Browsable = ((item2.configurationVisible & Configurability.Recipe) != 0),
									Category = localizedName
								}
							}));
							ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes
							{
								Order = (order -= 1),
								browsability = CustomTableBrowsability,
								Browsable = (CustomTableBrowsability() && (item2.configurationVisible & Configurability.Recipe) != 0),
								Category = localizedName
							};
							cfg.customTable = config(englishName, "Custom Crafting Station" + text, item2.Recipes[configKey].Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
							cfg.table.SettingChanged += TableConfigChanged;
							cfg.customTable.SettingChanged += TableConfigChanged;
							ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes
							{
								Order = (order -= 1),
								browsability = TableLevelBrowsability,
								Browsable = (TableLevelBrowsability() && (item2.configurationVisible & Configurability.Recipe) != 0),
								Category = localizedName
							};
							hideWhenNoneAttributes.Add(configurationManagerAttributes);
							cfg.tableLevel = config(englishName, "Crafting Station Level" + text, item2.Recipes[configKey].Crafting.Stations.First().level, new ConfigDescription("Required crafting station level to craft " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes }));
							cfg.tableLevel.SettingChanged += [<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (object _, EventArgs _) =>
							{
								if (activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(configKey, out var value10))
								{
									value10.First().m_minStationLevel = cfg.tableLevel.Value;
								}
							};
							if (item2.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality > 1)
							{
								cfg.maximumTableLevel = config(englishName, "Maximum Crafting Station Level" + text, (item2.MaximumRequiredStationLevel == int.MaxValue) ? (item2.Recipes[configKey].Crafting.Stations.First().level + item2.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality - 1) : item2.MaximumRequiredStationLevel, new ConfigDescription("Maximum crafting station level to upgrade and repair " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes }));
							}
							cfg.requireOneIngredient = config(englishName, "Require only one resource" + text, item2.Recipes[configKey].RequireOnlyOneIngredient ? Toggle.On : Toggle.Off, new ConfigDescription("Whether only one of the ingredients is needed to craft " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Order = (order -= 1),
									Category = localizedName
								}
							}));
							ConfigurationManagerAttributes qualityResultAttributes = new ConfigurationManagerAttributes
							{
								Order = (order -= 1),
								browsability = QualityResultBrowsability,
								Browsable = (QualityResultBrowsability() && (item2.configurationVisible & Configurability.Recipe) != 0),
								Category = localizedName
							};
							cfg.requireOneIngredient.SettingChanged += [<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (object _, EventArgs _) =>
							{
								if (activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(configKey, out var value9))
								{
									foreach (Recipe item5 in value9)
									{
										item5.m_requireOnlyOneIngredient = cfg.requireOneIngredient.Value == Toggle.On;
									}
								}
								qualityResultAttributes.Browsable = QualityResultBrowsability();
								reloadConfigDisplay();
							};
							cfg.qualityResultAmountMultiplier = config(englishName, "Quality Multiplier" + text, item2.Recipes[configKey].QualityResultAmountMultiplier, new ConfigDescription("Multiplies the crafted amount based on the quality of the resources when crafting " + englishName + ". Only works, if Require Only One Resource is true.", (AcceptableValueBase)null, new object[1] { qualityResultAttributes }));
							cfg.qualityResultAmountMultiplier.SettingChanged += [<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (object _, EventArgs _) =>
							{
								if (activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(configKey, out var value8))
								{
									foreach (Recipe item6 in value8)
									{
										item6.m_qualityResultAmountMultiplier = cfg.qualityResultAmountMultiplier.Value;
									}
								}
							};
							if ((!item2.Recipes[configKey].RequiredItems.Free || item2.Recipes[configKey].RequiredItems.Requirements.Count > 0) && item2.Recipes[configKey].RequiredItems.Requirements.All((Requirement r) => r.amountConfig == null))
							{
								cfg.craft = itemConfig("Crafting Costs" + text, new SerializedRequirements(item2.Recipes[configKey].RequiredItems.Requirements).ToString(), "Item costs to craft " + englishName);
							}
							if (item2.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality > 1 && (!item2.Recipes[configKey].RequiredUpgradeItems.Free || item2.Recipes[configKey].RequiredUpgradeItems.Requirements.Count > 0) && item2.Recipes[configKey].RequiredUpgradeItems.Requirements.All((Requirement r) => r.amountConfig == null))
							{
								cfg.upgrade = itemConfig("Upgrading Costs" + text, new SerializedRequirements(item2.Recipes[configKey].RequiredUpgradeItems.Requirements).ToString(), "Item costs per level to upgrade " + englishName);
							}
							if (cfg.craft != null)
							{
								cfg.craft.SettingChanged += ConfigChanged;
							}
							if (cfg.upgrade != null)
							{
								cfg.upgrade.SettingChanged += ConfigChanged;
							}
							void ConfigChanged(object o, EventArgs e)
							{
								if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(configKey, out var value4))
								{
									foreach (Recipe item7 in value4)
									{
										item7.m_resources = SerializedRequirements.toPieceReqs(ObjectDB.instance, new SerializedRequirements(cfg.craft?.Value ?? ""), new SerializedRequirements(cfg.upgrade?.Value ?? ""));
									}
								}
							}
							bool CustomTableBrowsability()
							{
								return cfg.table.Value == CraftingTable.Custom;
							}
							bool ItemBrowsability()
							{
								return cfg.table.Value != CraftingTable.Disabled;
							}
							bool QualityResultBrowsability()
							{
								return cfg.requireOneIngredient.Value == Toggle.On;
							}
							void TableConfigChanged(object o, EventArgs e)
							{
								if (activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(configKey, out var value5))
								{
									value5.First().m_enabled = cfg.table.Value != CraftingTable.Disabled;
									CraftingTable value6 = cfg.table.Value;
									if (value6 == CraftingTable.Inventory || value6 == CraftingTable.Disabled)
									{
										value5.First().m_craftingStation = null;
									}
									else if (cfg.table.Value == CraftingTable.Custom)
									{
										Recipe obj = value5.First();
										GameObject prefab2 = ZNetScene.instance.GetPrefab(cfg.customTable.Value);
										obj.m_craftingStation = ((prefab2 != null) ? prefab2.GetComponent<CraftingStation>() : null);
									}
									else
									{
										value5.First().m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName(cfg.table.Value)).GetComponent<CraftingStation>();
									}
								}
								customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom;
								foreach (ConfigurationManagerAttributes item8 in hideWhenNoneAttributes)
								{
									item8.Browsable = cfg.table.Value != CraftingTable.Disabled;
								}
								reloadConfigDisplay();
							}
							bool TableLevelBrowsability()
							{
								return cfg.table.Value != CraftingTable.Disabled;
							}
							ConfigEntry<string> itemConfig(string name, string value, string desc)
							{
								//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
								//IL_00b5: Expected O, but got Unknown
								ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes
								{
									CustomDrawer = drawRequirementsConfigTable,
									Order = (order -= 1),
									browsability = ItemBrowsability,
									Browsable = (ItemBrowsability() && (item2.configurationVisible & Configurability.Recipe) != 0),
									Category = localizedName
								};
								hideWhenNoneAttributes.Add(configurationManagerAttributes2);
								return config(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 }));
							}
						}
						if ((item2.configurability & Configurability.Drop) != 0)
						{
							ConfigEntry<string> val3 = (itemDropConfigs[item2] = config(englishName, "Drops from", new SerializedDrop(item2.DropsFrom.Drops).ToString(), new ConfigDescription(englishName + " drops from this creature.", (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									CustomDrawer = drawDropsConfigTable,
									Category = localizedName,
									Browsable = ((item2.configurationVisible & Configurability.Drop) != 0)
								}
							})));
							ConfigEntry<string> val4 = val3;
							val4.SettingChanged += [<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (object _, EventArgs _) =>
							{
								item2.UpdateCharacterDrop();
							};
						}
						for (int j = 0; j < item2.Conversions.Count; j++)
						{
							string text2 = ((item2.Conversions.Count > 1) ? $"{j + 1}. " : "");
							Conversion conversion = item2.Conversions[j];
							conversion.config = new Conversion.ConversionConfig();
							int index = j;
							conversion.config.input = config(englishName, text2 + "Conversion Input Item", conversion.Input, new ConfigDescription("Duration of conversion to create " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Category = localizedName,
									Browsable = ((item2.configurationVisible & Configurability.Recipe) != 0)
								}
							}));
							conversion.config.input.SettingChanged += [<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (object _, EventArgs _) =>
							{
								if (index < item2.conversions.Count)
								{
									ObjectDB instance = ObjectDB.instance;
									if (instance != null)
									{
										ItemDrop from = SerializedRequirements.fetchByName(instance, conversion.config.input.Value);
										item2.conversions[index].m_from = from;
										UpdatePiece();
									}
								}
							};
							conversion.config.piece = config(englishName, text2 + "Conversion Piece", conversion.Piece, new ConfigDescription("Duration of conversion to create " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Category = localizedName,
									Browsable = ((item2.configurationVisible & Configurability.Recipe) != 0)
								}
							}));
							conversion.config.piece.SettingChanged += [<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (object _, EventArgs _) =>
							{
								UpdatePiece();
							};
							conversion.config.customPiece = config(englishName, text2 + "Conversion Custom Piece", conversion.customPiece ?? "", new ConfigDescription("Duration of conversion to create " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Category = localizedName,
									Browsable = ((item2.configurationVisible & Configurability.Recipe) != 0)
								}
							}));
							conversion.config.customPiece.SettingChanged += [<0d49a340-51cb-4233-91da-521dfe94608c>NullableContext(0)] (object _, EventArgs _) =>
							{
								UpdatePiece();
							};
							void UpdatePiece()
							{
								if (index < item2.conversions.Count && Object.op_Implicit((Object)(object)ZNetScene.instance))
								{
									string text3 = ((conversion.config.piece.Value == ConversionPiece.Disabled) ? null : ((conversion.config.piece.Value == ConversionPiece.Custom) ? conversion.config.customPiece.Value : getInternalName(conversion.config.piece.Value)));
									string activePiece = conversion.config.activePiece;
									if (conversion.config.activePiece != null)
									{
										Smelter component = ZNetScene.instance.GetPrefab(conversion.config.activePiece).GetComponent<Smelter>();
										int num = component.m_conversion.IndexOf(item2.conversions[index]);
										if (num >= 0)
										{
											Smelter[] array3 = Resources.FindObjectsOfTypeAll<Smelter>();
											foreach (Smelter val5 in array3)
											{
												if (Utils.GetPrefabName(((Component)val5).gameObject) == activePiece)
												{
													val5.m_conversion.RemoveAt(num);
												}
											}
										}
										conversion.config.activePiece = null;
									}
									if (item2.conversions[index].m_from != null && conversion.config.piece.Value != 0)
									{
										GameObject prefab = ZNetScene.instance.GetPrefab(text3);
										if (((prefab != null) ? prefab.GetComponent<Smelter>() : null) != null)
										{
											conversion.config.activePiece = text3;
											Smelter[] array4 = Resources.FindObjectsOfTypeAll<Smelter>();
											foreach (Smelter val6 in array4)
											{
												if (Utils.GetPrefabName(((Component)val6).gameObject) == text3)
												{
													val6.m_conversion.Add(item2.conversions[index]);
												}
											}
										}
									}
								}
							}
						}
					}
					if ((item2.configurability & Configurability.Stats) == 0)
					{
						continue;
					}
					item2.statsConfigs.Clear();
					SharedData shared2 = item2.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
					ItemType itemType = shared2.m_itemType;
					statcfg<float>("Weight", "Weight of " + englishName + ".", (SharedData shared) => shared.m_weight, delegate(SharedData shared, float value)
					{
						shared.m_weight = value;
					});
					statcfg<int>("Trader Value", "Trader value of " + englishName + ".", (SharedData shared) => shared.m_value, delegate(SharedData shared, int value)
					{
						shared.m_value = value;
					});
					if ((int)itemType == 4 || (int)itemType == 7 || (int)itemType == 12 || (int)itemType == 6 || (int)itemType == 11 || (int)itemType == 5 || (int)itemType == 17 || (int)itemType == 19 || (int)itemType == 3 || (int)itemType == 14 || (int)itemType == 22)
					{
						statcfg<float>("Durability", "Durability of " + englishName + ".", (SharedData shared) => shared.m_maxDurability, delegate(SharedData shared, float value)
						{
							shared.m_maxDurability = value;
						});
						statcfg<float>("Durability per Level", "Durability gain per level of " + englishName + ".", (SharedData shared) => shared.m_durabilityPerLevel, delegate(SharedData shared, float value)
						{
							shared.m_durabilityPerLevel = value;
						});
						statcfg<float>("Movement Speed Modifier", "Movement speed modifier of " + englishName + ".", (SharedData shared) => shared.m_movementModifier, delegate(SharedData shared, float value)
						{
							shared.m_movementModifier = value;
						});
					}
					if ((int)itemType == 4 || (int)itemType == 5 || (int)itemType == 3 || (int)itemType == 14 || (int)itemType == 22)
					{
						statcfg<float>("Block Armor", "Block armor of " + englishName + ".", (SharedData shared) => shared.m_blockPower, delegate(SharedData shared, float value)
						{
							shared.m_blockPower = value;
						});
						statcfg<float>("Block Armor per Level", "Block armor per level for " + englishName + ".", (SharedData shared) => shared.m_blockPowerPerLevel, delegate(SharedData shared, float value)
						{
							shared.m_blockPowerPerLevel = value;
						});
						statcfg<float>("Block Force", "Block force of " + englishName + ".", (SharedData shared) => shared.m_deflectionForce, delegate(SharedData shared, float value)
						{
							shared.m_deflectionForce = value;
						});
						statcfg<float>("Block Force per Level", "Block force per level for " + englishName + ".", (SharedData shared) => shared.m_deflectionForcePerLevel, delegate(SharedData shared, float value)
						{
							shared.m_deflectionForcePerLevel = value;
						});
						statcfg<float>("Parry Bonus", "Parry bonus of " + englishName + ".", (SharedData shared) => shared.m_timedBlockBonus, delegate(SharedData shared, float value)
						{
							shared.m_timedBlockBonus = value;
						});
					}
					else if ((int)itemType == 7 || (int)itemType == 12 || (int)itemType == 6 || (int)itemType == 11 || (int)itemType == 17)
					{
						statcfg<float>("Armor", "Armor of " + englishName + ".", (SharedData shared) => shared.m_armor, delegate(SharedData shared, float value)
						{
							shared.m_armor = value;
						});
						statcfg<float>("Armor per Level", "Armor per level for " + englishName + ".", (SharedData shared) => shared.m_armorPerLevel, delegate(SharedData shared, float value)
						{
							shared.m_armorPerLevel = value;
						});
					}
					SkillType skillType = shared2.m_skillType;
					if ((int)skillType == 7 || (int)skillType == 12)
					{
						statcfg<int>("Tool tier", "Tool tier of " + englishName + ".", (SharedData shared) => shared.m_toolTier, delegate(SharedData shared, int value)
						{
							shared.m_toolTier = value;
						});
					}
					if ((int)itemType == 5 || (int)itemType == 7 || (int)itemType == 12 || (int)itemType == 6 || (int)itemType == 11 || (int)itemType == 17)
					{
						Dictionary<DamageType, DamageModifier> modifiers = shared2.m_damageModifiers.ToDictionary((DamageModPair d) => d.m_type, (DamageModPair d) => (DamageModifier)d.m_modifier);
						DamageType[] first = (DamageType[])Enum.GetValues(typeof(DamageType));
						DamageType[] array = new DamageType[5];
						RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
						foreach (DamageType item9 in first.Except((IEnumerable<DamageType>)(object)array))
						{
							DamageType damageType = item9;
							statcfg<DamageModifier>(((object)(DamageType)(ref damageType)).ToString() + " Resistance", ((object)(DamageType)(ref damageType)).ToString() + " resistance of " + englishName + ".", (SharedData _) => modifiers.TryGetValue(damageType, out var value7) ? value7 : DamageModifier.None, delegate(SharedData shared, DamageModifier value)
							{
								//IL_0003: Unknown result type (might be due to invalid IL or missing references)
								//IL_000c: Unknown result type (might be due to invalid IL or missing references)
								//IL_0011: Unknown result type (might be due to invalid IL or missing references)
								//IL_0019: Unknown result type (might be due to invalid IL or missing references)
								//IL_001e: Unknown result type (might be due to invalid IL or missing references)
								//IL_001f: Unknown result type (might be due to invalid IL or missing references)
								//IL_002c: Unknown result type (might be due to invalid IL or missing references)
								//IL_0031: Unknown result type (might be due to invalid IL or missing references)
								//IL_0037: Unknown result type (might be due to invalid IL or missing references)
								//IL_009d: Unknown result type (might be due to invalid IL or missing references)
								//IL_0066: Unknown result type (might be due to invalid IL or missing references)
								DamageModPair val7 = default(DamageModPair);
								val7.m_type = damageType;
								val7.m_modifier = (DamageModifier)value;
								DamageModPair val8 = val7;
								for (int num2 = 0; num2 < shared.m_damageModifiers.Count; num2++)
								{
									if (shared.m_damageModifiers[num2].m_type == damageType)
									{
										if (value == DamageModifier.None)
										{
											shared.m_damageModifiers.RemoveAt(num2);
										}
										else
										{
											shared.m_damageModifiers[num2] = val8;
										}
										return;
									}
								}
								if (value != DamageModifier.None)
								{
									shared.m_damageModifiers.Add(val8);
								}
							});
						}
					}
					if ((int)itemType == 2 && shared2.m_food > 0f)
					{
						statcfg<float>("Health", "Health value of " + englishName + ".", (SharedData shared) => shared.m_food, delegate(SharedData shared, float value)
						{
							shared.m_food = value;
						});
						statcfg<float>("Stamina", "Stamina value of " + englishName + ".", (SharedData shared) => shared.m_foodStamina, delegate(SharedData shared, float value)
						{
							shared.m_foodStamina = value;
						});
						statcfg<float>("Eitr", "Eitr value of " + englishName + ".", (SharedData shared) => shared.m_foodEitr, delegate(SharedData shared, float value)
						{
							shared.m_foodEitr = value;
						});
						statcfg<float>("Duration", "Duration of " + englishName + ".", (SharedData shared) => shared.m_foodBurnTime, delegate(SharedData shared, float value)
						{
							shared.m_foodBurnTime = value;
						});
						statcfg<float>("Health Regen", "Health regen value of " + englishName + ".", (SharedData shared) => shared.m_foodRegen, delegate(SharedData shared, float value)
						{
							shared.m_foodRegen = value;
						});
					}
					if ((int)shared2.m_skillType == 10)
					{
						statcfg<float>("Health Cost", "Health cost of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackHealth, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_attackHealth = value;
						});
						statcfg<float>("Health Cost Percentage", "Health cost percentage of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackHealthPercentage, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_attackHealthPercentage = value;
						});
					}
					skillType = shared2.m_skillType;
					if ((int)skillType == 10 || (int)skillType == 9)
					{
						statcfg<float>("Eitr Cost", "Eitr cost of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackEitr, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_attackEitr = value;
						});
					}
					if ((int)itemType != 3 && (int)itemType != 14 && (int)itemType != 22 && (int)itemType != 4)
					{
						continue;
					}
					statcfg<float>("Knockback", "Knockback of " + englishName + ".", (SharedData shared) => shared.m_attackForce, delegate(SharedData shared, float value)
					{
						shared.m_attackForce = value;
					});
					statcfg<float>("Backstab Bonus", "Backstab bonus of " + englishName + ".", (SharedData shared) => shared.m_backstabBonus, delegate(SharedData shared, float value)
					{
						shared.m_backstabBonus = value;
					});
					statcfg<float>("Attack Stamina", "Attack stamina of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackStamina, delegate(SharedData shared, float value)
					{
						shared.m_attack.m_attackStamina = value;
					});
					SetDmg("True", (DamageTypes dmg) => dmg.m_damage, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_damage = val;
					});
					SetDmg("Slash", (DamageTypes dmg) => dmg.m_slash, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_slash = val;
					});
					SetDmg("Pierce", (DamageTypes dmg) => dmg.m_pierce, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_pierce = val;
					});
					SetDmg("Blunt", (DamageTypes dmg) => dmg.m_blunt, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_blunt = val;
					});
					SetDmg("Chop", (DamageTypes dmg) => dmg.m_chop, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_chop = val;
					});
					SetDmg("Pickaxe", (DamageTypes dmg) => dmg.m_pickaxe, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_pickaxe = val;
					});
					SetDmg("Fire", (DamageTypes dmg) => dmg.m_fire, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_fire = val;
					});
					SetDmg("Poison", (DamageTypes dmg) => dmg.m_poison, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_poison = val;
					});
					SetDmg("Frost", (DamageTypes dmg) => dmg.m_frost, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_frost = val;
					});
					SetDmg("Lightning", (DamageTypes dmg) => dmg.m_lightning, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_lightning = val;
					});
					SetDmg("Spirit", (DamageTypes dmg) => dmg.m_spirit, delegate(ref DamageTypes dmg, float val)
					{
						dmg.m_spirit = val;
					});
					if ((int)itemType == 4)
					{
						statcfg<int>("Projectiles", "Number of projectiles that " + englishName + " shoots at once.", (SharedData shared) => shared.m_attack.m_projectileBursts, delegate(SharedData shared, int value)
						{
							shared.m_attack.m_projectileBursts = value;
						});
						statcfg<float>("Burst Interval", "Time between the projectiles " + englishName + " shoots at once.", (SharedData shared) => shared.m_attack.m_burstInterval, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_burstInterval = value;
						});
						statcfg<float>("Minimum Accuracy", "Minimum accuracy for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileAccuracyMin, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_projectileAccuracyMin = value;
						});
						statcfg<float>("Accuracy", "Accuracy for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileAccuracy, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_projectileAccuracy = value;
						});
						statcfg<float>("Minimum Velocity", "Minimum velocity for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileVelMin, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_projectileVelMin = value;
						});
						statcfg<float>("Velocity", "Velocity for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileVel, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_projectileVel = value;
						});
						statcfg<float>("Maximum Draw Time", "Time until " + englishName + " is fully drawn at skill level 0.", (SharedData shared) => shared.m_attack.m_drawDurationMin, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_drawDurationMin = value;
						});
						statcfg<float>("Stamina Drain", "Stamina drain per second while drawing " + englishName + ".", (SharedData shared) => shared.m_attack.m_drawStaminaDrain, delegate(SharedData shared, float value)
						{
							shared.m_attack.m_drawStaminaDrain = value;
						});
					}
					void SetDmg(string dmgType, Func<DamageTypes, float> readDmg, setDmgFunc setDmg)
					{
						statcfg<float>(dmgType + " Damage", dmgType + " damage dealt by " + englishName + ".", (SharedData shared) => readDmg(shared.m_damages), delegate(SharedData shared, float val)
						{
							setDmg(ref shared.m_damages, val);
						});
						statcfg<float>(dmgType + " Damage Per Level", dmgType + " damage dealt increase per level for " + englishName + ".", (SharedData shared) => readDmg(shared.m_damagesPerLevel), delegate(SharedData shared, float val)
						{
							setDmg(ref shared.m_damagesPerLevel, val);
						});
					}
					void statcfg<T>(string configName, string description, [<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(new byte[] { 1, 1, 0 })] Func<SharedData, T> readDefault, [<b98f41fe-cc42-4143-abec-caa2245befde>Nullable(new byte[] { 1, 1, 0 })] Action<SharedData, T> setValue)
					{
					

BepInEx/plugins/ASharpPen-Drop_That/Valheim.DropThat.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
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.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using CreatureLevelControl;
using EpicLoot;
using EpicLoot.Data;
using EpicLoot.LegendarySystem;
using HarmonyLib;
using UnityEngine;
using Valheim.DropThat.Caches;
using Valheim.DropThat.Configuration;
using Valheim.DropThat.Configuration.ConfigTypes;
using Valheim.DropThat.Core;
using Valheim.DropThat.Core.Configuration;
using Valheim.DropThat.Core.Network;
using Valheim.DropThat.Creature.DamageRecords;
using Valheim.DropThat.Creature.StatusRecords;
using Valheim.DropThat.Debugging;
using Valheim.DropThat.Drop.CharacterDropSystem.Caches;
using Valheim.DropThat.Drop.CharacterDropSystem.Conditions;
using Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ModSpecific;
using Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ModSpecific.CLLC;
using Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ModSpecific.SpawnThat;
using Valheim.DropThat.Drop.CharacterDropSystem.Models;
using Valheim.DropThat.Drop.CharacterDropSystem.Modifiers;
using Valheim.DropThat.Drop.CharacterDropSystem.Modifiers.ModSpecific;
using Valheim.DropThat.Drop.CharacterDropSystem.Modifiers.ModSpecific.ModEpicLoot;
using Valheim.DropThat.Drop.CharacterDropSystem.Services;
using Valheim.DropThat.Drop.DropTableSystem.Caches;
using Valheim.DropThat.Drop.DropTableSystem.Conditions;
using Valheim.DropThat.Drop.DropTableSystem.Conditions.ModSpecific;
using Valheim.DropThat.Drop.DropTableSystem.Conditions.ModSpecific.ModCLLC;
using Valheim.DropThat.Drop.DropTableSystem.Managers;
using Valheim.DropThat.Drop.DropTableSystem.Modifiers;
using Valheim.DropThat.Drop.DropTableSystem.Modifiers.ModSpecific.ModEpicLoot;
using Valheim.DropThat.Drop.DropTableSystem.Wrapper;
using Valheim.DropThat.Integrations;
using Valheim.DropThat.Integrations.EpicLootIntegration;
using Valheim.DropThat.Locations;
using Valheim.DropThat.Reset;
using Valheim.DropThat.Utilities;
using Valheim.DropThat.Utilities.Valheim;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("A Sharp Pen")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Valheim mod and tool for configuring loot drops.")]
[assembly: AssemblyFileVersion("2.3.9.0")]
[assembly: AssemblyInformationalVersion("2.3.9")]
[assembly: AssemblyProduct("Valheim.DropThat")]
[assembly: AssemblyTitle("Valheim.DropThat")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ASharpPen/Valheim.SpawnThat")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.3.9.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Valheim.DropThat
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("asharppen.valheim.drop_that", "Drop That!", "2.3.9")]
	public class DropThatPlugin : BaseUnityPlugin
	{
		public const string ModId = "asharppen.valheim.drop_that";

		public const string PluginName = "Drop That!";

		public const string Version = "2.3.9";

		private void Awake()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			Log.Logger = ((BaseUnityPlugin)this).Logger;
			ConfigurationManager.LoadGeneralConfigurations();
			new Harmony("asharppen.valheim.drop_that").PatchAll();
			NetworkSetup.SetupNetworking();
		}
	}
}
namespace Valheim.DropThat.Utilities
{
	public static class CodeMatcherExtensions
	{
		public static CodeMatcher GetPosition(this CodeMatcher codeMatcher, out int position)
		{
			position = codeMatcher.Pos;
			return codeMatcher;
		}

		internal static CodeMatcher Print(this CodeMatcher codeMatcher, int before, int after)
		{
			return codeMatcher;
		}
	}
	internal static class HashSetExtensions
	{
		public static void AddNullSafe<T>(this HashSet<T> set, T candidate) where T : class
		{
			if (set != null && candidate != null)
			{
				set.Add(candidate);
			}
		}
	}
	internal static class ListExtensions
	{
		public static void AddNullSafe<T>(this List<T> list, T candidate) where T : class
		{
			if (list != null && candidate != null)
			{
				list.Add(candidate);
			}
		}
	}
	internal static class ReflectionUtils
	{
		private static MethodInfo InstantiateGameObject;

		public static MethodInfo InstantiateGameObjectMethod => InstantiateGameObject ?? (InstantiateGameObject = (from x in typeof(Object).GetMethods(BindingFlags.Static | BindingFlags.Public)
			where x.Name.StartsWith("Instantiate")
			select x into m
			where m.IsGenericMethod
			select m).First((MethodInfo m) => m.ContainsGenericParameters && m.GetParameters().Length == 3).GetGenericMethodDefinition().MakeGenericMethod(typeof(GameObject)));
	}
	public static class StringExtensions
	{
		private static char[] Comma = new char[1] { ',' };

		public static List<string> SplitBy(this string value, char splitChar, bool toUpper = false)
		{
			string[] array = value.Split(new char[1] { splitChar }, StringSplitOptions.RemoveEmptyEntries);
			if (array == null || array.Length == 0)
			{
				return new List<string>();
			}
			return array.Select((string x) => Clean(x, toUpper)).ToList();
		}

		public static List<string> SplitByComma(this string value, bool toUpper = false)
		{
			string[] array = value.Split(Comma, StringSplitOptions.RemoveEmptyEntries);
			if (array == null || array.Length == 0)
			{
				return new List<string>();
			}
			return array.Select((string x) => Clean(x, toUpper)).ToList();
		}

		private static string Clean(string x, bool toUpper)
		{
			string text = x.Trim();
			if (toUpper)
			{
				return text.ToUpperInvariant();
			}
			return text;
		}

		public static bool TryConvertToEnum<T>(this IEnumerable<string> strings, out List<T> enums) where T : struct
		{
			enums = new List<T>();
			foreach (string @string in strings)
			{
				if (Enum.TryParse<T>(@string, ignoreCase: true, out var result))
				{
					enums.Add(result);
					continue;
				}
				return false;
			}
			return true;
		}
	}
	public static class UnityObjectExtensions
	{
		private static Regex NameRegex = new Regex("^[^$(]*(?=$|[(])", RegexOptions.Compiled);

		public static bool IsNull(this Object obj)
		{
			if (obj == (Object)null || !Object.op_Implicit(obj))
			{
				return true;
			}
			return false;
		}

		public static bool IsNotNull(this Object obj)
		{
			if (obj != (Object)null && Object.op_Implicit(obj))
			{
				return true;
			}
			return false;
		}

		public static string GetCleanedName(this Object obj, bool toUpper = false)
		{
			if (obj.IsNull())
			{
				return null;
			}
			string text = obj.name.Split(new char[1] { '(' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault()?.Trim();
			if (!string.IsNullOrWhiteSpace(text))
			{
				return text;
			}
			return obj.name;
		}
	}
}
namespace Valheim.DropThat.Utilities.Valheim
{
	public static class BiomeExtensions
	{
		public static string GetNames(this Biome biome)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between Unknown and I4
			List<string> list = new List<string>();
			foreach (Biome value in Enum.GetValues(typeof(Biome)))
			{
				Biome val = value;
				if ((int)val != 0 && (biome & val) > 0)
				{
					list.Add(((object)(Biome)(ref val)).ToString());
				}
			}
			return GeneralExtensions.Join<string>((IEnumerable<string>)list, (Func<string, string>)null, ", ");
		}
	}
	public static class HitDataExtensions
	{
		public static DamageType GetCombinedDamageType(this HitData hit)
		{
			//IL_0001: 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_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			DamageType val = (DamageType)0;
			if (hit.m_damage.m_blunt > 0f)
			{
				val = (DamageType)(val | 1);
			}
			if (hit.m_damage.m_slash > 0f)
			{
				val = (DamageType)(val | 2);
			}
			if (hit.m_damage.m_pierce > 0f)
			{
				val = (DamageType)(val | 4);
			}
			if (hit.m_damage.m_chop > 0f)
			{
				val = (DamageType)(val | 8);
			}
			if (hit.m_damage.m_pickaxe > 0f)
			{
				val = (DamageType)(val | 0x10);
			}
			if (hit.m_damage.m_fire > 0f)
			{
				val = (DamageType)(val | 0x20);
			}
			if (hit.m_damage.m_frost > 0f)
			{
				val = (DamageType)(val | 0x40);
			}
			if (hit.m_damage.m_lightning > 0f)
			{
				val = (DamageType)(val | 0x80);
			}
			if (hit.m_damage.m_poison > 0f)
			{
				val = (DamageType)(val | 0x100);
			}
			if (hit.m_damage.m_spirit > 0f)
			{
				val = (DamageType)(val | 0x200);
			}
			return val;
		}
	}
}
namespace Valheim.DropThat.Reset
{
	public static class StateResetter
	{
		private static HashSet<Action> OnResetActions = new HashSet<Action>();

		public static void Subscribe(Action onReset)
		{
			OnResetActions.Add(onReset);
		}

		public static void Unsubscribe(Action onReset)
		{
			OnResetActions.Remove(onReset);
		}

		public static void Reset()
		{
			Log.LogDebug("Resetting mod state.");
			foreach (Action onResetAction in OnResetActions)
			{
				onResetAction();
			}
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "OnWorldStart")]
	public static class WorldStartPatch
	{
		[HarmonyPatch("OnWorldStart")]
		[HarmonyPrefix]
		private static void ResetState()
		{
			Log.LogDebug("OnWorldStart - Resetting configurations");
			StateResetter.Reset();
			ConfigurationManager.LoadAll();
		}

		[HarmonyPatch("JoinServer")]
		[HarmonyPrefix]
		private static void ResetStateMultiplayer()
		{
			Log.LogDebug("JoinServer - Resetting configurations");
			StateResetter.Reset();
		}

		[HarmonyPatch("ParseServerArguments")]
		[HarmonyPrefix]
		private static void ResetStateServer()
		{
			Log.LogDebug("ParseServerArguments - Resetting configurations");
			StateResetter.Reset();
			ConfigurationManager.LoadAllCharacterDropConfigurations();
			ConfigurationManager.LoadAllCharacterDropLists();
			ConfigurationManager.LoadAllDropTableConfigurations();
			ConfigurationManager.LoadAllDropTableLists();
		}
	}
}
namespace Valheim.DropThat.Locations
{
	public static class LocationHelper
	{
		private static Dictionary<Vector2i, SimpleLocation> _simpleLocationsByZone { get; set; }

		static LocationHelper()
		{
			StateResetter.Subscribe(delegate
			{
				_simpleLocationsByZone = null;
			});
		}

		internal static void SetLocations(IEnumerable<SimpleLocation> locations)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (_simpleLocationsByZone == null)
			{
				_simpleLocationsByZone = new Dictionary<Vector2i, SimpleLocation>();
			}
			foreach (SimpleLocation location in locations)
			{
				_simpleLocationsByZone[location.ZonePosition] = location;
			}
		}

		public static SimpleLocation FindLocation(Vector3 position)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (((Object)(object)ZoneSystem.instance).IsNull())
			{
				Log.LogWarning("Attempting to retrieve location before ZoneSystem is initialized.");
				return null;
			}
			Vector2i zone = ZoneSystem.instance.GetZone(position);
			if (((Object)(object)ZoneSystem.instance).IsNotNull() && (ZoneSystem.instance.m_locationInstances?.Count ?? 0) > 0 && ZoneSystem.instance.m_locationInstances.TryGetValue(zone, out var value))
			{
				return new SimpleLocation
				{
					LocationName = (value.m_location?.m_prefabName ?? ""),
					Position = value.m_position,
					ZonePosition = zone
				};
			}
			if (_simpleLocationsByZone != null && _simpleLocationsByZone.TryGetValue(zone, out var value2))
			{
				return value2;
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(ZoneSystem))]
	internal static class Patch_ZoneSystem_Start_PrintLocations
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void PrintLocations(ZoneSystem __instance)
		{
			if (__instance.m_locations != null && (bool)ConfigurationManager.GeneralConfig.WriteLocationsToFile)
			{
				LocationsFileWriter.WriteToList(__instance.m_locations);
			}
		}
	}
	public class SimpleLocation
	{
		public Vector3 Position;

		public Vector2i ZonePosition;

		public string LocationName;
	}
	[Serializable]
	internal class SimpleLocationPackage : CompressedPackage
	{
		public string[] LocationNames;

		public SimpleLocationDTO[] Locations;

		protected override void BeforePack()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<Vector2i, LocationInstance> locationInstances = ZoneSystem.instance.m_locationInstances;
			Dictionary<string, ushort> dictionary = new Dictionary<string, ushort>();
			List<string> list = new List<string>();
			List<SimpleLocationDTO> list2 = new List<SimpleLocationDTO>();
			foreach (KeyValuePair<Vector2i, LocationInstance> item in locationInstances)
			{
				string prefabName = item.Value.m_location.m_prefabName;
				ushort num;
				if (dictionary.TryGetValue(item.Value.m_location.m_prefabName, out var value))
				{
					num = value;
				}
				else
				{
					list.Add(prefabName);
					num = (ushort)(list.Count - 1);
					dictionary.Add(prefabName, num);
				}
				list2.Add(new SimpleLocationDTO(item.Key, num));
			}
			LocationNames = list.ToArray();
			Locations = list2.ToArray();
			Log.LogTrace($"Packed {LocationNames.Length} location names");
			Log.LogTrace($"Packed {Locations.Length} locations");
		}

		protected override void AfterUnpack(object responseObject)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: 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)
			if (responseObject is SimpleLocationPackage)
			{
				Log.LogTrace($"Unpacking {LocationNames.Length} location names");
				Log.LogTrace($"Unpacking {Locations.Length} locations");
				List<SimpleLocation> list = new List<SimpleLocation>(Locations.Length);
				SimpleLocationDTO[] locations = Locations;
				Vector2i val = default(Vector2i);
				for (int i = 0; i < locations.Length; i++)
				{
					SimpleLocationDTO simpleLocationDTO = locations[i];
					((Vector2i)(ref val))..ctor(simpleLocationDTO.PositionX, simpleLocationDTO.PositionY);
					list.Add(new SimpleLocation
					{
						LocationName = LocationNames[simpleLocationDTO.Location],
						Position = ZoneSystem.instance.GetZonePos(val),
						ZonePosition = val
					});
				}
				LocationHelper.SetLocations(list);
			}
		}
	}
	[Serializable]
	public struct SimpleLocationDTO
	{
		public int PositionX;

		public int PositionY;

		public ushort Location;

		public SimpleLocationDTO(Vector2i pos, ushort location)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			PositionX = pos.x;
			PositionY = pos.y;
			Location = location;
		}
	}
	[HarmonyPatch(typeof(ZNet))]
	public static class ZoneSystemMultiplayerPatch
	{
		private static bool HaveReceivedLocations;

		static ZoneSystemMultiplayerPatch()
		{
			StateResetter.Subscribe(delegate
			{
				HaveReceivedLocations = false;
			});
		}

		[HarmonyPatch("OnNewConnection")]
		[HarmonyPostfix]
		private static void TransferLocationData(ZNet __instance, ZNetPeer peer)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			if (ZNet.instance.IsServer())
			{
				Log.LogDebug("Registering server RPC for sending location data on request from client.");
				peer.m_rpc.Register("RPC_RequestLocationsDropThat", new Method(RPC_RequestLocationsDropThat));
				return;
			}
			Log.LogDebug("Registering client RPC for receiving location data from server.");
			peer.m_rpc.Register<ZPackage>("RPC_ReceiveLocationsDropThat", (Action<ZRpc, ZPackage>)RPC_ReceiveLocationsDropThat);
			Log.LogDebug("Requesting location data from server.");
			peer.m_rpc.Invoke("RPC_RequestLocationsDropThat", Array.Empty<object>());
		}

		private static void RPC_RequestLocationsDropThat(ZRpc rpc)
		{
			try
			{
				if (!ZNet.instance.IsServer())
				{
					Log.LogWarning("Non-server instance received request for location data. Ignoring request.");
					return;
				}
				Log.LogInfo("Sending location data.");
				if (ZoneSystem.instance.m_locationInstances == null)
				{
					Log.LogWarning("Unable to get locations from zonesystem to send to client.");
					return;
				}
				ZPackage package = new SimpleLocationPackage().Pack();
				DataTransferService.Service.AddToQueue(package, "RPC_ReceiveLocationsDropThat", rpc);
				Log.LogInfo("Finished sending locations package.");
			}
			catch (Exception e)
			{
				Log.LogError("Unexpected error while attempting to create and send locations package from server to client.", e);
			}
		}

		private static void RPC_ReceiveLocationsDropThat(ZRpc rpc, ZPackage pkg)
		{
			Log.LogDebug("Received locations package.");
			try
			{
				if (HaveReceivedLocations)
				{
					Log.LogDebug("Already received locations previously. Skipping.");
					return;
				}
				CompressedPackage.Unpack(pkg);
				HaveReceivedLocations = true;
				Log.LogInfo("Successfully received and unpacked locations package.");
			}
			catch (Exception e)
			{
				Log.LogError("Error while attempting to read received locations package.", e);
			}
		}
	}
}
namespace Valheim.DropThat.Integrations
{
	public static class InstallationManager
	{
		private static bool? _epicLootInstalled;

		private static bool? _rrrInstalled;

		public static bool EpicLootInstalled
		{
			get
			{
				bool valueOrDefault = _epicLootInstalled.GetValueOrDefault();
				if (!_epicLootInstalled.HasValue)
				{
					valueOrDefault = (object)Type.GetType("EpicLoot.EpicLoot, EpicLoot") != null;
					_epicLootInstalled = valueOrDefault;
					return valueOrDefault;
				}
				return valueOrDefault;
			}
		}

		public static bool RRRInstalled
		{
			get
			{
				bool valueOrDefault = _rrrInstalled.GetValueOrDefault();
				if (!_rrrInstalled.HasValue)
				{
					valueOrDefault = (object)Type.GetType("RRRCore.Plugin, RRRCore") != null;
					_rrrInstalled = valueOrDefault;
					return valueOrDefault;
				}
				return valueOrDefault;
			}
		}
	}
}
namespace Valheim.DropThat.Integrations.EpicLootIntegration
{
	internal static class ItemRoller
	{
		internal static bool TryRollMagic(ItemData itemData, Vector3 dropPos, ItemRollParameters parameters)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (!EpicLoot.CanBeMagicItem(itemData))
			{
				return false;
			}
			Rarity rarity = ItemService.RollRarity(parameters);
			switch (rarity)
			{
			case Rarity.None:
				return false;
			case Rarity.Unique:
				return ItemService.TryMakeUnique(itemData, parameters);
			default:
			{
				ItemRarity? val = ItemService.RarityToItemRarity(rarity);
				if (val.HasValue)
				{
					ItemService.MakeMagic(val.Value, itemData, dropPos);
					return true;
				}
				return false;
			}
			}
		}
	}
	internal class ItemRollParameters
	{
		public float RarityWeightNone { get; set; }

		public float RarityWeightMagic { get; set; }

		public float RarityWeightRare { get; set; }

		public float RarityWeightEpic { get; set; }

		public float RarityWeightLegendary { get; set; }

		public float RarityWeightUnique { get; set; }

		public List<string> UniqueIds { get; set; }
	}
	internal static class ItemService
	{
		public static bool TryMakeUnique(ItemData itemData, ItemRollParameters parameters)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			if (parameters.UniqueIds == null || parameters.UniqueIds.Count == 0)
			{
				return false;
			}
			string text = parameters.UniqueIds[Random.Range(0, parameters.UniqueIds.Count)];
			LegendaryInfo val = default(LegendaryInfo);
			if (!UniqueLegendaryHelper.TryGetLegendaryInfo(text, ref val))
			{
				Log.LogWarning("Attempted to roll Epic Loot unique legendary with id '" + text + "' but was unable to find matching info registered in Epic Loot.");
				return false;
			}
			MagicItem val2 = new MagicItem
			{
				Rarity = (ItemRarity)3,
				LegendaryID = val.ID,
				DisplayName = val.Name
			};
			if (!val.Requirements.CheckRequirements(itemData, val2, (string)null))
			{
				Log.LogWarning("Attempted to roll Epic Loot unique legendary with id '" + text + "' but requirements were not met. Skipping.");
				return false;
			}
			if (val.IsSetItem)
			{
				val2.SetID = UniqueLegendaryHelper.GetSetForLegendaryItem(val);
			}
			if ((val.GuaranteedMagicEffects?.Count ?? 0) > 0)
			{
				foreach (GuaranteedMagicEffect guaranteedMagicEffect in val.GuaranteedMagicEffects)
				{
					if (MagicItemEffectDefinitions.AllDefinitions.TryGetValue(guaranteedMagicEffect.Type, out var value))
					{
						MagicItemEffect item = LootRoller.RollEffect(value, (ItemRarity)3, guaranteedMagicEffect.Values);
						val2.Effects.Add(item);
						continue;
					}
					Log.LogWarning("Unable to find a guaranteed Epic Loot magic effect '" + guaranteedMagicEffect.Type + "' while rolling unique legendary with id '" + text + "'. Skipping effect.");
				}
			}
			int num = LootRoller.RollEffectCountPerRarity((ItemRarity)3) - val2.Effects.Count;
			if (num > 0)
			{
				List<MagicItemEffectDefinition> availableEffects = MagicItemEffectDefinitions.GetAvailableEffects(itemData, val2, -1);
				for (int i = 0; i < num; i++)
				{
					MagicItemEffect item2 = LootRoller.RollEffect(RollWeightedEffect(availableEffects, removeSelected: false), (ItemRarity)3, (ValueDef)null);
					val2.Effects.Add(item2);
				}
			}
			ItemExtensions.Data(itemData).GetOrCreate<MagicItemComponent>("").SetMagicItem(val2);
			LootRoller.InitializeMagicItem(itemData);
			return true;
		}

		public static void MakeMagic(ItemRarity rarity, ItemData itemData, Vector3 position)
		{
			//IL_0010: 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)
			MagicItemComponent orCreate = ItemExtensions.Data(itemData).GetOrCreate<MagicItemComponent>("");
			float luckFactor = LootRoller.GetLuckFactor(position);
			MagicItem magicItem = LootRoller.RollMagicItem(rarity, itemData, luckFactor);
			orCreate.SetMagicItem(magicItem);
			LootRoller.InitializeMagicItem(itemData);
		}

		private static MagicItemEffectDefinition RollWeightedEffect(List<MagicItemEffectDefinition> magicEffects, bool removeSelected)
		{
			float num = magicEffects.Sum((MagicItemEffectDefinition x) => x.SelectionWeight);
			float num2 = Random.Range(0f, num);
			float num3 = 0f;
			for (int i = 0; i < magicEffects.Count; i++)
			{
				MagicItemEffectDefinition val = magicEffects[i];
				num3 += val.SelectionWeight;
				if (num2 <= num3)
				{
					if (removeSelected)
					{
						magicEffects.RemoveAt(i);
					}
					return val;
				}
			}
			return magicEffects.Last();
		}

		public static Rarity RollRarity(ItemRollParameters parameters)
		{
			float num = parameters.RarityWeightNone + parameters.RarityWeightMagic + parameters.RarityWeightRare + parameters.RarityWeightEpic + parameters.RarityWeightLegendary + parameters.RarityWeightUnique;
			float num2 = Random.Range(0f, num);
			double num3 = 0.0;
			num3 += (double)parameters.RarityWeightUnique;
			if (parameters.RarityWeightUnique > 0f && (double)num2 <= num3)
			{
				return Rarity.Unique;
			}
			num3 += (double)parameters.RarityWeightLegendary;
			if (parameters.RarityWeightLegendary > 0f && (double)num2 <= num3)
			{
				return Rarity.Legendary;
			}
			num3 += (double)parameters.RarityWeightEpic;
			if (parameters.RarityWeightEpic > 0f && (double)num2 <= num3)
			{
				return Rarity.Epic;
			}
			num3 += (double)parameters.RarityWeightRare;
			if (parameters.RarityWeightRare > 0f && (double)num2 <= num3)
			{
				return Rarity.Rare;
			}
			num3 += (double)parameters.RarityWeightMagic;
			if (parameters.RarityWeightMagic > 0f && (double)num2 <= num3)
			{
				return Rarity.Magic;
			}
			return Rarity.None;
		}

		public static ItemRarity? RarityToItemRarity(Rarity rarity)
		{
			return rarity switch
			{
				Rarity.None => null, 
				Rarity.Magic => (ItemRarity)0, 
				Rarity.Rare => (ItemRarity)1, 
				Rarity.Epic => (ItemRarity)2, 
				Rarity.Legendary => (ItemRarity)3, 
				Rarity.Unique => (ItemRarity)3, 
				_ => null, 
			};
		}
	}
	internal enum Rarity
	{
		None,
		Magic,
		Rare,
		Epic,
		Legendary,
		Unique
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem
{
	public class DropModificationContext
	{
		public class CachedComponent<T> where T : Component
		{
			private T Component;

			private GameObject Source;

			private bool HasChecked;

			public CachedComponent(GameObject gameObject)
			{
				Source = gameObject;
			}

			public static implicit operator T(CachedComponent<T> cache)
			{
				if (!cache.HasChecked)
				{
					cache.Component = cache.Source.GetComponent<T>();
					cache.HasChecked = true;
				}
				return cache.Component;
			}
		}

		public GameObject Drop { get; }

		public DropTemplate Template { get; }

		public CachedComponent<ItemDrop> ItemDrop { get; }

		public DropModificationContext(GameObject drop, DropTemplate template)
		{
			Drop = drop;
			Template = template;
			ItemDrop = new CachedComponent<ItemDrop>(drop);
		}
	}
	public class DropSourceTemplateLink
	{
		public GameObject Source;

		public DropTableEntityConfiguration EntityConfig;
	}
	public class DropTemplate
	{
		public DropTableEntityConfiguration EntityConfig { get; set; }

		public DropTableItemConfiguration Config { get; set; }

		public List<IDropTableCondition> Conditions { get; set; } = new List<IDropTableCondition>();


		public List<IDropTableModifier> Modifiers { get; set; } = new List<IDropTableModifier>();


		public DropData Drop { get; set; }
	}
	internal static class DropTableManager
	{
		private static readonly ItemData[] Item = (ItemData[])(object)new ItemData[1];

		public static List<ItemData> GetItemDrops(DropTable dropTable, DropSourceTemplateLink context)
		{
			return GetDrops(dropTable, context, ConvertTemplateToItem);
		}

		public static List<GameObject> GetDrops(DropTable dropTable, DropSourceTemplateLink context)
		{
			return GetDrops(dropTable, context, ConvertTemplateToDrop);
		}

		private static List<T> GetDrops<T>(DropTable dropTable, DropSourceTemplateLink context, Func<DropTemplate, IEnumerable<T>> DropConverter) where T : class
		{
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			List<DropTemplate> possibleDrops = DropConfigManager.GetPossibleDrops(context, dropTable);
			if (possibleDrops.Count == 0)
			{
				return new List<T>(0);
			}
			DropTableEntityConfiguration entityConfig = context.EntityConfig;
			if ((entityConfig == null) ? (Random.value > dropTable.m_dropChance) : (Random.value > (float)entityConfig.SetDropChance / 100f))
			{
				return new List<T>(0);
			}
			List<DropTemplate> templates = new List<DropTemplate>(possibleDrops);
			templates = DropConditionManager.Filter(context, templates);
			float num = templates.Sum((DropTemplate x) => x.Drop.m_weight);
			int num2 = ((entityConfig == null) ? Random.Range(dropTable.m_dropMin, dropTable.m_dropMax + 1) : Random.Range((int)entityConfig.SetDropMin, (int)entityConfig.SetDropMax + 1));
			bool flag = ((entityConfig == null) ? dropTable.m_oneOfEach : ((bool)entityConfig.SetDropOnlyOnce));
			List<T> list = new List<T>(num2);
			for (int i = 0; i < num2; i++)
			{
				float num3 = Random.Range(0f, num);
				float num4 = 0f;
				try
				{
					bool flag2 = false;
					foreach (DropTemplate item in templates)
					{
						num4 += item.Drop.m_weight;
						if (num3 <= num4)
						{
							list.AddRange(DropConverter(item));
							if (flag)
							{
								templates.Remove(item);
								num -= item.Drop.m_weight;
							}
							flag2 = true;
							break;
						}
					}
					if (!flag2 && templates.Count > 0)
					{
						list.AddRange(DropConverter(templates.First()));
					}
				}
				catch (Exception e)
				{
					Log.LogWarning("Error while rolling drop. Skipping roll\n", e);
				}
			}
			return list;
		}

		private static IEnumerable<ItemData> ConvertTemplateToItem(DropTemplate template)
		{
			//IL_0001: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ItemData val = template.Drop.m_item.GetComponent<ItemDrop>().m_itemData.Clone();
				int num = Math.Max(1, template.Drop.m_stackMin);
				int num2 = Math.Min(val.m_shared.m_maxStackSize, template.Drop.m_stackMax) + 1;
				val.m_dropPrefab = template.Drop.m_item.Wrap();
				val.m_stack = Random.Range(num, num2);
				ConfigurationEntry<int> configurationEntry = template.Config?.SetQualityLevel;
				val.m_quality = ((configurationEntry == null) ? 1 : ((int)configurationEntry));
				ConfigurationEntry<float> configurationEntry2 = template.Config?.SetDurability;
				val.m_durability = ((((configurationEntry2 != null) ? ((float)configurationEntry2) : (-1f)) >= 0f) ? ((float)template.Config.SetDurability) : val.m_durability);
				DropTemplateCache.RegisterTemplate(val, template);
				DropTemplateCache.RegisterTemplate(val.m_dropPrefab, template);
				Item[0] = val;
				return Item;
			}
			catch (Exception e)
			{
				Log.LogError("Error while attempting to prepare new item data", e);
				return Enumerable.Empty<ItemData>();
			}
		}

		private static IEnumerable<GameObject> ConvertTemplateToDrop(DropTemplate template)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = template.Drop.m_item.Wrap();
			DropTemplateCache.RegisterTemplate(val, template);
			int num = Math.Max(1, template.Drop.m_stackMin);
			int num2 = template.Drop.m_stackMax + 1;
			int num3 = Random.Range(num, num2);
			GameObject[] array = (GameObject[])(object)new GameObject[num3];
			for (int i = 0; i < num3; i++)
			{
				array[i] = val;
			}
			return array;
		}
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Wrapper
{
	internal class WrapperCache
	{
		public GameObject Wrapper { get; set; }

		public GameObject Wrapped { get; set; }

		public bool Unwrapped { get; set; }

		internal static ManagedCache<WrapperCache> Cache { get; } = new ManagedCache<WrapperCache>();


		internal static WrapperCache Get(GameObject go)
		{
			if (Cache.TryGet((Object)(object)go, out var value))
			{
				return value;
			}
			return null;
		}

		internal static void SetStatus(GameObject wrapper, bool unwrapped = false)
		{
			if (Cache.TryGet((Object)(object)wrapper, out var value))
			{
				value.Unwrapped = unwrapped;
			}
		}

		internal static void Set(GameObject wrapper, GameObject wrapped, bool unwrapped = false)
		{
			Cache.Set((Object)(object)wrapper, new WrapperCache
			{
				Wrapper = wrapper,
				Wrapped = wrapped,
				Unwrapped = unwrapped
			});
		}
	}
	public class WrapperComponent : MonoBehaviour
	{
		public void Start()
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: 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)
			try
			{
				WrapperCache wrapperCache = WrapperCache.Get(((Component)this).gameObject);
				if ((wrapperCache == null || !wrapperCache.Unwrapped) && wrapperCache == null)
				{
					string cleanedName = ((Object)(object)((Component)this).gameObject).GetCleanedName();
					GameObject prefab = ZNetScene.instance.GetPrefab(cleanedName);
					if (((Object)(object)prefab).IsNotNull())
					{
						Vector3 position = ((Component)this).gameObject.transform.position;
						Object.Instantiate<GameObject>(prefab, position, ((Component)this).gameObject.transform.rotation);
					}
				}
			}
			catch (Exception e)
			{
				Log.LogError("Error during Wrapper.Start", e);
			}
			finally
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}
	}
	public static class WrapperGameObjectExtensions
	{
		public static GameObject Wrap(this GameObject gameObject)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_0025: Expected O, but got Unknown
			if (WrapperCache.Get(gameObject) != null)
			{
				return gameObject;
			}
			GameObject val = new GameObject(((Object)gameObject).name);
			val.AddComponent<WrapperComponent>();
			WrapperCache.Set(val, gameObject);
			return val;
		}

		public static GameObject Unwrap(this GameObject gameObject)
		{
			if ((Object)(object)gameObject == (Object)null || !Object.op_Implicit((Object)(object)gameObject))
			{
				return gameObject;
			}
			WrapperCache wrapperCache = WrapperCache.Get(gameObject);
			if (wrapperCache != null)
			{
				wrapperCache.Unwrapped = true;
				return wrapperCache.Wrapped;
			}
			return gameObject;
		}
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Patches
{
	internal static class Patch_DropSourceLink
	{
		[HarmonyPatch(typeof(Container))]
		internal static class Patch_Container_Awake_InitDropContext
		{
			[HarmonyPatch("Awake")]
			[HarmonyPrefix]
			private static void SetLink(Container __instance)
			{
				CreateLink(__instance.m_defaultItems, ((Component)__instance).gameObject);
			}
		}

		[HarmonyPatch(typeof(DropOnDestroyed))]
		internal static class Patch_DropOnDestroyed_Awake_InitDropContext
		{
			[HarmonyPatch("Awake")]
			[HarmonyPostfix]
			private static void SetLink(DropOnDestroyed __instance)
			{
				CreateLink(__instance.m_dropWhenDestroyed, ((Component)__instance).gameObject);
			}
		}

		[HarmonyPatch(typeof(LootSpawner))]
		internal static class Patch_LootSpawner_Awake_InitDropContext
		{
			[HarmonyPatch("Awake")]
			[HarmonyPostfix]
			private static void SetLink(LootSpawner __instance)
			{
				CreateLink(__instance.m_items, ((Component)__instance).gameObject);
			}
		}

		[HarmonyPatch(typeof(TreeBase))]
		internal static class Patch_TreeBase_Awake_InitDropContext
		{
			[HarmonyPatch("Awake")]
			[HarmonyPostfix]
			private static void SetLink(TreeBase __instance)
			{
				CreateLink(__instance.m_dropWhenDestroyed, ((Component)__instance).gameObject);
			}
		}

		[HarmonyPatch(typeof(TreeLog))]
		internal static class Patch_TreeLog_Awake_InitDropContext
		{
			[HarmonyPatch("Awake")]
			[HarmonyPostfix]
			private static void SetLink(TreeLog __instance)
			{
				CreateLink(__instance.m_dropWhenDestroyed, ((Component)__instance).gameObject);
			}
		}

		[HarmonyPatch(typeof(MineRock))]
		internal static class Patch_MineRock_Awake_InitDropContext
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void SetLink(MineRock __instance)
			{
				CreateLink(__instance.m_dropItems, ((Component)__instance).gameObject);
			}
		}

		[HarmonyPatch(typeof(MineRock5))]
		internal static class Patch_MineRock5_Awake_InitDropContext
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void SetLink(MineRock5 __instance)
			{
				CreateLink(__instance.m_dropItems, ((Component)__instance).gameObject);
			}
		}

		private static void CreateLink(DropTable dropTable, GameObject source)
		{
			try
			{
				if (dropTable == null || source == null)
				{
					return;
				}
				DropSourceTemplateLink dropSourceTemplateLink = new DropSourceTemplateLink
				{
					Source = source
				};
				string cleanedName = ((Object)(object)source).GetCleanedName();
				if (string.IsNullOrWhiteSpace(cleanedName))
				{
					return;
				}
				if (ConfigurationManager.DropTableConfigs == null)
				{
					Log.LogDebug($"{source} woke before configs were loaded. Skipping config for '{source}'");
					return;
				}
				if (ConfigurationManager.DropTableConfigs.TryGet(cleanedName, out var value))
				{
					dropSourceTemplateLink.EntityConfig = value;
				}
				DropLinkCache.SetLink(dropTable, dropSourceTemplateLink);
			}
			catch (Exception e)
			{
				Log.LogError("Error while attempting to create associate drop table for object with config.", e);
			}
		}
	}
	[HarmonyPatch(typeof(DropTable))]
	internal static class Patch_DropTable_GetDrops_Overhaul
	{
		[HarmonyPatch("GetDropListItems")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> DropListItemsOverhaul(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			Label label = default(Label);
			return new CodeMatcher(instructions, generator).Start().InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Ldarg_0, (object)null)
			}).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patch_DropTable_GetDrops_Overhaul), "GetDropListItems", (Type[])null, (Type[])null))
			})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ret, (object)null)
				})
				.CreateLabel(ref label)
				.Start()
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patch_DropTable_GetDrops_Overhaul), "UseOriginal", (Type[])null, (Type[])null))
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Brtrue, (object)label)
				})
				.InstructionEnumeration();
		}

		[HarmonyPatch("GetDropList", new Type[] { typeof(int) })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> DropListOverhaul(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			Label label = default(Label);
			return new CodeMatcher(instructions, generator).Start().InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Ldarg_0, (object)null)
			}).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Ldarg_1, (object)null)
			})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patch_DropTable_GetDrops_Overhaul), "GetDropList", (Type[])null, (Type[])null))
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ret, (object)null)
				})
				.CreateLabel(ref label)
				.Start()
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patch_DropTable_GetDrops_Overhaul), "UseOriginal", (Type[])null, (Type[])null))
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Brtrue, (object)label)
				})
				.InstructionEnumeration();
		}

		private static bool UseOriginal(DropTable dropTable)
		{
			return DropLinkCache.GetLink(dropTable)?.EntityConfig == null;
		}

		private static List<ItemData> GetDropListItems(DropTable dropTable)
		{
			try
			{
				DropSourceTemplateLink link = DropLinkCache.GetLink(dropTable);
				if (DropConfigManager.GetPossibleDrops(link, dropTable).Count == 0)
				{
					return new List<ItemData>(0);
				}
				return DropTableManager.GetItemDrops(dropTable, link);
			}
			catch (Exception e)
			{
				Log.LogError("Error during calculation of item drops", e);
				return new List<ItemData>(0);
			}
		}

		private static List<GameObject> GetDropList(DropTable dropTable, int dropCount)
		{
			try
			{
				DropSourceTemplateLink link = DropLinkCache.GetLink(dropTable);
				if (DropConfigManager.GetPossibleDrops(link, dropTable).Count == 0)
				{
					return new List<GameObject>(0);
				}
				return DropTableManager.GetDrops(dropTable, link);
			}
			catch (Exception e)
			{
				Log.LogError("Error during calculation of item drops", e);
				return new List<GameObject>(0);
			}
		}
	}
	[HarmonyPatch(typeof(MineRock5))]
	internal static class Patch_MineRock5_Fix_Naming
	{
		private static string _originalPrefabName { get; set; }

		[HarmonyPatch("Start")]
		private static void Prefix(MineRock5 __instance)
		{
			if (((Object)(object)__instance).IsNotNull() && ((Object)(object)((Component)__instance).gameObject).IsNotNull())
			{
				_originalPrefabName = ((Object)((Component)__instance).gameObject).name;
			}
		}

		[HarmonyPatch("Start")]
		private static void Postfix(MineRock5 __instance)
		{
			if (((Object)(object)__instance).IsNotNull() && ((Object)(object)((Component)__instance).gameObject).IsNotNull() && _originalPrefabName != null)
			{
				((Object)((Component)__instance).gameObject).name = _originalPrefabName;
			}
		}
	}
	internal static class Patch_OnDrop
	{
		[HarmonyPatch(typeof(Container))]
		internal static class Patch_Container_AddDefaultItems
		{
			[HarmonyPatch("AddDefaultItems")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> InsertItemManagement(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Expected O, but got Unknown
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Expected O, but got Unknown
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Expected O, but got Unknown
				return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((OpCode?)OpCodes.Callvirt, (object)AddItemToInventory, (string)null)
				}).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null)
				}).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Patch_OnDrop), "ModifyContainerItem", (Type[])null, (Type[])null))
				})
					.InstructionEnumeration();
			}
		}

		[HarmonyPatch(typeof(DropOnDestroyed))]
		internal static class Patch_DropOnDestroyed_OnDestroyed
		{
			[HarmonyPatch("OnDestroyed")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> InsertDropManagement(IEnumerable<CodeInstruction> instructions)
			{
				return instructions.InsertDropManagementInstructions();
			}
		}

		[HarmonyPatch(typeof(LootSpawner))]
		internal static class Patch_LootSpawner_UpdateSpawner
		{
			[HarmonyPatch("UpdateSpawner")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> InsertDropManagement(IEnumerable<CodeInstruction> instructions)
			{
				return instructions.InsertDropManagementInstructions();
			}
		}

		[HarmonyPatch(typeof(TreeLog))]
		internal static class Patch_TreeLog_Destroy
		{
			[HarmonyPatch("Destroy")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> InsertDropManagement(IEnumerable<CodeInstruction> instructions)
			{
				return instructions.InsertDropManagementInstructions();
			}
		}

		[HarmonyPatch(typeof(TreeBase))]
		internal static class Patch_TreeBase_RPC_Damage
		{
			[HarmonyPatch("RPC_Damage")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> InsertDropManagement(IEnumerable<CodeInstruction> instructions)
			{
				return instructions.InsertDropManagementInstructions();
			}
		}

		[HarmonyPatch(typeof(MineRock))]
		internal static class Patch_MineRock_RPC_Hit
		{
			[HarmonyPatch("RPC_Hit")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> InsertDropManagement(IEnumerable<CodeInstruction> instructions)
			{
				return instructions.InsertDropManagementInstructions();
			}
		}

		[HarmonyPatch(typeof(MineRock5))]
		internal static class Patch_MineRock5_DamageArea
		{
			[HarmonyPatch("DamageArea")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> InsertDropManagement(IEnumerable<CodeInstruction> instructions)
			{
				return instructions.InsertDropManagementInstructions();
			}
		}

		private static MethodInfo DropInstantiation = ReflectionUtils.InstantiateGameObjectMethod;

		private static MethodInfo AddItemToInventory = AccessTools.Method(typeof(Inventory), "AddItem", new Type[1] { typeof(ItemData) }, (Type[])null);

		private static MethodInfo UnwrapDropMethod = AccessTools.Method(typeof(Patch_OnDrop), "UnwrapDrop", (Type[])null, (Type[])null);

		private static MethodInfo ModifyDropMethod = AccessTools.Method(typeof(Patch_OnDrop), "ModifyDrop", (Type[])null, (Type[])null);

		private static GameObject _currentWrapped;

		private static ItemData _currentItem;

		private static IEnumerable<CodeInstruction> InsertDropManagementInstructions(this IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)DropInstantiation, (string)null)
			}).Advance(-2).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Call, (object)UnwrapDropMethod)
			})
				.MatchForward(true, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((OpCode?)OpCodes.Call, (object)DropInstantiation, (string)null)
				})
				.Advance(1)
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Dup, (object)null)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)ModifyDropMethod)
				})
				.InstructionEnumeration();
		}

		private static GameObject UnwrapDrop(GameObject wrappedDrop)
		{
			try
			{
				_currentWrapped = wrappedDrop;
				return wrappedDrop.Unwrap();
			}
			catch (Exception e)
			{
				Log.LogError("Error while attempting to unwrap drop", e);
				return wrappedDrop;
			}
		}

		private static void ModifyDrop(GameObject drop)
		{
			try
			{
				DropTemplate template = DropTemplateCache.GetTemplate(_currentWrapped);
				if (template == null)
				{
					return;
				}
				DropModificationContext context = new DropModificationContext(drop, template);
				foreach (IDropTableModifier modifier in template.Modifiers)
				{
					try
					{
						modifier.Modify(context);
					}
					catch (Exception e)
					{
						Log.LogError($"Error while attempting to apply modifier '{modifier.GetType().Name}' to drop '{drop}'. Skipping modifier.", e);
					}
				}
			}
			catch (Exception e2)
			{
				Log.LogError($"Error while preparing to modify drop '{drop}'. Skipping modifiers.", e2);
			}
			_currentWrapped = null;
		}

		private static ItemData ModifyContainerItem(ItemData item, Container container)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				item.m_dropPrefab = item.m_dropPrefab.Unwrap();
				DropTemplate template = DropTemplateCache.GetTemplate(item);
				if (template == null)
				{
					return item;
				}
				foreach (IDropTableModifier modifier in template.Modifiers)
				{
					try
					{
						modifier.Modify(ref item, template, ((Component)container).transform.position);
					}
					catch (Exception e)
					{
						Log.LogError("Error while attempting to apply modifier '" + modifier.GetType().Name + "' to drop '" + ((Object)item.m_dropPrefab).name + "'. Skipping modifier.", e);
					}
				}
			}
			catch (Exception e2)
			{
				Log.LogError("Error while preparing to modify drop '" + ((Object)item.m_dropPrefab).name + "'. Skipping modifiers.", e2);
			}
			return item;
		}

		private static void RememberCurrentItem(ItemData itemData)
		{
			_currentItem = itemData;
		}
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Modifiers
{
	public interface IDropTableModifier
	{
		void Modify(DropModificationContext context);

		void Modify(ref ItemData drop, DropTemplate template, Vector3 position);
	}
	public class ModifierSetDurability : IDropTableModifier
	{
		private static ModifierSetDurability _instance;

		public static ModifierSetDurability Instance => _instance ?? (_instance = new ModifierSetDurability());

		public void Modify(DropModificationContext context)
		{
			ConfigurationEntry<float> configurationEntry = context.Template?.Config?.SetDurability;
			float num = ((configurationEntry != null) ? ((float)configurationEntry) : (-1f));
			if (!(num < 0f))
			{
				ItemDrop val = context.ItemDrop;
				if (val != null)
				{
					Log.LogTrace($"Setting durability of item '{context.Drop}' to {num}");
					val.m_itemData.m_durability = num;
				}
			}
		}

		public void Modify(ref ItemData drop, DropTemplate template, Vector3 position)
		{
			ConfigurationEntry<float> configurationEntry = template.Config?.SetDurability;
			float num = ((configurationEntry != null) ? ((float)configurationEntry) : (-1f));
			if (!(num < 0f))
			{
				drop.m_durability = num;
			}
		}
	}
	public class ModifierSetQualityLevel : IDropTableModifier
	{
		private static ModifierSetQualityLevel _instance;

		public static ModifierSetQualityLevel Instance => _instance ?? (_instance = new ModifierSetQualityLevel());

		public void Modify(DropModificationContext context)
		{
			ConfigurationEntry<int> configurationEntry = context.Template?.Config?.SetQualityLevel;
			int num = ((configurationEntry != null) ? ((int)configurationEntry) : 0);
			if (num > 0)
			{
				ItemDrop val = context.ItemDrop;
				if (val != null)
				{
					Log.LogTrace($"Setting level of item '{context.Drop}' to {num}");
					val.m_itemData.m_quality = num;
				}
			}
		}

		public void Modify(ref ItemData drop, DropTemplate template, Vector3 position)
		{
			ConfigurationEntry<int> configurationEntry = template.Config?.SetQualityLevel;
			int num = ((configurationEntry != null) ? ((int)configurationEntry) : 0);
			if (num > 0)
			{
				drop.m_quality = num;
			}
		}
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Modifiers.ModSpecific.ModEpicLoot
{
	internal class ModifierMagicItem : IDropTableModifier
	{
		private static ModifierMagicItem _instance;

		public static ModifierMagicItem Instance => _instance ?? (_instance = new ModifierMagicItem());

		public void Modify(DropModificationContext context)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (!InstallationManager.EpicLootInstalled)
			{
				return;
			}
			EpicLootItemConfiguration config = GetConfig(context.Template);
			if (config != null)
			{
				ItemDrop val = context.ItemDrop;
				if (!((Object)(object)val).IsNull() && ItemRoller.TryRollMagic(val.m_itemData, ((Component)val).transform.position, new ItemRollParameters
				{
					RarityWeightNone = config.RarityWeightNone,
					RarityWeightMagic = config.RarityWeightMagic,
					RarityWeightRare = config.RarityWeightRare,
					RarityWeightEpic = config.RarityWeightEpic,
					RarityWeightLegendary = config.RarityWeightLegendary,
					RarityWeightUnique = config.RarityWeightUnique,
					UniqueIds = config.UniqueIDs.Value.SplitByComma()
				}))
				{
					val.Save();
				}
			}
		}

		public void Modify(ref ItemData drop, DropTemplate template, Vector3 position)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (InstallationManager.EpicLootInstalled)
			{
				EpicLootItemConfiguration config = GetConfig(template);
				if (config != null && drop != null)
				{
					ItemRoller.TryRollMagic(drop, position, new ItemRollParameters
					{
						RarityWeightNone = config.RarityWeightNone,
						RarityWeightMagic = config.RarityWeightMagic,
						RarityWeightRare = config.RarityWeightRare,
						RarityWeightEpic = config.RarityWeightEpic,
						RarityWeightLegendary = config.RarityWeightLegendary,
						RarityWeightUnique = config.RarityWeightUnique,
						UniqueIds = config.UniqueIDs.Value.SplitByComma()
					});
				}
			}
		}

		private EpicLootItemConfiguration GetConfig(DropTemplate template)
		{
			if (template == null)
			{
				return null;
			}
			if (template.Config.TryGet("EpicLoot", out var value) && value is EpicLootItemConfiguration result)
			{
				return result;
			}
			return null;
		}
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Managers
{
	internal static class DropConditionManager
	{
		public static List<DropTemplate> Filter(DropSourceTemplateLink context, List<DropTemplate> templates)
		{
			return templates.Where(delegate(DropTemplate template)
			{
				try
				{
					if ((template?.Conditions?.Count).GetValueOrDefault() == 0)
					{
						return true;
					}
					return !template.Conditions.Any(delegate(IDropTableCondition x)
					{
						try
						{
							return x?.ShouldFilter(context, template) ?? true;
						}
						catch (Exception e2)
						{
							Log.LogError($"Error while attempting to check condition '{x?.GetType()?.Name}' for '{template.Config.PrefabName}'. Condition will be ignored", e2);
							return true;
						}
					});
				}
				catch (Exception e)
				{
					Log.LogError($"Error while attempting to check conditions for '{template?.Config?.PrefabName}'. Conditions will be ignored", e);
					return true;
				}
			}).ToList();
		}
	}
	internal static class DropConfigManager
	{
		private static Dictionary<int, List<DropTemplate>> TemplateCache { get; set; }

		private static GeneralConfiguration GeneralConfig => ConfigurationManager.GeneralConfig;

		static DropConfigManager()
		{
			TemplateCache = new Dictionary<int, List<DropTemplate>>();
			StateResetter.Subscribe(delegate
			{
				TemplateCache = new Dictionary<int, List<DropTemplate>>();
			});
		}

		public static List<DropTemplate> GetPossibleDrops(DropSourceTemplateLink context, DropTable dropTable)
		{
			int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)context.Source).name);
			if (TemplateCache.TryGetValue(stableHashCode, out var value))
			{
				return new List<DropTemplate>(value);
			}
			List<DropTemplate> list = PrepareDrops(context, dropTable);
			TemplateCache[stableHashCode] = new List<DropTemplate>(list);
			return list;
		}

		private static List<DropTemplate> PrepareDrops(DropSourceTemplateLink context, DropTable dropTable)
		{
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			List<DropTemplate> list = new List<DropTemplate>();
			string text = context.EntityConfig?.UseDropList?.Value;
			DropTableListConfiguration dropTableListConfiguration = null;
			if (!string.IsNullOrWhiteSpace(text) && ConfigurationManager.DropTableLists != null && ConfigurationManager.DropTableLists.TryGet(text, out var value))
			{
				dropTableListConfiguration = value;
			}
			bool flag = false;
			if ((bool)GeneralConfig.ClearAllExistingDropTables)
			{
				goto IL_0133;
			}
			if ((bool)GeneralConfig.ClearAllExistingDropTablesWhenModified)
			{
				DropTableEntityConfiguration entityConfig = context.EntityConfig;
				if ((entityConfig != null && entityConfig.Subsections?.Any((KeyValuePair<string, DropTableItemConfiguration> x) => x.Value.EnableConfig) == true) || (dropTableListConfiguration != null && dropTableListConfiguration.Subsections?.Any((KeyValuePair<string, DropTableItemConfiguration> x) => x.Value.EnableConfig) == true))
				{
					goto IL_0133;
				}
			}
			goto IL_0136;
			IL_0133:
			flag = true;
			goto IL_0136;
			IL_0136:
			if (!flag)
			{
				foreach (DropData drop in dropTable.m_drops)
				{
					if (!(drop.m_weight <= 0f))
					{
						list.Add(new DropTemplate
						{
							Drop = drop
						});
					}
				}
			}
			if (context.EntityConfig == null)
			{
				return list;
			}
			foreach (DropTableItemConfiguration item in MergeAndOrder(dropTableListConfiguration, context.EntityConfig))
			{
				InsertDrop(list, item, context.EntityConfig);
			}
			return list;
		}

		private static void InsertDrop(List<DropTemplate> drops, DropTableItemConfiguration itemConfig, DropTableEntityConfiguration entityConfig)
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			if (!itemConfig.EnableConfig || (float)itemConfig.SetTemplateWeight <= 0f)
			{
				return;
			}
			GameObject val = ObjectDB.instance.GetItemPrefab(itemConfig.PrefabName.Value);
			if (((Object)(object)val).IsNull())
			{
				val = ZNetScene.instance.GetPrefab(itemConfig.PrefabName.Value);
			}
			if (((Object)(object)val).IsNull())
			{
				Log.LogWarning("Unable to find prefab '" + itemConfig.PrefabName.Value + "' for '" + itemConfig.SectionKey + "'.");
				return;
			}
			DropTemplate item = new DropTemplate
			{
				Drop = new DropData
				{
					m_item = val,
					m_weight = itemConfig.SetTemplateWeight,
					m_stackMin = itemConfig.SetAmountMin,
					m_stackMax = itemConfig.SetAmountMax
				},
				Conditions = ExtractConditions(itemConfig),
				Modifiers = ExtractModifiers(itemConfig),
				Config = itemConfig,
				EntityConfig = entityConfig
			};
			if ((bool)GeneralConfig.AlwaysAppendCharacterDrops)
			{
				drops.Add(item);
				return;
			}
			int index = itemConfig.Index;
			if (drops.Count > index && index >= 0)
			{
				drops.RemoveAt(index);
			}
			if (index >= 0 && index <= drops.Count)
			{
				drops.Insert(index, item);
			}
			else
			{
				drops.Add(item);
			}
		}

		private static List<IDropTableCondition> ExtractConditions(DropTableItemConfiguration config)
		{
			List<IDropTableCondition> list = new List<IDropTableCondition>();
			list.AddNullSafe(Valheim.DropThat.Drop.DropTableSystem.Conditions.ConditionBiome.Instance);
			list.AddNullSafe(ConditionAltitude.Instance);
			list.AddNullSafe(Valheim.DropThat.Drop.DropTableSystem.Conditions.ConditionDaytime.Instance);
			list.AddNullSafe(Valheim.DropThat.Drop.DropTableSystem.Conditions.ConditionEnvironments.Instance);
			list.AddNullSafe(ConditionGlobalKeysRequired.Instance);
			list.AddNullSafe(Valheim.DropThat.Drop.DropTableSystem.Conditions.ConditionLocation.Instance);
			list.AddNullSafe(Valheim.DropThat.Drop.DropTableSystem.Conditions.ConditionDistanceToCenter.Instance);
			list.AddNullSafe(Valheim.DropThat.Drop.DropTableSystem.Conditions.ModSpecific.ConditionLoaderCLLC.ConditionWorldLevel);
			return list;
		}

		private static List<IDropTableModifier> ExtractModifiers(DropTableItemConfiguration config)
		{
			List<IDropTableModifier> list = new List<IDropTableModifier>();
			list.AddNullSafe(Valheim.DropThat.Drop.DropTableSystem.Modifiers.ModifierSetQualityLevel.Instance);
			if (InstallationManager.EpicLootInstalled && config.TryGet("EpicLoot", out var value) && value is EpicLootItemConfiguration)
			{
				list.AddNullSafe(Valheim.DropThat.Drop.DropTableSystem.Modifiers.ModSpecific.ModEpicLoot.ModifierMagicItem.Instance);
			}
			list.AddNullSafe(Valheim.DropThat.Drop.DropTableSystem.Modifiers.ModifierSetDurability.Instance);
			return list;
		}

		private static IEnumerable<DropTableItemConfiguration> MergeAndOrder(DropTableListConfiguration list, DropTableEntityConfiguration entity)
		{
			Dictionary<int, DropTableItemConfiguration> dictionary = new Dictionary<int, DropTableItemConfiguration>();
			if (list != null)
			{
				foreach (DropTableItemConfiguration value in list.Subsections.Values)
				{
					if ((bool)value.EnableConfig)
					{
						dictionary[value.Index] = value;
					}
				}
			}
			if (entity != null)
			{
				foreach (DropTableItemConfiguration value2 in entity.Subsections.Values)
				{
					if ((bool)value2.EnableConfig)
					{
						dictionary[value2.Index] = value2;
					}
				}
			}
			return dictionary.Values.OrderBy((DropTableItemConfiguration x) => x.Index);
		}
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Debug
{
	[HarmonyPatch(typeof(DungeonDB))]
	internal static class Patch_DungeonDB_Start
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void WriteDropTableData()
		{
			if ((bool)ConfigurationManager.GeneralConfig?.WriteDropTablesToFiles)
			{
				DropTableDataWriter.PrintDungeonDropTables();
			}
		}
	}
	[HarmonyPatch(typeof(ZoneSystem))]
	internal static class Patch_ZoneSystem_Start
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void WriteDropTableData()
		{
			if ((bool)ConfigurationManager.GeneralConfig?.WriteDropTablesToFiles)
			{
				DropTableDataWriter.PrintPrefabDropTables();
				DropTableDataWriter.PrintLocationDropTables();
			}
		}
	}
	internal static class DropTableDataWriter
	{
		private static string GetData(MonoBehaviour source, DropTable dropTable, string[] additionalHeaders)
		{
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			string cleanedName = ((Object)(object)((Component)source).gameObject).GetCleanedName();
			if (string.IsNullOrWhiteSpace(cleanedName))
			{
				return "";
			}
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("## DropTable Source: " + ((object)source).GetType().Name + "; " + GeneralExtensions.Join<string>((IEnumerable<string>)additionalHeaders, (Func<string, string>)null, "; "));
			stringBuilder.AppendLine("[" + cleanedName + "]");
			stringBuilder.AppendLine("SetDropChance=" + (dropTable.m_dropChance * 100f).ToString(CultureInfo.InvariantCulture));
			stringBuilder.AppendLine(string.Format("{0}={1}", "SetDropOnlyOnce", dropTable.m_oneOfEach));
			stringBuilder.AppendLine(string.Format("{0}={1}", "SetDropMin", dropTable.m_dropMin));
			stringBuilder.AppendLine(string.Format("{0}={1}", "SetDropMax", dropTable.m_dropMax));
			for (int i = 0; i < dropTable.m_drops.Count; i++)
			{
				DropData val = dropTable.m_drops[i];
				stringBuilder.AppendLine();
				stringBuilder.AppendLine($"[{cleanedName}.{i}]");
				stringBuilder.AppendLine("PrefabName=" + (((Object)(object)val.m_item).IsNotNull() ? ((Object)val.m_item).name : ""));
				stringBuilder.AppendLine("SetTemplateWeight=" + val.m_weight.ToString(CultureInfo.InvariantCulture));
				stringBuilder.AppendLine(string.Format("{0}={1}", "SetAmountMin", val.m_stackMin));
				stringBuilder.AppendLine(string.Format("{0}={1}", "SetAmountMax", val.m_stackMax));
			}
			return stringBuilder.ToString();
		}

		internal static void PrintDungeonDropTables()
		{
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			IOrderedEnumerable<ZoneLocation> orderedEnumerable = from x in ZoneSystem.instance.m_locations
				orderby x.m_biome, x.m_prefabName
				select x;
			List<string> list = new List<string>();
			foreach (ZoneLocation item in orderedEnumerable)
			{
				GameObject prefab = item.m_prefab;
				if (prefab == null)
				{
					continue;
				}
				DungeonGenerator[] componentsInChildren = prefab.GetComponentsInChildren<DungeonGenerator>();
				if (componentsInChildren == null || componentsInChildren.Length == 0)
				{
					continue;
				}
				DungeonGenerator[] array = componentsInChildren;
				foreach (DungeonGenerator dungeon in array)
				{
					List<RoomData> list2 = (from x in DungeonDB.GetRooms()
						where (Theme)(x.m_room.m_theme & dungeon.m_themes) == x.m_room.m_theme
						select x).ToList();
					if (list2 == null || list2.Count == 0)
					{
						continue;
					}
					foreach (RoomData item2 in list2)
					{
						list.AddRange(Extract(((Component)item2.m_room).gameObject, "Biome: " + item.m_biome.GetNames(), "Location: " + item.m_prefabName, $"Room Theme: {item2.m_room.m_theme}", "Room: " + ((Object)item2.m_room).name));
					}
				}
			}
			PrintDebugFile.PrintFile(list, "drop_that.drop_table.dungeons.txt", "drop tables for dungeons");
		}

		internal static void PrintLocationDropTables()
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			IOrderedEnumerable<ZoneLocation> orderedEnumerable = from x in ZoneSystem.instance.m_locations
				orderby x.m_biome, x.m_prefabName
				select x;
			List<string> list = new List<string>();
			foreach (ZoneLocation item in orderedEnumerable)
			{
				GameObject prefab = item.m_prefab;
				if (!((Object)(object)prefab).IsNull())
				{
					list.AddRange(Extract(prefab, "Biome: " + item.m_biome.GetNames(), "Location: " + item.m_prefabName));
				}
			}
			PrintDebugFile.PrintFile(list, "drop_that.drop_table.locations.txt", "drop tables for locations");
		}

		internal static void PrintPrefabDropTables()
		{
			List<string> list = new List<string>();
			foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
			{
				list.AddRange(Extract(prefab));
			}
			PrintDebugFile.PrintFile(list, "drop_that.drop_table.prefabs.txt", "drop tables for prefabs");
		}

		private static List<string> Extract(GameObject prefab, params string[] additionalHeaders)
		{
			List<string> list = new List<string>();
			Container componentInChildren = prefab.GetComponentInChildren<Container>();
			if (((Object)(object)componentInChildren).IsNotNull() && Object.op_Implicit((Object)(object)componentInChildren))
			{
				list.Add(GetData((MonoBehaviour)(object)componentInChildren, componentInChildren.m_defaultItems, additionalHeaders));
			}
			DropOnDestroyed componentInChildren2 = prefab.GetComponentInChildren<DropOnDestroyed>();
			if (((Object)(object)componentInChildren2).IsNotNull() && Object.op_Implicit((Object)(object)componentInChildren2))
			{
				list.Add(GetData((MonoBehaviour)(object)componentInChildren2, componentInChildren2.m_dropWhenDestroyed, additionalHeaders));
			}
			LootSpawner componentInChildren3 = prefab.GetComponentInChildren<LootSpawner>();
			if (((Object)(object)componentInChildren3).IsNotNull() && Object.op_Implicit((Object)(object)componentInChildren3))
			{
				list.Add(GetData((MonoBehaviour)(object)componentInChildren3, componentInChildren3.m_items, additionalHeaders));
			}
			TreeBase componentInChildren4 = prefab.GetComponentInChildren<TreeBase>();
			if (((Object)(object)componentInChildren4).IsNotNull() && Object.op_Implicit((Object)(object)componentInChildren4))
			{
				list.Add(GetData((MonoBehaviour)(object)componentInChildren4, componentInChildren4.m_dropWhenDestroyed, additionalHeaders));
			}
			TreeLog componentInChildren5 = prefab.GetComponentInChildren<TreeLog>();
			if (((Object)(object)componentInChildren5).IsNotNull() && Object.op_Implicit((Object)(object)componentInChildren5))
			{
				list.Add(GetData((MonoBehaviour)(object)componentInChildren5, componentInChildren5.m_dropWhenDestroyed, additionalHeaders));
			}
			MineRock componentInChildren6 = prefab.GetComponentInChildren<MineRock>();
			if (((Object)(object)componentInChildren6).IsNotNull() && Object.op_Implicit((Object)(object)componentInChildren6))
			{
				list.Add(GetData((MonoBehaviour)(object)componentInChildren6, componentInChildren6.m_dropItems, additionalHeaders));
			}
			MineRock5 componentInChildren7 = prefab.GetComponentInChildren<MineRock5>();
			if (((Object)(object)componentInChildren7).IsNotNull() && Object.op_Implicit((Object)(object)componentInChildren7))
			{
				list.Add(GetData((MonoBehaviour)(object)componentInChildren7, componentInChildren7.m_dropItems, additionalHeaders));
			}
			return list;
		}
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Conditions
{
	public class ConditionAltitude : IDropTableCondition
	{
		private static ConditionAltitude _instance;

		public static ConditionAltitude Instance => _instance ?? (_instance = new ConditionAltitude());

		public bool ShouldFilter(DropSourceTemplateLink context, DropTemplate template)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (IsValid(context.Source.transform.position, template?.Config))
			{
				return false;
			}
			Log.LogTrace("Filtered drop '" + ((Object)template.Drop.m_item).name + "' due being outside required altitude.");
			return true;
		}

		public bool IsValid(Vector3 position, DropTableItemConfiguration config)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			if (config == null)
			{
				return true;
			}
			float num = position.y - ZoneSystem.instance.m_waterLevel;
			if (num < (float)config.ConditionAltitudeMin)
			{
				return false;
			}
			if (num > (float)config.ConditionAltitudeMax)
			{
				return false;
			}
			return true;
		}
	}
	public class ConditionBiome : IDropTableCondition
	{
		private static ConditionBiome _instance;

		public static ConditionBiome Instance => _instance ?? (_instance = new ConditionBiome());

		public bool ShouldFilter(DropSourceTemplateLink context, DropTemplate template)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (IsValid(context.Source.transform.position, template?.Config))
			{
				return false;
			}
			Log.LogTrace("Filtered drop '" + ((Object)template.Drop.m_item).name + "' due being outside required biome.");
			return true;
		}

		public bool IsValid(Vector3 position, DropTableItemConfiguration config)
		{
			//IL_0030: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			if (config == null)
			{
				return true;
			}
			if (string.IsNullOrWhiteSpace(config.ConditionBiomes.Value))
			{
				return true;
			}
			List<string> source = config.ConditionBiomes.Value.SplitByComma(toUpper: true);
			Biome val = Heightmap.FindBiome(position);
			string currentBiomeCleaned = ((object)(Biome)(ref val)).ToString().ToUpperInvariant();
			return source.Any((string x) => x == currentBiomeCleaned);
		}
	}
	public class ConditionDaytime : IDropTableCondition
	{
		private static ConditionDaytime _instance;

		public static ConditionDaytime Instance => _instance ?? (_instance = new ConditionDaytime());

		public bool ShouldFilter(DropSourceTemplateLink context, DropTemplate template)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (IsValid(template?.Config))
			{
				return false;
			}
			Log.LogTrace("Filtered drop '" + ((Object)template.Drop.m_item).name + "' due being outside allowed time of day.");
			return true;
		}

		public bool IsValid(DropTableItemConfiguration config)
		{
			if (config == null)
			{
				return true;
			}
			EnvMan instance = EnvMan.instance;
			if ((bool)config.ConditionNotDay && instance.IsDay())
			{
				return false;
			}
			if ((bool)config.ConditionNotAfternoon && instance.IsAfternoon())
			{
				return false;
			}
			if ((bool)config.ConditionNotNight && instance.IsNight())
			{
				return false;
			}
			return true;
		}
	}
	public class ConditionDistanceToCenter : IDropTableCondition
	{
		private static ConditionDistanceToCenter _instance;

		public static ConditionDistanceToCenter Instance => _instance ?? (_instance = new ConditionDistanceToCenter());

		public bool ShouldFilter(DropSourceTemplateLink context, DropTemplate template)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (IsValid(context.Source.transform.position, template?.Config))
			{
				return false;
			}
			Log.LogTrace("Filtered drop '" + ((Object)template.Drop.m_item).name + "' due not being within required distance to center of map.");
			return true;
		}

		public bool IsValid(Vector3 position, DropTableItemConfiguration config)
		{
			if (config == null)
			{
				return true;
			}
			float magnitude = ((Vector3)(ref position)).magnitude;
			if (magnitude < config.ConditionDistanceToCenterMin.Value)
			{
				return false;
			}
			if (config.ConditionDistanceToCenterMax.Value > 0f && magnitude > config.ConditionDistanceToCenterMax.Value)
			{
				return false;
			}
			return true;
		}
	}
	public class ConditionEnvironments : IDropTableCondition
	{
		private static ConditionEnvironments _instance;

		public static ConditionEnvironments Instance => _instance ?? (_instance = new ConditionEnvironments());

		public bool ShouldFilter(DropSourceTemplateLink context, DropTemplate template)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (IsValid(template.Config))
			{
				return false;
			}
			Log.LogTrace("Filtered drop '" + ((Object)template.Drop.m_item).name + "' due to current environment.");
			return true;
		}

		public bool IsValid(DropTableItemConfiguration config)
		{
			if (string.IsNullOrEmpty(config.ConditionEnvironments.Value))
			{
				return true;
			}
			EnvMan instance = EnvMan.instance;
			string currentEnv = instance.GetCurrentEnvironment().m_name.Trim().ToUpperInvariant();
			List<string> list = config.ConditionEnvironments.Value.SplitByComma(toUpper: true);
			if (list.Count == 0)
			{
				return true;
			}
			if (list.Any((string x) => x == currentEnv))
			{
				return true;
			}
			return false;
		}
	}
	public class ConditionGlobalKeysRequired : IDropTableCondition
	{
		private static ConditionGlobalKeysRequired _instance;

		public static ConditionGlobalKeysRequired Instance => _instance ?? (_instance = new ConditionGlobalKeysRequired());

		public bool ShouldFilter(DropSourceTemplateLink context, DropTemplate template)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (IsValid(template.Config))
			{
				return false;
			}
			Log.LogTrace("Filtered drop '" + ((Object)template.Drop.m_item).name + "' due to not finding required global key.");
			return true;
		}

		public bool IsValid(DropTableItemConfiguration config)
		{
			if (string.IsNullOrEmpty(config.ConditionGlobalKeys.Value))
			{
				return true;
			}
			List<string> list = config.ConditionGlobalKeys.Value.SplitByComma();
			if (list.Count == 0)
			{
				return true;
			}
			if (list.Any((string x) => ZoneSystem.instance.GetGlobalKey(x)))
			{
				return true;
			}
			return false;
		}
	}
	public class ConditionLocation : IDropTableCondition
	{
		private static ConditionLocation _instance;

		public static ConditionLocation Instance => _instance ?? (_instance = new ConditionLocation());

		public bool ShouldFilter(DropSourceTemplateLink context, DropTemplate template)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (IsValid(context.Source.transform.position, template.Config))
			{
				return false;
			}
			Log.LogTrace("Filtered drop '" + ((Object)template.Drop.m_item).name + "' due to not being in required location.");
			return true;
		}

		public bool IsValid(Vector3 position, DropTableItemConfiguration config)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(config?.ConditionLocations?.Value))
			{
				return true;
			}
			List<string> list = config.ConditionLocations.Value.SplitByComma(toUpper: true);
			if (list.Count == 0)
			{
				return true;
			}
			SimpleLocation simpleLocation = LocationHelper.FindLocation(position);
			string currentLocationName = simpleLocation.LocationName.Trim().ToUpperInvariant();
			return list.Any((string x) => x == currentLocationName);
		}
	}
	public interface IDropTableCondition
	{
		bool ShouldFilter(DropSourceTemplateLink context, DropTemplate template);
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Conditions.ModSpecific
{
	internal static class ConditionLoaderCLLC
	{
		public static bool InstalledCLLC { get; } = (object)Type.GetType("CreatureLevelControl.API, CreatureLevelControl") != null;


		public static Valheim.DropThat.Drop.DropTableSystem.Conditions.ModSpecific.ModCLLC.ConditionWorldLevel ConditionWorldLevel
		{
			get
			{
				if (!InstalledCLLC)
				{
					return null;
				}
				return Valheim.DropThat.Drop.DropTableSystem.Conditions.ModSpecific.ModCLLC.ConditionWorldLevel.Instance;
			}
		}
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Conditions.ModSpecific.ModCLLC
{
	public class ConditionWorldLevel : IDropTableCondition
	{
		private static ConditionWorldLevel _instance;

		public static ConditionWorldLevel Instance => _instance ?? (_instance = new ConditionWorldLevel());

		public bool ShouldFilter(DropSourceTemplateLink context, DropTemplate template)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (IsValid(template?.Config))
			{
				return false;
			}
			Log.LogTrace("Filtered drop '" + ((Object)template.Drop.m_item).name + "' due to not being within required CLLC world level.");
			return true;
		}

		public bool IsValid(DropTableItemConfiguration itemConfig)
		{
			if (itemConfig == null)
			{
				return true;
			}
			if (itemConfig.TryGet("CreatureLevelAndLootControl", out var value) && value is DropTableModConfigCLLC dropTableModConfigCLLC)
			{
				int worldLevel = API.GetWorldLevel();
				if (worldLevel < (int)dropTableModConfigCLLC.ConditionWorldLevelMin)
				{
					return false;
				}
				if ((int)dropTableModConfigCLLC.ConditionWorldLevelMax > 0 && worldLevel > (int)dropTableModConfigCLLC.ConditionWorldLevelMax)
				{
					return false;
				}
			}
			return true;
		}
	}
}
namespace Valheim.DropThat.Drop.DropTableSystem.Caches
{
	internal static class DropLinkCache
	{
		private static ConditionalWeakTable<DropTable, DropSourceTemplateLink> LinkTable = new ConditionalWeakTable<DropTable, DropSourceTemplateLink>();

		public static DropSourceTemplateLink GetLink(DropTable key)
		{
			if (LinkTable.TryGetValue(key, out var value))
			{
				return value;
			}
			return null;
		}

		public static void SetLink(DropTable key, DropSourceTemplateLink context)
		{
			if (context != null)
			{
				LinkTable.Add(key, context);
			}
		}
	}
	internal class DropTemplateCache
	{
		private static ManagedCache<DropTemplate> DropTemplates { get; } = new ManagedCache<DropTemplate>();


		private static ConditionalWeakTable<ItemData, DropTemplateCache> ItemTemplates { get; } = new ConditionalWeakTable<ItemData, DropTemplateCache>();


		public DropTemplate Template { get; set; }

		public static void RegisterTemplate(GameObject drop, DropTemplate template)
		{
			DropTemplates.Set((Object)(object)drop, template);
		}

		public static void RegisterTemplate(ItemData item, DropTemplate template)
		{
			ItemTemplates.GetOrCreateValue(item).Template = template;
		}

		public static DropTemplate GetTemplate(ItemData item)
		{
			if (ItemTemplates.TryGetValue(item, out var value))
			{
				return value.Template;
			}
			return null;
		}

		public static DropTemplate GetTemplate(GameObject drop)
		{
			if (DropTemplates.TryGet((Object)(object)drop, out var value))
			{
				return value;
			}
			return null;
		}
	}
}
namespace Valheim.DropThat.Drop.CharacterDropSystem
{
	public class ConditionChecker
	{
		private HashSet<ICondition> OnStartConditions;

		private HashSet<ICondition> OnDeathConditions;

		private static ConditionChecker _instance;

		public static ConditionChecker Instance => _instance ?? (_instance = new ConditionChecker());

		private ConditionChecker()
		{
			StateResetter.Subscribe(delegate
			{
				_instance = null;
			});
			OnStartConditions = new HashSet<ICondition>();
			OnStartConditions.AddNullSafe(ConditionInventory.Instance);
			OnStartConditions.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ConditionLocation.Instance);
			OnStartConditions.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ConditionDistanceToCenter.Instance);
			OnStartConditions.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ConditionBiome.Instance);
			OnDeathConditions = new HashSet<ICondition>();
			OnDeathConditions.AddNullSafe(ConditionCreatureState.Instance);
			OnDeathConditions.AddNullSafe(ConditionLoaderSpawnThat.ConditionTemplateId);
			OnDeathConditions.AddNullSafe(ConditionFaction.Instance);
			OnDeathConditions.AddNullSafe(ConditionNotFaction.Instance);
			OnDeathConditions.AddNullSafe(ConditionKilledByDamageType.Instance);
			OnDeathConditions.AddNullSafe(ConditionKilledBySkillType.Instance);
			OnDeathConditions.AddNullSafe(ConditionKilledWithStatus.Instance);
			OnDeathConditions.AddNullSafe(ConditionKilledWithStatuses.Instance);
			OnDeathConditions.AddNullSafe(ConditionKilledByEntityType.Instance);
			OnDeathConditions.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ConditionEnvironments.Instance);
			OnDeathConditions.AddNullSafe(ConditionGlobalKeys.Instance);
			OnDeathConditions.AddNullSafe(ConditionLevel.Instance);
			OnDeathConditions.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ConditionDaytime.Instance);
			OnDeathConditions.AddNullSafe(ConditionHitByEntityTypeRecently.Instance);
			OnDeathConditions.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ModSpecific.ConditionLoaderCLLC.ConditionBossAffix);
			OnDeathConditions.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ModSpecific.ConditionLoaderCLLC.ConditionInfusion);
			OnDeathConditions.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ModSpecific.ConditionLoaderCLLC.ConditionCreatureExtraEffect);
			OnDeathConditions.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Conditions.ModSpecific.ConditionLoaderCLLC.ConditionWorldLevel);
		}

		public static List<Drop> FilterOnStart(CharacterDrop characterDrop)
		{
			try
			{
				return Instance.Filter(characterDrop, Instance.OnStartConditions);
			}
			catch (Exception e)
			{
				Log.LogError("Error while attempting to run OnStart conditions. Skipping filtering.", e);
				return characterDrop.m_drops;
			}
		}

		public static List<Drop> FilterOnDeath(CharacterDrop characterDrop)
		{
			try
			{
				return Instance.Filter(characterDrop, Instance.OnDeathConditions);
			}
			catch (Exception e)
			{
				Log.LogError("Error while attempting to run OnDeath conditions. Skipping filtering.", e);
				return characterDrop.m_drops;
			}
		}

		public List<Drop> Filter(CharacterDrop characterDrop, IEnumerable<ICondition> conditions)
		{
			List<Drop> list = new List<Drop>();
			foreach (Drop drop in characterDrop.m_drops)
			{
				DropExtended dropExtended = DropExtended.GetExtension(drop);
				if (dropExtended == null)
				{
					list.Add(drop);
				}
				else if (!conditions.Any((ICondition x) => x?.ShouldFilter(drop, dropExtended, characterDrop) ?? false))
				{
					list.Add(drop);
				}
			}
			return list;
		}
	}
	public class DropContext
	{
		public GameObject Item { get; set; }

		public DropExtended Extended { get; set; }

		public Vector3 Pos { get; set; }
	}
	public class DropModificationManager
	{
		private HashSet<IDropModifier> DropModifiers = new HashSet<IDropModifier>();

		private static DropModificationManager _instance;

		public static DropModificationManager Instance => _instance ?? (_instance = new DropModificationManager());

		private DropModificationManager()
		{
			StateResetter.Subscribe(delegate
			{
				_instance = null;
			});
			DropModifiers.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Modifiers.ModifierSetQualityLevel.Instance);
			DropModifiers.AddNullSafe(ModifierLoaderEpicLoot.MagicItem);
			DropModifiers.AddNullSafe(Valheim.DropThat.Drop.CharacterDropSystem.Modifiers.ModifierSetDurability.Instance);
		}

		public void ApplyModifications(GameObject item, DropExtended extended, Vector3 pos)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (item == null || extended == null)
			{
				return;
			}
			DropContext context = new DropContext
			{
				Item = item,
				Extended = extended,
				Pos = pos
			};
			foreach (IDropModifier dropModifier in DropModifiers)
			{
				try
				{
					dropModifier?.Modify(context);
				}
				catch (Exception e)
				{
					Log.LogError("Error while attempting to modify item drop " + ((Object)item).name, e);
				}
			}
		}
	}
}
namespace Valheim.DropThat.Drop.CharacterDropSystem.Services
{
	internal static class MobDropInitializationService
	{
		public static IEnumerable<CharacterDropItemConfiguration> PrepareInsertion(CharacterDropListConfiguration listConfig, CharacterDropMobConfiguration mobConfig)
		{
			Dictionary<int, CharacterDropItemConfiguration> dictionary = new Dictionary<int, CharacterDropItemConfiguration>();
			if (listConfig != null)
			{
				foreach (CharacterDropItemConfiguration value in listConfig.Subsections.Values)
				{
					if ((bool)value.EnableConfig)
					{
						dictionary[value.Index] = value;
					}
				}
			}
			if (mobConfig != null)
			{
				foreach (CharacterDropItemConfiguration value2 in mobConfig.Subsections.Values)
				{
					if ((bool)value2.EnableConfig)
					{
						dictionary[value2.Index] = value2;
					}
				}
			}
			return dictionary.Values.OrderBy((CharacterDropItemConfiguration x) => x.Index);
		}
	}
}
namespace Valheim.DropThat.Drop.CharacterDropSystem.Patches
{
	[HarmonyPatch(typeof(CharacterDrop))]
	public static class Patch_CharacterDrop_DropItems
	{
		private class LoopCounter
		{
			private static ConditionalWeakTable<object, LoopCounter> LoopCounterTable = new ConditionalWeakTable<object, LoopCounter>();

			public int Count;

			public static void Increment(object obj)
			{
				LoopCounterTable.GetOrCreateValue(obj).Count++;
			}

			public static void Increment(object obj, int count)
			{
				LoopCounterTable.GetOrCreateValue(obj).Count += count;
			}

			public static int GetCount(object obj)
			{
				if (LoopCounterTable.TryGetValue(obj, out var value))
				{
					return value.Count;
				}
				return 0;
			}
		}

		private static MethodInfo OnSpawnedItemMethod = AccessTools.Method(typeof(Patch_CharacterDrop_DropItems), "OnSpawnedItem", new Type[3]
		{
			typeof(GameObject),
			typeof(List<KeyValuePair<GameObject, int>>),
			typeof(Vector3)
		}, (Type[])null);

		private static MethodInfo AfterSpawnedItemMethod = AccessTools.Method(typeof(Patch_CharacterDrop_DropItems), "AfterSpawnedItem", (Type[])null, (Type[])null);

		[HarmonyPatch("DropItems")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> HookSpawnedItem(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Ldloc_3, (object)null, (string)null)
			}).Advance(3).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Ldloc_S, (object)5)
			})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldarg_1, (object)null)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)OnSpawnedItemMethod)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldloc_S, (object)5)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldarg_0, (object)null)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Ldloc_2, (object)null)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AfterSpawnedItemMethod)
				})
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Stloc_2, (object)null)
				})
				.InstructionEnumeration();
		}

		private static int AfterSpawnedItem(GameObject item, List<KeyValuePair<GameObject, int>> drops, int index)
		{
			int num = index;
			try
			{
				int itemCount = LoopCounter.GetCount(drops) - 1;
				int index2 = GetIndex(drops, itemCount);
				if (index2 >= drops.Count)
				{
					return num;
				}
				KeyValuePair<GameObject, int> keyValuePair = drops[index2];
				bool flag = false;
				if (keyValuePair.Value > 1)
				{
					if ((bool)ConfigurationManager.GeneralConfig.AlwaysAutoStack)
					{
						flag = true;
					}
					else
					{
						DropExtended drop = TempDropListCache.GetDrop(drops, index2);
						if (drop != null && (bool)drop.Config.SetAutoStack)
						{
							flag = true;
						}
					}
				}
				if (flag)
				{
					int num2 = GetMaxStackSize(keyValuePair.Key);
					int num3 = Math.Min(num2, keyValuePair.Value - index);
					if (num3 > 1)
					{
						ItemDrop component = ComponentCache.GetComponent<ItemDrop>(item);
						Log.LogTrace($"Stacking item '{((Object)keyValuePair.Key).name}' {num3} times out of maximum {num2}.");
						component.SetStack(num3);
						LoopCounter.Increment(drops, num3 - 1);
						num += num3 - 1;
					}
				}
			}
			catch (Exception e)
			{
				Log.LogError("Error while attempting to stack item '" + ((Object)item).name + "'. Skipping stacking.", e);
			}
			return num;
			static int GetMaxStackSize(GameObject item)
			{
				ItemDrop component2 = ComponentCache.GetComponent<ItemDrop>(item);
				if (((Object)(object)component2).IsNull() || component2.m_itemData?.m_shared == null)
				{
					return -1;
				}
				return component2.m_itemData.m_shared.m_maxStackSize;
			}
		}

		private static void OnSpawnedItem(GameObject item, List<KeyValuePair<GameObject, int>> drops, Vector3 centerPos)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			int count = LoopCounter.GetCount(drops);
			int index = GetIndex(drops, count);
			LoopCounter.Increment(drops);
			try
			{
				DropExtended drop = TempDropListCache.GetDrop(drops, index);
				if (drop != null)
				{
					DropModificationManager.Instance.ApplyModifications(item, drop, centerPos);
				}
			}
			catch (Exception e)
			{
				Log.LogError("Error during drop modification.", e);
			}
		}

		private static int GetIndex(List<KeyValuePair<GameObject, int>> drops, int itemCount)
		{
			int num = 0;
			int i = 0;
			int num2 = 0;
			for (; i < drops.Count; i++)
			{
				int num3 = 0;
				while (num3 < drops[i].Value)
				{
					if (itemCount == num2)
					{
						return num;
					}
					num3++;
					num2++;
				}
				num++;
			}
			return num;
		}
	}
	[HarmonyPatch(typeof(CharacterDrop))]
	public static class Patch_CharacterDrop_GenerateDropList_CarryDropExtended
	{
		private static MethodInfo Anchor = AccessTools.Method(typeof(List<Drop>.Enumerator), "MoveNext", (Type[])null, (Type[])null);

		private static MethodInfo CarryExtendedMethod = AccessTools.Method(typeof(Patch_CharacterDrop_GenerateDropList_CarryDropExtended), "CarryExtended", (Type[])null, (Type[])null);

		[HarmonyPatch("GenerateDropList")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> CarryItemConfigs(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0034: Unkn

BepInEx/plugins/ASharpPen-Spawn_That/Valheim.SpawnThat.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
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.Configuration;
using BepInEx.Logging;
using CreatureLevelControl;
using EpicLoot;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using RagnarsRokare.MobAI;
using SpawnThat.Caches;
using SpawnThat.Configuration;
using SpawnThat.Configuration.Sync;
using SpawnThat.Core;
using SpawnThat.Core.Cache;
using SpawnThat.Core.Configuration;
using SpawnThat.Core.Network;
using SpawnThat.Core.Toml;
using SpawnThat.Core.Toml.Parsers;
using SpawnThat.Core.Toml.Writers;
using SpawnThat.Debugging;
using SpawnThat.Integrations;
using SpawnThat.Integrations.CLLC.Conditions;
using SpawnThat.Integrations.CLLC.Models;
using SpawnThat.Integrations.CLLC.Modifiers;
using SpawnThat.Integrations.EpicLoot.Conditions;
using SpawnThat.Integrations.EpicLoot.Models;
using SpawnThat.Integrations.MobAi.Modifiers;
using SpawnThat.Lifecycle;
using SpawnThat.Options.Conditions;
using SpawnThat.Options.Identifiers;
using SpawnThat.Options.Modifiers;
using SpawnThat.Options.PositionConditions;
using SpawnThat.Spawners;
using SpawnThat.Spawners.Contexts;
using SpawnThat.Spawners.LocalSpawner;
using SpawnThat.Spawners.LocalSpawner.Caches;
using SpawnThat.Spawners.LocalSpawner.Configuration;
using SpawnThat.Spawners.LocalSpawner.Configuration.BepInEx;
using SpawnThat.Spawners.LocalSpawner.Managers;
using SpawnThat.Spawners.LocalSpawner.Models;
using SpawnThat.Spawners.LocalSpawner.Services;
using SpawnThat.Spawners.LocalSpawner.Startup;
using SpawnThat.Spawners.LocalSpawner.Sync;
using SpawnThat.Spawners.SpawnAreaSpawner;
using SpawnThat.Spawners.SpawnAreaSpawner.Configuration;
using SpawnThat.Spawners.SpawnAreaSpawner.Configuration.BepInEx;
using SpawnThat.Spawners.SpawnAreaSpawner.Debug;
using SpawnThat.Spawners.SpawnAreaSpawner.Managers;
using SpawnThat.Spawners.SpawnAreaSpawner.Models;
using SpawnThat.Spawners.SpawnAreaSpawner.Services;
using SpawnThat.Spawners.SpawnAreaSpawner.Startup;
using SpawnThat.Spawners.SpawnAreaSpawner.Sync;
using SpawnThat.Spawners.WorldSpawner;
using SpawnThat.Spawners.WorldSpawner.Configurations;
using SpawnThat.Spawners.WorldSpawner.Configurations.BepInEx;
using SpawnThat.Spawners.WorldSpawner.Debug;
using SpawnThat.Spawners.WorldSpawner.Managers;
using SpawnThat.Spawners.WorldSpawner.Services;
using SpawnThat.Spawners.WorldSpawner.Startup;
using SpawnThat.Spawners.WorldSpawner.Sync;
using SpawnThat.Utilities;
using SpawnThat.Utilities.Enums;
using SpawnThat.Utilities.Extensions;
using SpawnThat.Utilities.Spatial;
using SpawnThat.World.Dungeons;
using SpawnThat.World.Locations;
using SpawnThat.World.Maps;
using SpawnThat.World.Maps.Area;
using SpawnThat.World.Queries;
using SpawnThat.World.Zone;
using UnityEngine;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("SpawnThat.Tests")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("A Sharp Pen")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Valheim mod and tool for configuring spawners.")]
[assembly: AssemblyFileVersion("1.2.7.0")]
[assembly: AssemblyInformationalVersion("1.2.7")]
[assembly: AssemblyProduct("Valheim.SpawnThat")]
[assembly: AssemblyTitle("Valheim.SpawnThat")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ASharpPen/Valheim.SpawnThat")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.7.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 SpawnThat
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("asharppen.valheim.spawn_that", "Spawn That!", "1.2.7")]
	public class SpawnThatPlugin : BaseUnityPlugin
	{
		public const string ModId = "asharppen.valheim.spawn_that";

		public const string PluginName = "Spawn That!";

		public const string Version = "1.2.7";

		private void Awake()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			Log.Logger = ((BaseUnityPlugin)this).Logger;
			ConfigurationManager.GeneralConfig = ConfigurationManager.LoadGeneral();
			Startup.SetupServices();
			if ((object)Type.GetType("YamlDotNet.Serialization.SerializerBuilder, YamlDotNet") == null)
			{
				Log.LogWarning("Unable to detect required YamlDotNet type. Verify that YamlDotNet.dll is installed.");
			}
			new Harmony("asharppen.valheim.spawn_that").PatchAll();
		}
	}
	internal static class Startup
	{
		public static void SetupServices()
		{
			GeneralConfigurationSetup.SetupMainConfiguration();
			LocalSpawnerSetup.SetupLocalSpawners();
			WorldSpawnerSetup.SetupWorldSpawners();
			SpawnAreaSpawnerSetup.SetupSpawnAreaSpawners();
			LifecycleManager.OnLateInit += InitConfiguration;
			ZoneSystemSyncSetup.Configure();
		}

		private static void InitConfiguration()
		{
			if (LifecycleManager.GameState == GameState.Singleplayer || LifecycleManager.GameState == GameState.DedicatedServer)
			{
				SpawnerConfigurationManager.BuildConfigurations();
			}
		}
	}
}
namespace SpawnThat.World
{
	internal class ZoneHeightmap : IZone
	{
		private Heightmap Heightmap { get; }

		public int Width { get; }

		public Biome Biome { get; }

		public Vector2i ZoneId { get; }

		public Vector3 ZonePos { get; }

		public Biome[] BiomeCorners { get; }

		public BiomeArea BiomeArea { get; }

		public ZoneHeightmap(Heightmap heightmap)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			Heightmap = heightmap;
			ZonePos = ((Component)heightmap).transform.position;
			ZoneId = ZonePos.GetZoneId();
			Width = heightmap.m_width;
			Biome = heightmap.GetBiome(ZonePos);
			BiomeCorners = heightmap.m_cornerBiomes.ToArray();
			BiomeArea = heightmap.GetBiomeArea();
		}

		public bool HasBiome(Biome biome)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return Heightmap.HaveBiome(biome);
		}

		public Biome GetBiome(Vector3 pos)
		{
			//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)
			return Heightmap.GetBiome(pos);
		}

		public float Height(Vector3 worldCoordinate)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			float result = default(float);
			Heightmap.GetHeight(worldCoordinate, ref result);
			return result;
		}

		public float Height(Vector2i zoneLocalCoordinate)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return Heightmap.GetHeight(zoneLocalCoordinate.x, zoneLocalCoordinate.y);
		}

		public float OceanDepth(Vector3 worldCoordinate)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return Heightmap.GetOceanDepth(worldCoordinate);
		}

		public float OceanDepth(Vector2i zoneLocalCoordinate)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			Vector3 worldCoordinate = Heightmap.CalcVertex(zoneLocalCoordinate.x, zoneLocalCoordinate.y);
			return OceanDepth(worldCoordinate);
		}

		public float Tilt(Vector3 worldCoordinate)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			RaycastHit val = default(RaycastHit);
			if (Physics.Raycast(worldCoordinate + Vector3.up * 5000f, Vector3.down, ref val, 10000f, ZoneSystem.instance.m_terrainRayMask))
			{
				Vector3 normal = ((RaycastHit)(ref val)).normal;
				return 90f - Mathf.Asin(normal.y) * 57.29578f;
			}
			return 0f;
		}

		public Vector2i WorldToZoneCoordinate(Vector3 worldCoordinate)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			int num = default(int);
			int num2 = default(int);
			Heightmap.WorldToVertex(worldCoordinate, ref num, ref num2);
			return new Vector2i(num, num2);
		}
	}
	internal class ZoneSimulated : IZone
	{
		private BiomeArea? _biomeArea;

		private float[] _oceanDepthCorners;

		public int Width { get; } = 64;


		public Biome Biome { get; }

		public Vector2i ZoneId { get; }

		public Vector3 ZonePos { get; }

		public Biome[] BiomeCorners { get; }

		public BiomeArea BiomeArea
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				BiomeArea valueOrDefault = _biomeArea.GetValueOrDefault();
				if (!_biomeArea.HasValue)
				{
					valueOrDefault = (BiomeArea)((!BiomeCorners.All((Biome x) => (int)BiomeCorners[0] == (int)x)) ? 1 : 2);
					_biomeArea = valueOrDefault;
					return valueOrDefault;
				}
				return valueOrDefault;
			}
		}

		private float[] OceanDepthCorners => _oceanDepthCorners ?? (_oceanDepthCorners = CalculateOceanDepths());

		private static Vector2i North { get; } = new Vector2i(0, 1);


		private static Vector2i South { get; } = new Vector2i(0, -1);


		private static Vector2i West { get; } = new Vector2i(-1, 0);


		private static Vector2i East { get; } = new Vector2i(1, 0);


		public ZoneSimulated(Vector2i zoneId)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_007f: 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_0089: Invalid comparison between Unknown and I4
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Invalid comparison between Unknown and I4
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Invalid comparison between Unknown and I4
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			ZoneId = zoneId;
			if (((Object)(object)ZoneSystem.instance).IsNotNull())
			{
				ZonePos = ZoneSystem.instance.GetZonePos(ZoneId);
			}
			else
			{
				ZonePos = new Vector3((float)(zoneId.x * Width), 0f, (float)(zoneId.y * Width));
			}
			BiomeCorners = CalculateCornerBiomes(ZonePos);
			Biome val = BiomeCorners[0];
			if ((int)val == (int)BiomeCorners[1] && (int)val == (int)BiomeCorners[2] && (int)val == (int)BiomeCorners[3])
			{
				Biome = val;
			}
			else
			{
				Biome = GetBiome(ZonePos);
			}
		}

		public bool HasBiome(Biome biome)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return BiomeCorners.Any((Biome x) => (x & biome) > 0);
		}

		public Vector2i WorldToZoneCoordinate(Vector3 worldCoordinate)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = worldCoordinate - ZonePos;
			int num = Mathf.FloorToInt(val.x + 0.5f) + Width / 2;
			int num2 = Mathf.FloorToInt(val.z + 0.5f) + Width / 2;
			return new Vector2i(num, num2);
		}

		public float Height(Vector3 worldCoordinate)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Height(WorldToZoneCoordinate(worldCoordinate));
		}

		public float Height(Vector2i zoneLocalCoordinate)
		{
			//IL_0000: 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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Invalid comparison between Unknown and I4
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Invalid comparison between Unknown and I4
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Invalid comparison between Unknown and I4
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			int y = zoneLocalCoordinate.y;
			int x = zoneLocalCoordinate.x;
			Vector3 val = ZonePos + new Vector3((float)Width * -0.5f, 0f, (float)Width * -0.5f);
			float num = val.z + (float)y;
			float num2 = Mathf.SmoothStep(0f, 1f, (float)y / (float)Width);
			float num3 = val.x + (float)x;
			float num4 = Mathf.SmoothStep(0f, 1f, (float)x / (float)Width);
			WorldGenerator instance = WorldGenerator.instance;
			Biome val2 = BiomeCorners[0];
			Color val3 = default(Color);
			if ((int)val2 == (int)BiomeCorners[1] && (int)val2 == (int)BiomeCorners[2] && (int)val2 == (int)BiomeCorners[3])
			{
				return instance.GetBiomeHeight(val2, num3, num, ref val3, false);
			}
			float biomeHeight = instance.GetBiomeHeight(val2, num3, num, ref val3, false);
			float biomeHeight2 = instance.GetBiomeHeight(BiomeCorners[1], num3, num, ref val3, false);
			float biomeHeight3 = instance.GetBiomeHeight(BiomeCorners[2], num3, num, ref val3, false);
			float biomeHeight4 = instance.GetBiomeHeight(BiomeCorners[3], num3, num, ref val3, false);
			float num5 = Mathf.Lerp(biomeHeight, biomeHeight2, num4);
			float num6 = Mathf.Lerp(biomeHeight3, biomeHeight4, num4);
			return Mathf.Lerp(num5, num6, num2);
		}

		public float OceanDepth(Vector3 worldCoordinate)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return OceanDepth(WorldToZoneCoordinate(worldCoordinate));
		}

		public float OceanDepth(Vector2i zoneLocalCoordinate)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			float num = (float)zoneLocalCoordinate.x / (float)Width;
			float num2 = (float)zoneLocalCoordinate.y / (float)Width;
			float num3 = Mathf.Lerp(OceanDepthCorners[3], OceanDepthCorners[2], num);
			float num4 = Mathf.Lerp(OceanDepthCorners[0], OceanDepthCorners[1], num);
			return Mathf.Lerp(num3, num4, num2);
		}

		private Biome[] CalculateCornerBiomes(Vector3 pos)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: 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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected I4, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected I4, but got Unknown
			//IL_006c: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected I4, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected I4, but got Unknown
			Vector3 val = pos + new Vector3((float)Width * -0.5f, 0f, (float)Width * -0.5f);
			WorldGenerator instance = WorldGenerator.instance;
			return (Biome[])(object)new Biome[4]
			{
				(Biome)(int)instance.GetBiome(val.x, val.z),
				(Biome)(int)instance.GetBiome(val.x + (float)Width, val.z),
				(Biome)(int)instance.GetBiome(val.x, val.z + (float)Width),
				(Biome)(int)instance.GetBiome(val.x + (float)Width, val.z + (float)Width)
			};
		}

		private float[] CalculateOceanDepths()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			float[] array = new float[4];
			float num = (Object.op_Implicit((Object)(object)ZoneSystem.instance) ? ZoneSystem.instance.m_waterLevel : 30f);
			array[0] = Mathf.Max(0f, num - this.Height(new Vector2i(0, Width)));
			array[1] = Mathf.Max(0f, num - this.Height(new Vector2i(Width, Width)));
			array[2] = Mathf.Max(0f, num - this.Height(new Vector2i(Width, 0)));
			array[3] = Mathf.Max(0f, num - this.Height(new Vector2i(0, 0)));
			return array;
		}

		public float Tilt(Vector3 worldCoordinate)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: 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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			Vector2i val = WorldToZoneCoordinate(worldCoordinate);
			Vector2i zoneLocalCoordinate = val + North;
			Vector2i zoneLocalCoordinate2 = val + South;
			Vector2i zoneLocalCoordinate3 = val + West;
			Vector2i zoneLocalCoordinate4 = val + East;
			float num = Height(val);
			float num2 = Height(zoneLocalCoordinate);
			float num3 = Height(zoneLocalCoordinate2);
			float num4 = Height(zoneLocalCoordinate3);
			float num5 = Height(zoneLocalCoordinate4);
			Vector3 normalized = default(Vector3);
			((Vector3)(ref normalized))..ctor((float)North.x, num2 - num, (float)North.y);
			Vector3 normalized2 = default(Vector3);
			((Vector3)(ref normalized2))..ctor((float)South.x, num3 - num, (float)South.y);
			Vector3 normalized3 = default(Vector3);
			((Vector3)(ref normalized3))..ctor((float)West.x, num4 - num, (float)West.y);
			Vector3 normalized4 = default(Vector3);
			((Vector3)(ref normalized4))..ctor((float)East.x, num5 - num, (float)East.y);
			normalized = ((Vector3)(ref normalized)).normalized;
			normalized2 = ((Vector3)(ref normalized2)).normalized;
			normalized3 = ((Vector3)(ref normalized3)).normalized;
			normalized4 = ((Vector3)(ref normalized4)).normalized;
			float num6 = AngleByCross(normalized, normalized4);
			float num7 = AngleByCross(normalized4, normalized2);
			float num8 = AngleByCross(normalized2, normalized3);
			float num9 = AngleByCross(normalized3, normalized);
			return (num6 + num8 + num9 + num7) / 4f;
			static float AngleByCross(Vector3 p1, Vector3 p2)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val2 = Vector3.Cross(p1, p2);
				return Mathf.Abs(Vector3.Angle(Vector2.op_Implicit(Vector2.up), val2));
			}
		}

		public Biome GetBiome(Vector3 pos)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			(float x, float z) tuple = WorldCoordToNormalizedZoneCoord(pos);
			float item = tuple.x;
			float item2 = tuple.z;
			Dictionary<Biome, float> dictionary = new Dictionary<Biome, float>(4);
			AddWeight(dictionary, BiomeCorners[0], Distance(item, item2, 0f, 0f));
			AddWeight(dictionary, BiomeCorners[1], Distance(item, item2, 1f, 0f));
			AddWeight(dictionary, BiomeCorners[2], Distance(item, item2, 0f, 1f));
			AddWeight(dictionary, BiomeCorners[3], Distance(item, item2, 1f, 1f));
			return dictionary.OrderBy((KeyValuePair<Biome, float> v) => v.Value).First().Key;
			static void AddWeight(Dictionary<Biome, float> weights, Biome key, float weight)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				if (weights.TryGetValue(key, out var value))
				{
					weights[key] = value + weight;
				}
				else
				{
					weights[key] = weight;
				}
			}
			static float Distance(float x1, float z1, float x2, float z2)
			{
				float num = x1 - x2;
				float num2 = z1 - z2;
				return Mathf.Sqrt(num * num + num2 * num2);
			}
		}

		private (float x, float z) WorldCoordToNormalizedZoneCoord(Vector3 pos)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = pos - ZonePos;
			float item = val.x / (float)Width + 0.5f;
			float item2 = val.z / (float)Width + 0.5f;
			return (item, item2);
		}
	}
}
namespace SpawnThat.World.Zone
{
	public interface IZone
	{
		int Width { get; }

		Biome Biome { get; }

		Vector2i ZoneId { get; }

		Vector3 ZonePos { get; }

		Biome[] BiomeCorners { get; }

		BiomeArea BiomeArea { get; }

		bool HasBiome(Biome biome);

		Biome GetBiome(Vector3 pos);

		Vector2i WorldToZoneCoordinate(Vector3 worldCoordinate);

		float Height(Vector3 worldCoordinate);

		float Height(Vector2i zoneLocalCoordinate);

		float OceanDepth(Vector3 worldCoordinate);

		float OceanDepth(Vector2i zoneLocalCoordinate);

		float Tilt(Vector3 worldCoordinate);
	}
	public static class ZoneManager
	{
		[HarmonyPatch]
		private static class PatchHeightmap
		{
			[HarmonyPatch(typeof(Heightmap), "Regenerate")]
			[HarmonyPostfix]
			private static void Record(Heightmap __instance)
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				if (__instance.m_isDistantLod)
				{
					Vector2i zoneId = ((Component)__instance).gameObject.transform.position.GetZoneId();
					HeightmapsLoaded[zoneId] = new ZoneHeightmap(__instance);
				}
			}

			[HarmonyPatch(typeof(Heightmap), "OnDestroy")]
			[HarmonyPostfix]
			private static void RemoveRecord(Heightmap __instance)
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				Vector2i zoneId = ((Component)__instance).gameObject.transform.position.GetZoneId();
				HeightmapsLoaded.Remove(zoneId);
			}
		}

		private static Dictionary<Vector2i, ZoneHeightmap> HeightmapsLoaded;

		private static Dictionary<Vector2i, ZoneSimulated> SimulatedCache;

		static ZoneManager()
		{
			HeightmapsLoaded = new Dictionary<Vector2i, ZoneHeightmap>();
			SimulatedCache = new Dictionary<Vector2i, ZoneSimulated>();
			LifecycleManager.SubscribeToWorldInit(delegate
			{
				HeightmapsLoaded = new Dictionary<Vector2i, ZoneHeightmap>();
				SimulatedCache = new Dictionary<Vector2i, ZoneSimulated>();
			});
		}

		public static IZone GetZone(Vector2i zoneId)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if (HeightmapsLoaded.TryGetValue(zoneId, out var value))
			{
				return value;
			}
			if (SimulatedCache.TryGetValue(zoneId, out var value2))
			{
				return value2;
			}
			return SimulatedCache[zoneId] = new ZoneSimulated(zoneId);
		}
	}
	public static class ZoneUtils
	{
		public static List<Vector2i> GetZonesInSquare(int minX, int minZ, int maxX, int maxZ)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			List<Vector2i> list = new List<Vector2i>();
			int num = Zonify(minX);
			int num2 = Zonify(maxX);
			int num3 = Zonify(minZ);
			int num4 = Zonify(maxZ);
			for (int i = num; i <= num2; i++)
			{
				for (int j = num3; j <= num4; j++)
				{
					list.Add(new Vector2i(i, j));
				}
			}
			return list;
		}

		public static Vector2i GetZone(Vector3 pos)
		{
			//IL_0005: 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)
			return ZoneSystem.instance.GetZone(pos);
		}

		public static Vector2i GetZone(int x, int z)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return new Vector2i(Zonify(x), Zonify(z));
		}

		public static int GetZoneIndex(Vector2i zone)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return ZDOMan.instance.SectorToIndex(zone);
		}

		public static int Zonify(int coordinate)
		{
			return Mathf.FloorToInt((float)(coordinate + 32) / 64f);
		}
	}
}
namespace SpawnThat.World.Queries
{
	public abstract class BaseZdoQuery
	{
		private bool initialized;

		protected Vector3 Center { get; }

		protected int Range { get; }

		protected List<Vector2i> ZoneIds { get; private set; }

		protected List<ZDO> Zdos { get; private set; }

		protected int MinX { get; private set; }

		protected int MinZ { get; private set; }

		protected int MaxX { get; private set; }

		protected int MaxZ { get; private set; }

		protected BaseZdoQuery(Vector3 center, int range)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			Center = center;
			Range = range;
			Initialize();
		}

		protected virtual void Initialize()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			if (initialized)
			{
				return;
			}
			(int, int) range = GetRange((int)Center.x, Range);
			MinX = range.Item1;
			MaxX = range.Item2;
			range = GetRange((int)Center.z, Range);
			MinZ = range.Item1;
			MaxZ = range.Item2;
			ZoneIds = ZoneUtils.GetZonesInSquare(MinX, MinZ, MaxX, MaxZ);
			Zdos = new List<ZDO>();
			foreach (Vector2i zoneId in ZoneIds)
			{
				ZDOMan.instance.FindObjects(zoneId, Zdos);
			}
			initialized = true;
		}

		protected static (int min, int max) GetRange(int center, int range)
		{
			return (center - range, center + range);
		}

		protected bool IsWithinRangeManhattan(ZDO zdo)
		{
			if (zdo.m_position.x < (float)MinX || zdo.m_position.x > (float)MaxX)
			{
				return false;
			}
			if (zdo.m_position.z < (float)MinZ || zdo.m_position.z > (float)MaxZ)
			{
				return false;
			}
			return true;
		}

		protected bool IsWithinRange(ZDO zdo)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			if (zdo.m_position.x < (float)MinX || zdo.m_position.x > (float)MaxX)
			{
				return false;
			}
			if (zdo.m_position.z < (float)MinZ || zdo.m_position.z > (float)MaxZ)
			{
				return false;
			}
			return zdo.m_position.WithinHorizontalDistance(Center, Range);
		}
	}
	public class ZdoPrefabQuery : BaseZdoQuery
	{
		private Dictionary<int, int> CachedPrefabResults = new Dictionary<int, int>();

		public ZdoPrefabQuery(Vector3 center, int range)
			: base(center, range)
		{
		}//IL_000c: Unknown result type (might be due to invalid IL or missing references)


		public int CountEntities(int prefabHash, Predicate<ZDO> condition = null)
		{
			Initialize();
			if (CachedPrefabResults.TryGetValue(prefabHash, out var value))
			{
				return value;
			}
			int num = 0;
			num = ((condition != null) ? base.Zdos.Count((ZDO x) => IsWithinRange(x, prefabHash) && condition(x)) : base.Zdos.Count((ZDO x) => IsWithinRange(x, prefabHash)));
			CachedPrefabResults[prefabHash] = num;
			return num;
		}

		public bool HasAny(int prefabHash)
		{
			Initialize();
			if (CachedPrefabResults.TryGetValue(prefabHash, out var value))
			{
				return value > 0;
			}
			return base.Zdos.Any((ZDO x) => IsWithinRange(x, prefabHash));
		}

		private bool IsWithinRange(ZDO zdo, int prefabId)
		{
			if (zdo.m_prefab != prefabId)
			{
				return false;
			}
			return IsWithinRange(zdo);
		}
	}
}
namespace SpawnThat.World.Maps
{
	public static class MapManager
	{
		internal static AreaMap AreaMap { get; set; }

		private static int Seed { get; set; }

		public static void Initialize()
		{
			Seed = WorldGenerator.instance.GetSeed();
			AreaMap = AreaMapBuilder.BiomeMap(10500).CompileMap();
		}

		public static int GetAreaId(Vector3 position)
		{
			//IL_0010: 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)
			int num = Math.Min(AreaMap.MapWidth, Math.Max(0, AreaMap.CoordinateToIndex((int)position.x)));
			int num2 = Math.Min(AreaMap.MapWidth, Math.Max(0, AreaMap.CoordinateToIndex((int)position.z)));
			return AreaMap.AreaIds[num][num2];
		}

		public static float GetAreaChance(Vector3 position, int modifier = 0)
		{
			//IL_0010: 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)
			int num = Math.Min(AreaMap.MapWidth, Math.Max(0, AreaMap.CoordinateToIndex((int)position.x)));
			int num2 = Math.Min(AreaMap.MapWidth, Math.Max(0, AreaMap.CoordinateToIndex((int)position.z)));
			return (float)new Random(AreaMap.AreaIds[num][num2] + Seed + modifier).NextDouble();
		}

		public static float[][] GetTemplateAreaChanceMap(int templateIndex, int scaling = 1)
		{
			float[][] array = new float[AreaMap.MapWidth][];
			Dictionary<int, float> dictionary = new Dictionary<int, float>();
			for (int i = 0; i < AreaMap.MapWidth; i++)
			{
				array[i] = new float[AreaMap.MapWidth];
				for (int j = 0; j < AreaMap.MapWidth; j++)
				{
					int num = AreaMap.AreaIds[i][j];
					if (dictionary.ContainsKey(num))
					{
						array[i][j] = dictionary[num];
						continue;
					}
					Random random = new Random(num + Seed + templateIndex);
					dictionary[num] = (float)random.NextDouble() * (float)scaling;
				}
			}
			return array;
		}
	}
}
namespace SpawnThat.World.Maps.Patches
{
	[HarmonyPatch(typeof(Game))]
	internal class Patch_Game_FindSpawnPoint_PrintMaps
	{
		private static bool FirstTime;

		static Patch_Game_FindSpawnPoint_PrintMaps()
		{
			FirstTime = true;
			LifecycleManager.SubscribeToWorldInit(delegate
			{
				FirstTime = true;
			});
		}

		[HarmonyPatch("FindSpawnPoint")]
		[HarmonyPostfix]
		private static void PrintMaps()
		{
			try
			{
				if (!FirstTime)
				{
					return;
				}
				FirstTime = false;
				GeneralConfiguration generalConfig = ConfigurationManager.GeneralConfig;
				if (generalConfig != null && generalConfig.PrintAreaMap?.Value == true)
				{
					ImageBuilder.SetIds(MapManager.AreaMap).Print("area_ids_map");
				}
				GeneralConfiguration generalConfig2 = ConfigurationManager.GeneralConfig;
				if (generalConfig2 != null && generalConfig2.PrintBiomeMap?.Value == true)
				{
					ImageBuilder.SetBiomes(MapManager.AreaMap).Print("biome_map");
				}
				GeneralConfiguration generalConfig3 = ConfigurationManager.GeneralConfig;
				if (generalConfig3 == null || generalConfig3.PrintFantasticBeastsAndWhereToKillThem?.Value != true)
				{
					return;
				}
				foreach (var template in WorldSpawnTemplateManager.GetTemplates())
				{
					if (template.template.Enabled)
					{
						int[][] mapOfTemplatesActiveAreas = WorldSpawnerSpawnMapService.GetMapOfTemplatesActiveAreas(template.id);
						if (mapOfTemplatesActiveAreas != null)
						{
							ImageBuilder.SetGrayscaleBiomes(MapManager.AreaMap).AddHeatZones(mapOfTemplatesActiveAreas).Print($"spawn_map_{template.id}_{template.template.PrefabName ?? template.template.TemplateName ?? string.Empty}");
						}
					}
				}
			}
			catch (Exception e)
			{
				Log.LogWarning("Error while attempting to print spawn area maps. Skipping map printing.", e);
			}
		}
	}
	[HarmonyPatch(typeof(ZNet))]
	internal static class Patch_ZNet_Awake_ScanWorld
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void ScanWorld()
		{
			if (WorldGenerator.instance != null)
			{
				Log.LogDebug("Scanning map for biomes..");
				DateTimeOffset utcNow = DateTimeOffset.UtcNow;
				MapManager.Initialize();
				DateTimeOffset utcNow2 = DateTimeOffset.UtcNow;
				Log.LogDebug("Scanning map and assigning id's to areas took: " + (utcNow2 - utcNow));
			}
		}

		[HarmonyPatch("RPC_PeerInfo")]
		[HarmonyPostfix]
		private static void ScanJoinedWorld()
		{
			if (WorldGenerator.instance != null)
			{
				Log.LogDebug("Scanning map for biomes..");
				DateTimeOffset utcNow = DateTimeOffset.UtcNow;
				MapManager.Initialize();
				DateTimeOffset utcNow2 = DateTimeOffset.UtcNow;
				Log.LogDebug("Scanning map and assigning id's to areas took: " + (utcNow2 - utcNow));
			}
		}
	}
}
namespace SpawnThat.World.Maps.Area
{
	internal class AreaMap
	{
		public const int ZoneSize = 64;

		public const int ZoneSizeOffset = 32;

		public int[][] Biomes { get; private set; }

		public int[][] AreaIds { get; private set; }

		public int ZoneOffset { get; private set; }

		public int MapWidth { get; private set; }

		public int IndexStartCoordinate { get; private set; }

		public AreaMap(int mapRadius)
		{
			ZoneOffset = (int)Math.Ceiling((double)mapRadius / 64.0);
			IndexStartCoordinate = -(ZoneOffset * 64);
			MapWidth = ZoneOffset * 2;
			Biomes = new int[MapWidth][];
			AreaIds = new int[MapWidth][];
			for (int i = 0; i < MapWidth; i++)
			{
				Biomes[i] = new int[MapWidth];
				AreaIds[i] = new int[MapWidth];
			}
		}

		public int IndexToCoordinate(int index)
		{
			return IndexStartCoordinate + index * 64;
		}

		public int CoordinateToIndex(int coordinate)
		{
			return coordinate / 64 + ZoneOffset;
		}
	}
	internal class AreaMapBuilder
	{
		private class Label
		{
			public int Id { get; set; }

			public int Area { get; set; }
		}

		private IAreaProvider AreaProvider { get; set; }

		private AreaMap AreaMap { get; }

		private Label[][] LabelGrid { get; }

		private Dictionary<int, int> MergeTable { get; } = new Dictionary<int, int>();


		private int Size => AreaMap.MapWidth;

		private AreaMapBuilder(IAreaProvider areaProvider, int mapRadius)
		{
			AreaProvider = areaProvider;
			AreaMap = new AreaMap(mapRadius);
			LabelGrid = new Label[Size][];
			for (int i = 0; i < Size; i++)
			{
				LabelGrid[i] = new Label[Size];
			}
		}

		public static AreaMapBuilder BiomeMap(int mapRadius)
		{
			return new AreaMapBuilder(new WorldGeneratorAreaProvider(), mapRadius);
		}

		public AreaMapBuilder UseAreaProvider(IAreaProvider areaProvider)
		{
			AreaProvider = areaProvider;
			return this;
		}

		public AreaMap CompileMap()
		{
			ScanAreas();
			MergeLabels();
			Build();
			return AreaMap;
		}

		private void ScanAreas()
		{
			int num = 0;
			for (int i = 0; i < AreaMap.Biomes.Length; i++)
			{
				Label[] array = ((i == 0) ? null : LabelGrid[i - 1]);
				Label label = ((i == 0) ? null : array[0]);
				int[] array2 = ((i == 0) ? null : AreaMap.Biomes[i - 1]);
				int num2 = ((i == 0) ? (-1) : array2[0]);
				for (int j = 0; j < AreaMap.Biomes.Length; j++)
				{
					int area = GetArea(i, j);
					AreaMap.Biomes[i][j] = area;
					if (num2 != area)
					{
						if (i > 0 && array2[j] == area)
						{
							label = array[j];
						}
						else
						{
							label = new Label
							{
								Id = num++,
								Area = area
							};
							MergeTable[label.Id] = label.Id;
						}
					}
					LabelGrid[i][j] = label;
					num2 = area;
				}
			}
		}

		private int GetArea(int x, int y)
		{
			return AreaProvider.GetArea(AreaMap.IndexToCoordinate(x), AreaMap.IndexToCoordinate(y));
		}

		private void MergeLabels()
		{
			for (int i = 0; i < LabelGrid.Length; i++)
			{
				for (int j = 0; j < LabelGrid.Length; j++)
				{
					Label label3 = LabelGrid[i][j];
					if (j > 0)
					{
						Label label4 = LabelGrid[i][j - 1];
						_ = label3.Area;
						_ = label4.Area;
						if (MergeLabels(label4, label3, out var result2))
						{
							LabelGrid[i][j] = result2;
							continue;
						}
					}
					if (i > 0)
					{
						Label label5 = LabelGrid[i - 1][j];
						if (MergeLabels(label5, label3, out var result3))
						{
							LabelGrid[i][j] = result3;
							continue;
						}
					}
					if (j + 1 < LabelGrid.Length)
					{
						Label label6 = LabelGrid[i][j + 1];
						if (MergeLabels(label6, label3, out var result4))
						{
							LabelGrid[i][j] = result4;
							continue;
						}
					}
					if (i + 1 < LabelGrid.Length)
					{
						Label label7 = LabelGrid[i + 1][j];
						if (MergeLabels(label7, label3, out var result5))
						{
							LabelGrid[i][j] = result5;
						}
					}
				}
			}
			bool MergeLabels(Label label1, Label label2, out Label result)
			{
				result = null;
				if (label1.Area == label2.Area && label1.Id != label2.Id)
				{
					if (label1.Id > label2.Id)
					{
						if (MergeTable[label1.Id] > label2.Id)
						{
							MergeTable[label1.Id] = label2.Id;
						}
						result = label2;
						label1.Id = label2.Id;
					}
					else
					{
						if (MergeTable[label2.Id] > label1.Id)
						{
							MergeTable[label2.Id] = label1.Id;
						}
						result = label1;
						label2.Id = label1.Id;
					}
					return true;
				}
				return false;
			}
		}

		private void Build()
		{
			for (int i = 0; i < LabelGrid.Length; i++)
			{
				for (int j = 0; j < LabelGrid.Length; j++)
				{
					int id = LabelGrid[i][j].Id;
					int num = MergeTable[id];
					while (MergeTable[num] < num)
					{
						num = MergeTable[num];
						MergeTable[id] = num;
					}
					AreaMap.AreaIds[i][j] = num;
				}
			}
		}
	}
	internal static class ColourMapper
	{
		public static (int r, int g, int b) IntegerToColor255(int value)
		{
			int item;
			if (value > 255)
			{
				item = 255;
				value -= 255;
				int item2;
				if (value > 255)
				{
					item2 = 255;
					value -= 255;
					int item3 = ((value <= 255) ? value : 255);
					return (item3, item2, item);
				}
				item2 = value;
				return (0, item2, item);
			}
			item = value;
			return (0, 0, item);
		}

		public static (int r, int g, int b) IntegerToColour3Byte(int value)
		{
			byte[] bytes = BitConverter.GetBytes(value);
			return (bytes[2], bytes[1], bytes[0]);
		}

		public static (float r, float g, float b) IntegerToColor(int value)
		{
			var (num, num2, num3) = IntegerToColour3Byte(value);
			return (num / 255, num2 / 255, num3 / 255);
		}

		public static (float r, float g, float b) Rainbow255(int id)
		{
			float num = (float)new Random(id).NextDouble();
			int num2 = (int)(num * 6f);
			int num3 = (int)(num * 255f);
			int num4 = 1 - num3;
			return num2 switch
			{
				0 => (255f, num3, 0f), 
				1 => (num4, 255f, 0f), 
				2 => (0f, 255f, num3), 
				3 => (0f, num4, 255f), 
				4 => (num3, 0f, 255f), 
				_ => (255f, 0f, num4), 
			};
		}

		public static (float r, float g, float b) Rainbow(int id)
		{
			float num = (float)new Random(id).NextDouble();
			int num2 = (int)(num * 6f);
			float num3 = num;
			float num4 = 1f - num3;
			return num2 switch
			{
				0 => (1f, num3, 0f), 
				1 => (num4, 1f, 0f), 
				2 => (0f, 1f, num3), 
				3 => (0f, num4, 1f), 
				4 => (num3, 0f, 1f), 
				_ => (1f, 0f, num4), 
			};
		}

		public static (int r, int g, int b) ToBiomeColour255(int biome)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Invalid comparison between Unknown and I4
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Invalid comparison between Unknown and I4
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected I4, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Invalid comparison between Unknown and I4
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Invalid comparison between Unknown and I4
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Invalid comparison between Unknown and I4
			Biome val = (Biome)biome;
			if ((int)val <= 32)
			{
				switch ((int)val)
				{
				default:
					if ((int)val != 16)
					{
						if ((int)val != 32)
						{
							break;
						}
						return (255, 0, 0);
					}
					return (255, 255, 0);
				case 0:
					return (0, 0, 0);
				case 1:
					return (0, 255, 0);
				case 2:
					return (128, 0, 0);
				case 4:
					return (255, 255, 255);
				case 8:
					return (0, 128, 0);
				case 3:
				case 5:
				case 6:
				case 7:
					break;
				}
			}
			else
			{
				if ((int)val == 64)
				{
					return (0, 255, 255);
				}
				if ((int)val == 256)
				{
					return (0, 0, 255);
				}
				if ((int)val == 512)
				{
					return (128, 128, 128);
				}
			}
			return (0, 0, 0);
		}

		public static (float r, float g, float b) ToBiomeColour(Biome biome)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Invalid comparison between Unknown and I4
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected I4, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Invalid comparison between Unknown and I4
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Invalid comparison between Unknown and I4
			if ((int)biome <= 32)
			{
				switch ((int)biome)
				{
				default:
					if ((int)biome != 16)
					{
						if ((int)biome != 32)
						{
							break;
						}
						return (1f, 0f, 0f);
					}
					return (1f, 1f, 0f);
				case 0:
					return (0f, 0f, 0f);
				case 1:
					return (0f, 1f, 0f);
				case 2:
					return (0.5f, 0f, 0f);
				case 4:
					return (1f, 1f, 1f);
				case 8:
					return (0f, 0.5f, 0f);
				case 3:
				case 5:
				case 6:
				case 7:
					break;
				}
			}
			else
			{
				if ((int)biome == 64)
				{
					return (0f, 1f, 1f);
				}
				if ((int)biome == 256)
				{
					return (0f, 0f, 1f);
				}
				if ((int)biome == 512)
				{
					return (0.5f, 0.5f, 0.5f);
				}
			}
			return (0f, 0f, 0f);
		}

		public static (float r, float g, float b) ToBiomeColourGrayscale(int biome)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Invalid comparison between Unknown and I4
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Invalid comparison between Unknown and I4
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected I4, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Invalid comparison between Unknown and I4
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Invalid comparison between Unknown and I4
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Invalid comparison between Unknown and I4
			Biome val = (Biome)biome;
			(int, int, int) tuple;
			if ((int)val <= 32)
			{
				switch ((int)val)
				{
				case 0:
					goto IL_0069;
				case 1:
					goto IL_0083;
				case 2:
					goto IL_0094;
				case 4:
					goto IL_00ae;
				case 8:
					goto IL_00c8;
				case 3:
				case 5:
				case 6:
				case 7:
					goto IL_0155;
				}
				if ((int)val != 16)
				{
					if ((int)val != 32)
					{
						goto IL_0155;
					}
					tuple = (220, 220, 220);
				}
				else
				{
					tuple = (200, 200, 200);
				}
			}
			else if ((int)val != 64)
			{
				if ((int)val != 256)
				{
					if ((int)val != 512)
					{
						goto IL_0155;
					}
					tuple = (130, 130, 130);
				}
				else
				{
					tuple = (255, 255, 255);
				}
			}
			else
			{
				tuple = (240, 240, 240);
			}
			goto IL_016a;
			IL_0094:
			tuple = (140, 140, 140);
			goto IL_016a;
			IL_0069:
			tuple = (255, 255, 255);
			goto IL_016a;
			IL_0083:
			tuple = (120, 120, 120);
			goto IL_016a;
			IL_016a:
			(int, int, int) tuple2 = tuple;
			return (tuple2.Item1, tuple2.Item2, tuple2.Item3);
			IL_0155:
			tuple = (255, 255, 255);
			goto IL_016a;
			IL_00c8:
			tuple = (180, 180, 180);
			goto IL_016a;
			IL_00ae:
			tuple = (160, 160, 160);
			goto IL_016a;
		}
	}
	internal interface IAreaProvider
	{
		int GetArea(int x, int y);
	}
	internal class ImageBuilder
	{
		private AreaMap areaMap;

		private Texture2D image;

		private ImageBuilder(AreaMap areaMap)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			this.areaMap = areaMap;
			image = new Texture2D(this.areaMap.MapWidth, this.areaMap.MapWidth, (TextureFormat)4, true);
		}

		public static ImageBuilder Init(AreaMap areaMap)
		{
			return new ImageBuilder(areaMap);
		}

		public static ImageBuilder SetBiomes(AreaMap areaMap)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			ImageBuilder imageBuilder = new ImageBuilder(areaMap);
			for (int i = 0; i < areaMap.MapWidth; i++)
			{
				for (int j = 0; j < areaMap.MapWidth; j++)
				{
					var (num, num2, num3) = ColourMapper.ToBiomeColour((Biome)areaMap.Biomes[i][j]);
					imageBuilder.image.SetPixel(i, j, new Color(num, num2, num3));
				}
			}
			return imageBuilder;
		}

		public static ImageBuilder SetGrayscaleBiomes(AreaMap areaMap)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			ImageBuilder imageBuilder = new ImageBuilder(areaMap);
			for (int i = 0; i < areaMap.MapWidth; i++)
			{
				for (int j = 0; j < areaMap.MapWidth; j++)
				{
					var (num, num2, num3) = ColourMapper.ToBiomeColourGrayscale(areaMap.Biomes[i][j]);
					imageBuilder.image.SetPixel(i, j, Color32.op_Implicit(new Color32((byte)num, (byte)num2, (byte)num3, byte.MaxValue)));
				}
			}
			return imageBuilder;
		}

		public static ImageBuilder SetIds(AreaMap areaMap)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			ImageBuilder imageBuilder = new ImageBuilder(areaMap);
			Color32 val = default(Color32);
			for (int i = 0; i < areaMap.MapWidth; i++)
			{
				for (int j = 0; j < areaMap.MapWidth; j++)
				{
					var (num, num2, num3) = ColourMapper.IntegerToColour3Byte(areaMap.AreaIds[i][j]);
					((Color32)(ref val))..ctor((byte)num, (byte)num2, (byte)num3, byte.MaxValue);
					imageBuilder.image.SetPixel(i, j, Color32.op_Implicit(val));
				}
			}
			return imageBuilder;
		}

		public static ImageBuilder SetRainbowIds(AreaMap areaMap)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			ImageBuilder imageBuilder = new ImageBuilder(areaMap);
			Color32 val = default(Color32);
			for (int i = 0; i < areaMap.MapWidth; i++)
			{
				for (int j = 0; j < areaMap.MapWidth; j++)
				{
					var (num, num2, num3) = ColourMapper.Rainbow255(areaMap.AreaIds[i][j]);
					((Color32)(ref val))..ctor((byte)num, (byte)num2, (byte)num3, byte.MaxValue);
					imageBuilder.image.SetPixel(i, j, Color32.op_Implicit(val));
				}
			}
			return imageBuilder;
		}

		public ImageBuilder AddHeatZones(int[][] heatZones, bool ignoreZero = true)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < heatZones.Length; i++)
			{
				for (int j = 0; j < heatZones.Length; j++)
				{
					int num = heatZones[i][j];
					if (!ignoreZero || num != 0)
					{
						image.SetPixel(i, j, Color32.op_Implicit(new Color32(byte.MaxValue, (byte)(255 - num), (byte)(255 - num), byte.MaxValue)));
					}
				}
			}
			return this;
		}

		public void Print(string filename, string description = null)
		{
			image.Apply();
			DebugFileWriter.WriteFile(ImageConversion.EncodeToPNG(image), filename + ".png", description ?? "map");
		}
	}
	internal class WorldGeneratorAreaProvider : IAreaProvider
	{
		private WorldGenerator _instance;

		private WorldGenerator World => _instance ?? (_instance = WorldGenerator.instance);

		public int GetArea(int x, int y)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected I4, but got Unknown
			return (int)World.GetBiome((float)x, (float)y);
		}
	}
}
namespace SpawnThat.World.Locations
{
	public static class LocationManager
	{
		private static Dictionary<Vector2i, SimpleLocation> _simpleLocationsByZone { get; set; }

		static LocationManager()
		{
			LifecycleManager.SubscribeToWorldInit(delegate
			{
				_simpleLocationsByZone = null;
			});
		}

		public static Dictionary<Vector2i, SimpleLocation> GetLocations()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (_simpleLocationsByZone != null)
			{
				return new Dictionary<Vector2i, SimpleLocation>(_simpleLocationsByZone);
			}
			if (((Object)(object)ZoneSystem.instance).IsNotNull() && ZoneSystem.instance.m_locationInstances != null)
			{
				Dictionary<Vector2i, SimpleLocation> dictionary = new Dictionary<Vector2i, SimpleLocation>();
				foreach (KeyValuePair<Vector2i, LocationInstance> locationInstance in ZoneSystem.instance.m_locationInstances)
				{
					dictionary[locationInstance.Key] = new SimpleLocation
					{
						LocationName = (locationInstance.Value.m_location?.m_prefabName ?? ""),
						Position = locationInstance.Value.m_position,
						ZonePosition = locationInstance.Key
					};
				}
				_simpleLocationsByZone = dictionary;
				return dictionary;
			}
			return null;
		}

		public static SimpleLocation GetLocation(Vector3 position)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			ZoneSystem instance = ZoneSystem.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance == null)
			{
				Log.LogWarning("Attempting to retrieve location before ZoneSystem is initialized.");
				return null;
			}
			Vector2i zoneId = position.GetZoneId();
			if ((instance.m_locationInstances?.Count ?? 0) > 0 && instance.m_locationInstances.TryGetValue(zoneId, out var value))
			{
				return new SimpleLocation
				{
					LocationName = (value.m_location?.m_prefabName ?? ""),
					Position = value.m_position,
					ZonePosition = zoneId
				};
			}
			if (_simpleLocationsByZone != null && _simpleLocationsByZone.TryGetValue(zoneId, out var value2))
			{
				return value2;
			}
			return null;
		}

		internal static void SetLocations(IEnumerable<SimpleLocation> locations)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (_simpleLocationsByZone == null)
			{
				_simpleLocationsByZone = new Dictionary<Vector2i, SimpleLocation>();
			}
			foreach (SimpleLocation location in locations)
			{
				_simpleLocationsByZone[location.ZonePosition] = location;
			}
		}
	}
	public class SimpleLocation
	{
		public Vector3 Position;

		public Vector2i ZonePosition;

		public string LocationName;
	}
	internal class SimpleLocationPackage : CompressedPackage
	{
		public string[] LocationNames;

		public SimpleLocationDTO[] Locations;

		protected override void BeforePack()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<Vector2i, LocationInstance> obj = (((Object)(object)ZoneSystem.instance).IsNotNull() ? ZoneSystem.instance.m_locationInstances : null);
			Dictionary<string, ushort> dictionary = new Dictionary<string, ushort>();
			List<string> list = new List<string>();
			List<SimpleLocationDTO> list2 = new List<SimpleLocationDTO>();
			foreach (KeyValuePair<Vector2i, LocationInstance> item in obj)
			{
				string prefabName = item.Value.m_location.m_prefabName;
				ushort num;
				if (dictionary.TryGetValue(item.Value.m_location.m_prefabName, out var value))
				{
					num = value;
				}
				else
				{
					list.Add(prefabName);
					num = (ushort)(list.Count - 1);
					dictionary.Add(prefabName, num);
				}
				list2.Add(new SimpleLocationDTO(item.Key, num));
			}
			LocationNames = list.ToArray();
			Locations = list2.ToArray();
			string[] locationNames = LocationNames;
			Log.LogDebug($"Packaged locations: {((locationNames != null) ? locationNames.Length : 0)}");
		}

		protected override void AfterUnpack(object obj)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: 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)
			if (obj is SimpleLocationPackage simpleLocationPackage)
			{
				Log.LogDebug("Received and deserialized location package");
				List<SimpleLocation> list = new List<SimpleLocation>(simpleLocationPackage.Locations.Length);
				SimpleLocationDTO[] locations = simpleLocationPackage.Locations;
				Vector2i val = default(Vector2i);
				for (int i = 0; i < locations.Length; i++)
				{
					SimpleLocationDTO simpleLocationDTO = locations[i];
					((Vector2i)(ref val))..ctor(simpleLocationDTO.X, simpleLocationDTO.Y);
					list.Add(new SimpleLocation
					{
						LocationName = simpleLocationPackage.LocationNames[simpleLocationDTO.L],
						Position = ZoneSystem.instance.GetZonePos(val),
						ZonePosition = val
					});
				}
				LocationManager.SetLocations(list);
				Log.LogInfo($"Successfully unpacked locations: {list?.Count ?? 0}");
			}
			else
			{
				Log.LogWarning("Received bad location package. Unable to load.");
			}
		}
	}
	[Serializable]
	public struct SimpleLocationDTO
	{
		public int X;

		public int Y;

		public ushort L;

		public SimpleLocationDTO(Vector2i pos, ushort location)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			X = pos.x;
			Y = pos.y;
			L = location;
		}
	}
	internal static class ZoneSystemSyncSetup
	{
		public static void Configure()
		{
			SyncManager.RegisterSyncHandlers("RPC_ReceiveLocationsSpawnThat", GeneratePackage, RPC_ReceiveLocationsSpawnThat);
		}

		private static ZPackage GeneratePackage()
		{
			return new SimpleLocationPackage().Pack();
		}

		private static void RPC_ReceiveLocationsSpawnThat(ZRpc rpc, ZPackage pkg)
		{
			Log.LogInfo("Received locations package.");
			try
			{
				CompressedPackage.Unpack<SimpleLocationPackage>(pkg);
			}
			catch (Exception e)
			{
				Log.LogError("Error while attempting to read received locations package.", e);
			}
		}
	}
}
namespace SpawnThat.World.Dungeons
{
	public class RoomData : IPoint, IHaveVector3
	{
		public string Name;

		public Vector3Int Size;

		private Vector3 _pos;

		public Vector3 Pos
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return _pos;
			}
			set
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: 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)
				_pos = value;
				X = value.x;
				Y = value.z;
			}
		}

		public float X { get; set; }

		public float Y { get; set; }
	}
	public static class RoomManager
	{
		[HarmonyPatch(typeof(DungeonGenerator))]
		private static class DungeonGeneratorPatch
		{
			[HarmonyPatch("PlaceRoom", new Type[]
			{
				typeof(RoomData),
				typeof(Vector3),
				typeof(Quaternion),
				typeof(RoomConnection),
				typeof(SpawnMode)
			})]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> GetRoomObject(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Expected O, but got Unknown
				CodeInstruction instruction;
				return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(true, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((OpCode?)OpCodes.Callvirt, (object)AccessTools.Method(typeof(GameObject), "GetComponent", (Type[])null, new Type[1] { typeof(Room) }), (string)null)
				}).Advance(1).GetInstruction(out instruction)
					.Advance(1)
					.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { instruction.GetLdlocFromStLoc() })
					.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { Transpilers.EmitDelegate<Action<Room>>((Action<Room>)CacheRoom) })
					.InstructionEnumeration();
			}

			private static void CacheRoom(Room component)
			{
				AddRoom(component);
			}
		}

		private static ManagedCache<RoomData> RoomTable;

		private static HashSet<Vector3> HasAdded;

		private static List<RoomData> RoomList;

		static RoomManager()
		{
			RoomTable = new ManagedCache<RoomData>();
			HasAdded = new HashSet<Vector3>();
			RoomList = new List<RoomData>();
			LifecycleManager.SubscribeToWorldInit(delegate
			{
				HasAdded = new HashSet<Vector3>();
				RoomList = new List<RoomData>();
			});
		}

		public static RoomData GetContainingRoom(Vector3 pos)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			RoomData roomData = RoomList.FindClosest(pos);
			if (roomData == null)
			{
				return null;
			}
			Bounds val = default(Bounds);
			((Bounds)(ref val))..ctor(roomData.Pos, Vector3Int.op_Implicit(roomData.Size));
			if (((Bounds)(ref val)).Contains(pos))
			{
				return roomData;
			}
			return null;
		}

		private static RoomData FindClosestRoom(Vector3 pos)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			List<RoomData> roomList = RoomList;
			if (roomList == null || roomList.Count == 0)
			{
				return null;
			}
			RoomData result = null;
			float num = float.MaxValue;
			int num2 = RoomList.IndexLeft(pos.x - 20f);
			int num3 = RoomList.IndexRight(pos.x + 20f);
			for (int i = num2; i < num3; i++)
			{
				RoomData roomData = RoomList[i];
				if (!(Math.Abs(roomData.Pos.y - pos.y) > 100f))
				{
					float value = pos.x - roomData.Pos.x;
					float value2 = pos.z - roomData.Pos.z;
					float num4 = Math.Abs(value) + Math.Abs(value2);
					if (num4 < num)
					{
						result = roomData;
						num = num4;
					}
				}
			}
			return result;
		}

		internal static void AddRoom(Room room)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			RoomData orCreate = RoomTable.GetOrCreate((Object)(object)room);
			Vector3 position = ((Component)room).transform.position;
			if (HasAdded.Add(position))
			{
				orCreate.Name = ((Object)(object)room).GetCleanedName();
				orCreate.Pos = position;
				int num = ((((Vector3Int)(ref room.m_size)).x == 0) ? 10 : ((Vector3Int)(ref room.m_size)).x);
				int num2 = ((((Vector3Int)(ref room.m_size)).y == 0) ? 10 : ((Vector3Int)(ref room.m_size)).y);
				int num3 = ((((Vector3Int)(ref room.m_size)).z == 0) ? 10 : ((Vector3Int)(ref room.m_size)).z);
				orCreate.Size = new Vector3Int(num * 2, num2 * 2, num3 * 2);
				RoomList.Insert(orCreate);
			}
		}
	}
}
namespace SpawnThat.Utilities
{
	internal enum Separator
	{
		Comma,
		Slash,
		Dot,
		Newline
	}
	public static class StringExtensions
	{
		private static readonly char[] Comma = new char[1] { ',' };

		private static readonly char[] Slash = new char[2] { '/', '\\' };

		private static readonly char[] Dot = new char[1] { '.' };

		private static readonly char[] Newline = new char[1] { '\n' };

		internal static List<string> SplitBy(this string value, Separator separator, bool toUpper = false)
		{
			return value.SplitBy(separator switch
			{
				Separator.Comma => Comma, 
				Separator.Slash => Slash, 
				Separator.Dot => Dot, 
				Separator.Newline => Newline, 
				_ => throw new NotSupportedException("Separator"), 
			}, toUpper).ToList();
		}

		public static List<string> SplitByComma(this string value, bool toUpper = false)
		{
			return value.SplitBy(Comma, toUpper).ToList();
		}

		internal static string[] SplitBySlash(this string value, bool toUpper = false)
		{
			return value.SplitBy(Slash, toUpper).ToArray();
		}

		public static IEnumerable<string> SplitBy(this string value, char[] chars, bool toUpper = false)
		{
			if (value == null)
			{
				return Enumerable.Empty<string>();
			}
			string[] array = value.Split(chars, StringSplitOptions.RemoveEmptyEntries);
			if (array == null || array.Length == 0)
			{
				return Enumerable.Empty<string>();
			}
			return array.Select(Clean);
			string Clean(string x)
			{
				string text = x.Trim();
				if (toUpper)
				{
					return text.ToUpperInvariant();
				}
				return text;
			}
		}

		public static bool IsEmpty(this string s)
		{
			return string.IsNullOrWhiteSpace(s);
		}

		public static bool IsNotEmpty(this string s)
		{
			if (string.IsNullOrWhiteSpace(s))
			{
				return false;
			}
			return true;
		}
	}
	public static class FileUtils
	{
		public static void EnsureDirectoryExistsForFile(string filePath)
		{
			string directoryName = Path.GetDirectoryName(filePath);
			if (!Directory.Exists(directoryName))
			{
				Log.LogTrace("Creating missing folders in path.");
				Directory.CreateDirectory(directoryName);
			}
		}
	}
	internal static class HeightmapUtils
	{
		public static Biome ParseBiomeMask(IEnumerable<string> biomeNames)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			Biome val = (Biome)0;
			if (biomeNames == null || !biomeNames.Any())
			{
				return val;
			}
			foreach (string biomeName in biomeNames)
			{
				if (Enum.TryParse<Biome>(biomeName, ignoreCase: true, out Biome result))
				{
					val |= result;
				}
				else
				{
					Log.LogWarning("Unable to parse biome '" + biomeName + "'. Check spelling.");
				}
			}
			return val;
		}

		public static List<Biome> ParseBiomes(IEnumerable<string> biomeNames)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			List<Biome> list = new List<Biome>();
			if (biomeNames == null || !biomeNames.Any())
			{
				return list;
			}
			foreach (string biomeName in biomeNames)
			{
				if (Enum.TryParse<Biome>(biomeName, ignoreCase: true, out Biome result))
				{
					list.Add(result);
				}
				else
				{
					Log.LogWarning("Unable to parse biome '" + biomeName + "'. Check spelling.");
				}
			}
			return list;
		}

		public static string GetNames(Biome biome)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between Unknown and I4
			List<string> list = new List<string>();
			foreach (Biome value in Enum.GetValues(typeof(Biome)))
			{
				Biome val = value;
				if ((int)val != 0 && (biome & val) > 0)
				{
					list.Add(((object)(Biome)(ref val)).ToString());
				}
			}
			return string.Join(", ", list);
		}
	}
	public static class PlayerUtils
	{
		public static List<Player> GetPlayersInRadius(Vector3 point, float range)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			List<Player> list = new List<Player>();
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (Utils.DistanceXZ(((Component)allPlayer).transform.position, point) < range)
				{
					list.Add(allPlayer);
				}
			}
			return list;
		}

		public static List<ZDO> GetPlayerZdosInRadius(Vector3 point, float range)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			List<ZDO> list = new List<ZDO>();
			foreach (ZDO allCharacterZDO in ZNet.instance.GetAllCharacterZDOS())
			{
				if (Utils.DistanceXZ(allCharacterZDO.GetPosition(), point) < range)
				{
					list.Add(allCharacterZDO);
				}
			}
			return list;
		}
	}
	internal static class ReflectionUtils
	{
		private static MethodInfo InstantiateGameObject;

		public static MethodInfo InstantiateGameObjectMethod => InstantiateGameObject ?? (InstantiateGameObject = (from x in typeof(Object).GetMethods(BindingFlags.Static | BindingFlags.Public)
			where x.Name.StartsWith("Instantiate")
			select x into m
			where m.IsGenericMethod
			select m).First((MethodInfo m) => m.ContainsGenericParameters && m.GetParameters().Length == 3).GetGenericMethodDefinition().MakeGenericMethod(typeof(GameObject)));
	}
}
namespace SpawnThat.Utilities.Spatial
{
	internal interface IHaveVector3
	{
		Vector3 Pos { get; }
	}
	internal interface IPoint
	{
		float X { get; set; }

		float Y { get; set; }
	}
	internal static class SearchSpatial
	{
		public static T FindClosest<T>(this IList<T> points, Vector3 pos) where T : class, IHaveVector3, IPoint
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: 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)
			if (points == null || points.Count == 0)
			{
				return null;
			}
			T result = null;
			float num = float.MaxValue;
			int num2 = points.IndexLeft(pos.x - 20f);
			int num3 = points.IndexRight(pos.x + 20f);
			for (int i = num2; i <= num3 && i < points.Count; i++)
			{
				T val = points[i];
				if (!(Math.Abs(val.Pos.y - pos.y) > 100f))
				{
					float value = pos.x - val.Pos.x;
					float value2 = pos.z - val.Pos.z;
					float num4 = Math.Abs(value) + Math.Abs(value2);
					if (num4 < num)
					{
						result = val;
						num = num4;
					}
				}
			}
			return result;
		}
	}
	internal static class SpatialListExtensions
	{
		public static void Insert<T>(this List<T> points, T point) where T : IPoint
		{
			int num = points.IndexLeft(point.X) + 1;
			for (int i = num; i < points.Count; i++)
			{
				T val = points[i];
				if (val.X > point.X || val.Y > point.Y)
				{
					break;
				}
				num = i;
			}
			if (num >= points.Count)
			{
				points.Add(point);
			}
			else
			{
				points.Insert(num, point);
			}
		}

		public static int IndexLeft<T>(this IList<T> points, T point) where T : IPoint
		{
			return points.IndexLeft(point.X);
		}

		public static int IndexLeft<T>(this IList<T> points, float x) where T : IPoint
		{
			int count = points.Count;
			int num = 0;
			int num2 = count;
			while (num < num2)
			{
				int num3 = (num + num2) / 2;
				float x2 = points[num3].X;
				float x3 = points[Math.Min(num3 + 1, count - 1)].X;
				if (x2 < x)
				{
					if (x3 > x)
					{
						return num3;
					}
					num = num3 + 1;
				}
				else
				{
					num2 = num3;
				}
			}
			return num;
		}

		public static int IndexRight<T>(this IList<T> points, T point) where T : IPoint
		{
			return points.IndexRight(point.X);
		}

		public static int IndexRight<T>(this IList<T> points, float x) where T : IPoint
		{
			int count = points.Count;
			int num = 0;
			int num2 = count;
			while (num < num2)
			{
				int num3 = (num + num2) / 2;
				float x2 = points[num3].X;
				float x3 = points[Math.Max(num3 - 1, 0)].X;
				if (x2 > x)
				{
					if (x3 < x)
					{
						return num3;
					}
					num2 = num3;
				}
				else
				{
					num = num3 + 1;
				}
			}
			return num2 - 1;
		}

		public static int IndexUp<T>(this IList<T> points, int xLower, int xUpper, T point) where T : IPoint
		{
			return points.IndexUp(xLower, xUpper, point.Y);
		}

		public static int IndexUp<T>(this IList<T> points, int xLower, int xUpper, float y) where T : IPoint
		{
			int count = points.Count;
			int num = xLower;
			int num2 = xUpper;
			while (num < num2)
			{
				int num3 = (num + num2) / 2;
				float y2 = points[num3].Y;
				float y3 = points[Math.Min(num3 + 1, count - 1)].Y;
				if (y2 < y)
				{
					if (y3 > y)
					{
						return num3;
					}
					num = num3 + 1;
				}
				else
				{
					num2 = num3;
				}
			}
			return num;
		}

		public static int IndexDown<T>(this IList<T> points, int xIndex, T point) where T : IPoint
		{
			return points.IndexDown(xIndex, point.Y);
		}

		public static int IndexDown<T>(this IList<T> points, int xIndex, float y) where T : IPoint
		{
			if (xIndex >= points.Count)
			{
				return xIndex;
			}
			float x = points[xIndex].X;
			int num = xIndex;
			int num2 = points.Count;
			while (num < num2)
			{
				int num3 = (num + num2) / 2;
				if (points[num3].X > x)
				{
					return num3 - 1;
				}
				if (points[num3].Y > y)
				{
					num2 = num3;
				}
				else
				{
					num = num3 + 1;
				}
			}
			return num2 - 1;
		}
	}
}
namespace SpawnThat.Utilities.Extensions
{
	internal static class CodeInstructionExtensions
	{
		public static CodeInstruction GetLdlocFromStLoc(this CodeInstruction instruction)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			if (instruction.opcode == OpCodes.Stloc_0)
			{
				return new CodeInstruction(OpCodes.Ldloc_0, (object)null);
			}
			if (instruction.opcode == OpCodes.Stloc_1)
			{
				return new CodeInstruction(OpCodes.Ldloc_1, (object)null);
			}
			if (instruction.opcode == OpCodes.Stloc_2)
			{
				return new CodeInstruction(OpCodes.Ldloc_2, (object)null);
			}
			if (instruction.opcode == OpCodes.Stloc_3)
			{
				return new CodeInstruction(OpCodes.Ldloc_3, (object)null);
			}
			if (instruction.opcode == OpCodes.Stloc_S)
			{
				return new CodeInstruction(OpCodes.Ldloca_S, instruction.operand);
			}
			if (instruction.opcode == OpCodes.Stloc)
			{
				return new CodeInstruction(OpCodes.Ldloc, instruction.operand);
			}
			throw new ArgumentException($"Unexpected instruction '{instruction}' encountered. Expected an {OpCodes.Stloc}.");
		}

		public static CodeInstruction GetStlocFromLdloc(this CodeInstruction instruction)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			if (instruction.opcode == OpCodes.Ldloc_0)
			{
				return new CodeInstruction(OpCodes.Stloc_0, (object)null);
			}
			if (instruction.opcode == OpCodes.Ldloc_1)
			{
				return new CodeInstruction(OpCodes.Stloc_1, (object)null);
			}
			if (instruction.opcode == OpCodes.Ldloc_2)
			{
				return new CodeInstruction(OpCodes.Stloc_2, (object)null);
			}
			if (instruction.opcode == OpCodes.Ldloc_3)
			{
				return new CodeInstruction(OpCodes.Stloc_3, (object)null);
			}
			if (instruction.opcode == OpCodes.Ldloca_S)
			{
				return new CodeInstruction(OpCodes.Stloc_S, instruction.operand);
			}
			if (instruction.opcode == OpCodes.Ldloc)
			{
				return new CodeInstruction(OpCodes.Stloc, instruction.operand);
			}
			throw new ArgumentException($"Unexpected instruction '{instruction}' encountered. Expected an {OpCodes.Ldloc}.");
		}
	}
	public static class CodeMatcherExtensions
	{
		public static CodeMatcher GetPosition(this CodeMatcher codeMatcher, out int position)
		{
			position = codeMatcher.Pos;
			return codeMatcher;
		}

		public static CodeMatcher InsertAndAdvance(this CodeMatcher codeMatcher, OpCode opcode)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			codeMatcher.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(opcode, (object)null)
			});
			return codeMatcher;
		}

		public static CodeMatcher InsertAndAdvance(this CodeMatcher codeMatcher, MethodInfo method)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			codeMatcher.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Call, (object)method)
			});
			return codeMatcher;
		}

		public static CodeMatcher InsertAndAdvance<T>(this CodeMatcher codeMatcher, string methodName)
		{
			return codeMatcher.InsertAndAdvance(AccessTools.Method(typeof(T), methodName, (Type[])null, (Type[])null));
		}

		public static CodeMatcher GetOpcode(this CodeMatcher codeMatcher, out OpCode opcode)
		{
			opcode = codeMatcher.Opcode;
			return codeMatcher;
		}

		public static CodeMatcher GetInstruction(this CodeMatcher codeMatcher, out CodeInstruction instruction)
		{
			instruction = codeMatcher.Instruction;
			return codeMatcher;
		}

		public static CodeMatcher GetOperand(this CodeMatcher codeMatcher, out object operand)
		{
			operand = codeMatcher.Operand;
			return codeMatcher;
		}

		internal static CodeMatcher Print(this CodeMatcher codeMatcher, int before, int after)
		{
			return codeMatcher;
		}
	}
	internal static class EnumExtensions
	{
		public static List<TEnum> Split<TEnum>(this TEnum enumVal) where TEnum : struct, Enum
		{
			int num = Convert.ToInt32(enumVal);
			List<TEnum> list = new List<TEnum>();
			foreach (TEnum value in Enum.GetValues(typeof(TEnum)))
			{
				if ((num & Convert.ToInt32(value)) > 0)
				{
					list.Add(value);
				}
			}
			return list;
		}

		public static List<Biome> Split(this Biome biomeMask)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			List<Biome> list = new List<Biome>();
			foreach (Biome value in Enum.GetValues(typeof(Biome)))
			{
				if ((biomeMask & value) > 0)
				{
					list.Add(value);
				}
			}
			return list;
		}
	}
	internal static class ICollectionExtensions
	{
		public static void AddNullSafe<T>(this ICollection<T> collection, T newEntry) where T : class
		{
			if (collection != null && newEntry != null)
			{
				Object val = (Object)(object)((newEntry is Object) ? newEntry : null);
				if (val == null || Object.op_Implicit(val))
				{
					collection.Add(newEntry);
				}
			}
		}

		public static string Join(this ICollection<float> list)
		{
			return list.Join((float x) => x.ToString(CultureInfo.InvariantCulture));
		}

		public static string Join(this ICollection<double> list)
		{
			return list.Join((double x) => x.ToString(CultureInfo.InvariantCulture));
		}

		public static string Join<T>(this ICollection<T> list)
		{
			if (list == null || list.Count == 0)
			{
				return "";
			}
			return string.Join(", ", list);
		}

		public static string Join<T>(this ICollection<T> list, Func<T, string> tostring)
		{
			if (list == null || list.Count == 0)
			{
				return string.Empty;
			}
			return string.Join(", ", list.Select((T x) => tostring(x)));
		}

		public static string Join<T, K>(this ICollection<T> list, Func<T, K> selector)
		{
			if (list == null || list.Count == 0)
			{
				return string.Empty;
			}
			return string.Join(", ", list.Select((T x) => selector(x)));
		}
	}
	internal static class IListExtensions
	{
		public static void AddOrReplaceByType<T, TEntry>(this IList<T> list, TEntry entry) where T : class where TEntry : class, T
		{
			Type typeFromHandle = typeof(TEntry);
			int num = -1;
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].GetType() == typeFromHandle)
				{
					num = i;
					break;
				}
			}
			if (num < 0)
			{
				list.Add((T)entry);
			}
			else
			{
				list[num] = (T)entry;
			}
		}
	}
	internal static class MulticastDelegateExtensions
	{
		public static void RaiseSafely(this MulticastDelegate deleg, string messageOnError, params object[] args)
		{
			if ((object)deleg == null)
			{
				return;
			}
			Delegate[] invocationList = deleg.GetInvocationList();
			foreach (Delegate @delegate in invocationList)
			{
				try
				{
					@delegate?.DynamicInvoke(args);
				}
				catch (Exception e)
				{
					string text = @delegate.Method.DeclaringType.Assembly.GetName().Name + "." + @delegate.Method.DeclaringType.Name + "." + @delegate.Method.Name;
					Log.LogError("[" + text + "]: " + messageOnError, e);
				}
			}
		}

		public static void RaiseSafely(this Action events, string messageOnError)
		{
			if (events == null)
			{
				return;
			}
			Delegate[] invocationList = events.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				Action action = (Action)invocationList[i];
				try
				{
					action();
				}
				catch (Exception e)
				{
					string text = action.Method.DeclaringType.Assembly.GetName().Name + "." + action.Method.DeclaringType.Name + "." + action.Method.Name;
					Log.LogError("[" + text + "]: " + messageOnError, e);
				}
			}
		}

		public static void RaiseSafely<T>(this Action<T> events, string messageOnError, T arg)
		{
			if (events == null)
			{
				return;
			}
			Delegate[] invocationList = events.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				Action<T> action = (Action<T>)invocationList[i];
				try
				{
					action(arg);
				}
				catch (Exception e)
				{
					string text = action.Method.DeclaringType.Assembly.GetName().Name + "." + action.Method.DeclaringType.Name + "." + action.Method.Name;
					Log.LogError("[" + text + "]: " + messageOnError, e);
				}
			}
		}
	}
	public static class StringHashExtensions
	{
		internal static int HashInteger(this string str)
		{
			int num = 5381;
			int num2 = num;
			for (int i = 0; i < str.Length && str[i] != 0; i += 2)
			{
				num = ((num << 5) + num) ^ str[i];
				if (i == str.Length - 1 || str[i + 1] == '\0')
				{
					break;
				}
				num2 = ((num2 << 5) + num2) ^ str[i + 1];
			}
			return num + num2 * 1566083941;
		}

		public static long Hash(this string str)
		{
			long num = 5381L;
			long num2 = num;
			for (int i = 0; i < str.Length && str[i] != 0; i += 2)
			{
				num = ((num << 5) + num) ^ str[i];
				if (i == str.Length - 1 || str[i + 1] == '\0')
				{
					break;
				}
				num2 = ((num2 << 5) + num2) ^ str[i + 1];
			}
			return num + num2 * 1566083941;
		}

		public static long Hash(this IEnumerable<string> strs)
		{
			long num = 0L;
			foreach (long item in from x in strs.Select((string x) => x.Hash()).Distinct()
				orderby x
				select x)
			{
				num += item;
			}
			return num;
		}
	}
	public static class UnityObjectExtensions
	{
		private static Regex NameRegex = new Regex("^[^$(]*(?=$|[(])", RegexOptions.Compiled);

		public static bool IsNull(this Object obj)
		{
			if (obj == (Object)null || !Object.op_Implicit(obj))
			{
				return true;
			}
			return false;
		}

		public static bool IsNotNull(this Object obj)
		{
			if (obj != (Object)null && Object.op_Implicit(obj))
			{
				return true;
			}
			return false;
		}

		public static string GetName(this Object obj)
		{
			if (!obj.IsNotNull())
			{
				return string.Empty;
			}
			return obj.name;
		}

		public static string GetCleanedName(this Object obj, bool toUpper = false)
		{
			if (obj.IsNull())
			{
				return null;
			}
			Match match = NameRegex.Match(obj.name);
			if (!match.Success)
			{
				return null;
			}
			string text = match.Value.Trim();
			if (toUpper)
			{
				text = text?.ToUpperInvariant();
			}
			return text;
		}
	}
	public static class Vector3Extensions
	{
		public static bool WithinSquare(this Vector3 position, int centerX, int centerZ, int size = 10)
		{
			//IL_0000: 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)
			float x = position.x;
			float z = position.z;
			if (x < (float)(centerX - size) || x > (float)(centerX + size))
			{
				return false;
			}
			if (z < (float)(centerZ - size) || z > (float)(centerZ + size))
			{
				return false;
			}
			return true;
		}

		public static Vector2i GetZoneId(this Vector3 position)
		{
			//IL_0000: 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_000e: Unknown result type (might be due to invalid IL or missing references)
			return ZoneUtils.GetZone((int)position.x, (int)position.z);
		}

		public static float DistanceHorizontal(this Vector3 source, Vector3 destination)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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)
			float num = source.x - destination.x;
			float num2 = source.z - destination.z;
			return Mathf.Sqrt(num * num + num2 * num2);
		}

		public static bool WithinHorizontalDistance(this Vector3 pos1, Vector3 pos2, float distance)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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)
			float num = pos1.x - pos2.x;
			float num2 = pos1.z - pos2.z;
			return num * num + num2 * num2 < distance * distance;
		}
	}
	public static class ZdoExtensions
	{
		private static int NoiseHash = "noise".HashInteger();

		private static int TamedHash = "tamed".HashInteger();

		private static int EventCreatureHash = "EventCreature".HashInteger();

		private static int HuntPlayerHash = "huntplayer".HashInteger();

		private static int FactionHash = "faction".HashInteger();

		public static float GetNoise(this ZDO zdo)
		{
			return zdo.GetFloat(NoiseHash, 0f);
		}

		public static bool GetTamed(this ZDO zdo)
		{
			return zdo.GetBool(TamedHash, false);
		}

		public static bool GetEventCreature(this ZDO zdo)
		{
			return zdo.GetBool(EventCreatureHash, false);
		}

		public static Faction? GetFaction(this ZDO zdo)
		{
			int @int = zdo.GetInt(FactionHash, -1);
			if (@int < 0)
			{
				return null;
			}
			return (Faction)@int;
		}

		public static void SetFaction(this ZDO zdo, Faction faction)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected I4, but got Unknown
			zdo.Set(FactionHash, (int)faction, false);
		}

		public static bool GetHuntPlayer(this ZDO zdo)
		{
			return zdo.GetBool(HuntPlayerHash, false);
		}

		public static void SetHuntPlayer(this ZDO zdo, bool huntPlayer)
		{
			zdo.Set(HuntPlayerHash, huntPlayer);
		}
	}
}
namespace SpawnThat.Utilities.Enums
{
	public enum Daytime
	{
		All,
		Day,
		Night,
		Morning,
		Afternoon,
		Midnight,
		Midday
	}
	public static class DaytimeExtensions
	{
		public static bool IsActive(this Daytime daytime, float? fraction = null)
		{
			float valueOrDefault = fraction.GetValueOrDefault();
			if (!fraction.HasValue)
			{
				valueOrDefault = EnvMan.instance.GetDayFraction();
				fraction = valueOrDefault;
			}
			switch (daytime)
			{
			case Daytime.Day:
				if (fraction.HasValue)
				{
					valueOrDefault = fraction.GetValueOrDefault();
					if (valueOrDefault >= 0.25f && valueOrDefault <= 0.75f)
					{
						return true;
					}
				}
				break;
			case Daytime.Night:
				if (fraction.HasValue)
				{
					valueOrDefault = fraction.GetValueOrDefault();
					if (valueOrDefault <= 0.25f || valueOrDefault >= 0.75f)
					{
						return true;
					}
				}
				brea

BepInEx/plugins/ASharpPen-Spawn_That/YamlDotNet.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("11.2.1.0")]
[assembly: AssemblyInformationalVersion("11.2.1")]
[assembly: AssemblyTitle("YamlDotNet")]
[assembly: AssemblyDescription("The YamlDotNet library.")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YamlDotNet")]
[assembly: AssemblyCopyright("Copyright (c) Antoine Aubry and contributors 2008 - 2019")]
[assembly: AssemblyTrademark("")]
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("YamlDotNet.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010065e52a453dde5c5b4be5bbe2205755727fce80244b79b894faf8793d80f7db9a96d360b51c220782db32aacee4cb5b8a91bee33aeec700e1f21895c4baadef501eeeac609220d1651603b378173811ee5bb6a002df973d38821bd2fef820c00c174a69faec326a1983b570f07ec66147026b9c8753465de3a8d0c44b613b02af")]
[assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")]
[assembly: AssemblyVersion("11.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
}
namespace System.Collections.Generic
{
	internal static class DeconstructionExtensions
	{
		public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value)
		{
			key = pair.Key;
			value = pair.Value;
		}
	}
}
namespace YamlDotNet
{
	internal sealed class CultureInfoAdapter : CultureInfo
	{
		private readonly IFormatProvider provider;

		public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider)
			: base(baseCulture.LCID)
		{
			this.provider = provider;
		}

		public override object? GetFormat(Type? formatType)
		{
			return provider.GetFormat(formatType);
		}
	}
	internal static class ReflectionExtensions
	{
		private static readonly FieldInfo? RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);

		public static Type? BaseType(this Type type)
		{
			return type.BaseType;
		}

		public static bool IsValueType(this Type type)
		{
			return type.IsValueType;
		}

		public static bool IsGenericType(this Type type)
		{
			return type.IsGenericType;
		}

		public static bool IsGenericTypeDefinition(this Type type)
		{
			return type.IsGenericTypeDefinition;
		}

		public static bool IsInterface(this Type type)
		{
			return type.IsInterface;
		}

		public static bool IsEnum(this Type type)
		{
			return type.IsEnum;
		}

		public static bool IsDbNull(this object value)
		{
			return value is DBNull;
		}

		public static bool HasDefaultConstructor(this Type type)
		{
			if (!type.IsValueType)
			{
				return type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null) != null;
			}
			return true;
		}

		public static TypeCode GetTypeCode(this Type type)
		{
			return Type.GetTypeCode(type);
		}

		public static PropertyInfo? GetPublicProperty(this Type type, string name)
		{
			return type.GetProperty(name);
		}

		public static FieldInfo? GetPublicStaticField(this Type type, string name)
		{
			return type.GetField(name, BindingFlags.Static | BindingFlags.Public);
		}

		public static IEnumerable<PropertyInfo> GetProperties(this Type type, bool includeNonPublic)
		{
			BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
			if (includeNonPublic)
			{
				bindingFlags |= BindingFlags.NonPublic;
			}
			if (!type.IsInterface)
			{
				return type.GetProperties(bindingFlags);
			}
			return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetProperties(bindingFlags));
		}

		public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type)
		{
			return type.GetProperties(includeNonPublic: false);
		}

		public static IEnumerable<FieldInfo> GetPublicFields(this Type type)
		{
			return type.GetFields(BindingFlags.Instance | BindingFlags.Public);
		}

		public static IEnumerable<MethodInfo> GetPublicStaticMethods(this Type type)
		{
			return type.GetMethods(BindingFlags.Static | BindingFlags.Public);
		}

		public static MethodInfo GetPrivateStaticMethod(this Type type, string name)
		{
			return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'.");
		}

		public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes)
		{
			return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null);
		}

		public static MethodInfo? GetPublicInstanceMethod(this Type type, string name)
		{
			return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public);
		}

		public static Exception Unwrap(this TargetInvocationException ex)
		{
			Exception innerException = ex.InnerException;
			if (innerException == null)
			{
				return ex;
			}
			if (RemoteStackTraceField != null)
			{
				RemoteStackTraceField.SetValue(innerException, innerException.StackTrace + "\r\n");
			}
			return innerException;
		}

		public static bool IsInstanceOf(this Type type, object o)
		{
			return type.IsInstanceOfType(o);
		}

		public static Attribute[] GetAllCustomAttributes<TAttribute>(this PropertyInfo property)
		{
			return Attribute.GetCustomAttributes(property, typeof(TAttribute));
		}
	}
	internal static class PropertyInfoExtensions
	{
		public static object? ReadValue(this PropertyInfo property, object target)
		{
			return property.GetValue(target, null);
		}
	}
	internal static class StandardRegexOptions
	{
		public const RegexOptions Compiled = RegexOptions.Compiled;
	}
}
namespace YamlDotNet.Serialization
{
	public abstract class BuilderSkeleton<TBuilder> where TBuilder : BuilderSkeleton<TBuilder>
	{
		internal INamingConvention namingConvention = NullNamingConvention.Instance;

		internal ITypeResolver typeResolver;

		internal readonly YamlAttributeOverrides overrides;

		internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories;

		internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories;

		private bool ignoreFields;

		private bool includeNonPublicProperties;

		protected abstract TBuilder Self { get; }

		internal BuilderSkeleton(ITypeResolver typeResolver)
		{
			overrides = new YamlAttributeOverrides();
			typeConverterFactories = new LazyComponentRegistrationList<Nothing, IYamlTypeConverter>
			{
				{
					typeof(YamlDotNet.Serialization.Converters.GuidConverter),
					(Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false)
				},
				{
					typeof(SystemTypeConverter),
					(Nothing _) => new SystemTypeConverter()
				}
			};
			typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>();
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
		}

		internal ITypeInspector BuildTypeInspector()
		{
			ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties);
			if (!ignoreFields)
			{
				typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector);
			}
			return typeInspectorFactories.BuildComponentChain(typeInspector);
		}

		public TBuilder IgnoreFields()
		{
			ignoreFields = true;
			return Self;
		}

		public TBuilder IncludeNonPublicProperties()
		{
			includeNonPublicProperties = true;
			return Self;
		}

		public TBuilder WithNamingConvention(INamingConvention namingConvention)
		{
			this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention");
			return Self;
		}

		public TBuilder WithTypeResolver(ITypeResolver typeResolver)
		{
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
			return Self;
		}

		public abstract TBuilder WithTagMapping(TagName tag, Type type);

		public TBuilder WithAttributeOverride<TClass>(Expression<Func<TClass, object>> propertyAccessor, Attribute attribute)
		{
			overrides.Add(propertyAccessor, attribute);
			return Self;
		}

		public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute)
		{
			overrides.Add(type, member, attribute);
			return Self;
		}

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter)
		{
			return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where)
		{
			IYamlTypeConverter typeConverter2 = typeConverter;
			if (typeConverter2 == null)
			{
				throw new ArgumentNullException("typeConverter");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2));
			return Self;
		}

		public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter
		{
			WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory2 = typeConverterFactory;
			if (typeConverterFactory2 == null)
			{
				throw new ArgumentNullException("typeConverterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped)));
			return Self;
		}

		public TBuilder WithoutTypeConverter<TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter
		{
			return WithoutTypeConverter(typeof(TYamlTypeConverter));
		}

		public TBuilder WithoutTypeConverter(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			typeConverterFactories.Remove(converterType);
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector
		{
			return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			Func<ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory;
			if (typeInspectorFactory2 == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner)));
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory;
			if (typeInspectorFactory2 == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner)));
			return Self;
		}

		public TBuilder WithoutTypeInspector<TTypeInspector>() where TTypeInspector : ITypeInspector
		{
			return WithoutTypeInspector(typeof(TTypeInspector));
		}

		public TBuilder WithoutTypeInspector(Type inspectorType)
		{
			if (inspectorType == null)
			{
				throw new ArgumentNullException("inspectorType");
			}
			typeInspectorFactories.Remove(inspectorType);
			return Self;
		}

		protected IEnumerable<IYamlTypeConverter> BuildTypeConverters()
		{
			return typeConverterFactories.BuildComponentList();
		}
	}
	public delegate TComponent WrapperFactory<TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase;
	public delegate TComponent WrapperFactory<TArgument, TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase;
	[Flags]
	public enum DefaultValuesHandling
	{
		Preserve = 0,
		OmitNull = 1,
		OmitDefaults = 2,
		OmitEmptyCollections = 4
	}
	public sealed class Deserializer : IDeserializer
	{
		private readonly IValueDeserializer valueDeserializer;

		public Deserializer()
			: this(new DeserializerBuilder().BuildValueDeserializer())
		{
		}

		private Deserializer(IValueDeserializer valueDeserializer)
		{
			this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer");
		}

		public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer)
		{
			return new Deserializer(valueDeserializer);
		}

		public T Deserialize<T>(string input)
		{
			using StringReader input2 = new StringReader(input);
			return Deserialize<T>(input2);
		}

		public T Deserialize<T>(TextReader input)
		{
			return Deserialize<T>(new Parser(input));
		}

		public object? Deserialize(TextReader input)
		{
			return Deserialize(input, typeof(object));
		}

		public object? Deserialize(string input, Type type)
		{
			using StringReader input2 = new StringReader(input);
			return Deserialize(input2, type);
		}

		public object? Deserialize(TextReader input, Type type)
		{
			return Deserialize(new Parser(input), type);
		}

		public T Deserialize<T>(IParser parser)
		{
			return (T)Deserialize(parser, typeof(T));
		}

		public object? Deserialize(IParser parser)
		{
			return Deserialize(parser, typeof(object));
		}

		public object? Deserialize(IParser parser, Type type)
		{
			if (parser == null)
			{
				throw new ArgumentNullException("parser");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			YamlDotNet.Core.Events.StreamStart @event;
			bool flag = parser.TryConsume<YamlDotNet.Core.Events.StreamStart>(out @event);
			YamlDotNet.Core.Events.DocumentStart event2;
			bool flag2 = parser.TryConsume<YamlDotNet.Core.Events.DocumentStart>(out event2);
			object result = null;
			if (!parser.Accept<YamlDotNet.Core.Events.DocumentEnd>(out var _) && !parser.Accept<YamlDotNet.Core.Events.StreamEnd>(out var _))
			{
				using SerializerState serializerState = new SerializerState();
				result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer);
				serializerState.OnDeserialization();
			}
			if (flag2)
			{
				parser.Consume<YamlDotNet.Core.Events.DocumentEnd>();
			}
			if (flag)
			{
				parser.Consume<YamlDotNet.Core.Events.StreamEnd>();
			}
			return result;
		}
	}
	public sealed class DeserializerBuilder : BuilderSkeleton<DeserializerBuilder>
	{
		private Lazy<IObjectFactory> objectFactory;

		private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories;

		private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories;

		private readonly Dictionary<TagName, Type> tagMappings;

		private readonly Dictionary<Type, Type> typeMappings;

		private bool ignoreUnmatched;

		protected override DeserializerBuilder Self => this;

		public DeserializerBuilder()
			: base((ITypeResolver)new StaticTypeResolver())
		{
			typeMappings = new Dictionary<Type, Type>();
			objectFactory = new Lazy<IObjectFactory>(() => new DefaultObjectFactory(typeMappings), isThreadSafe: true);
			tagMappings = new Dictionary<TagName, Type>
			{
				{
					FailsafeSchema.Tags.Map,
					typeof(Dictionary<object, object>)
				},
				{
					FailsafeSchema.Tags.Str,
					typeof(string)
				},
				{
					JsonSchema.Tags.Bool,
					typeof(bool)
				},
				{
					JsonSchema.Tags.Float,
					typeof(double)
				},
				{
					JsonSchema.Tags.Int,
					typeof(int)
				},
				{
					DefaultSchema.Tags.Timestamp,
					typeof(DateTime)
				}
			};
			typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner));
			typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner);
			typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner));
			typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone()));
			typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), (ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner));
			nodeDeserializerFactories = new LazyComponentRegistrationList<Nothing, INodeDeserializer>
			{
				{
					typeof(YamlConvertibleNodeDeserializer),
					(Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(YamlSerializableNodeDeserializer),
					(Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(TypeConverterNodeDeserializer),
					(Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters())
				},
				{
					typeof(NullNodeDeserializer),
					(Nothing _) => new NullNodeDeserializer()
				},
				{
					typeof(ScalarNodeDeserializer),
					(Nothing _) => new ScalarNodeDeserializer()
				},
				{
					typeof(ArrayNodeDeserializer),
					(Nothing _) => new ArrayNodeDeserializer()
				},
				{
					typeof(DictionaryNodeDeserializer),
					(Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(CollectionNodeDeserializer),
					(Nothing _) => new CollectionNodeDeserializer(objectFactory.Value)
				},
				{
					typeof(EnumerableNodeDeserializer),
					(Nothing _) => new EnumerableNodeDeserializer()
				},
				{
					typeof(ObjectNodeDeserializer),
					(Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched)
				}
			};
			nodeTypeResolverFactories = new LazyComponentRegistrationList<Nothing, INodeTypeResolver>
			{
				{
					typeof(MappingNodeTypeResolver),
					(Nothing _) => new MappingNodeTypeResolver(typeMappings)
				},
				{
					typeof(YamlConvertibleTypeResolver),
					(Nothing _) => new YamlConvertibleTypeResolver()
				},
				{
					typeof(YamlSerializableTypeResolver),
					(Nothing _) => new YamlSerializableTypeResolver()
				},
				{
					typeof(TagNodeTypeResolver),
					(Nothing _) => new TagNodeTypeResolver(tagMappings)
				},
				{
					typeof(PreventUnknownTagsNodeTypeResolver),
					(Nothing _) => new PreventUnknownTagsNodeTypeResolver()
				},
				{
					typeof(DefaultContainersNodeTypeResolver),
					(Nothing _) => new DefaultContainersNodeTypeResolver()
				}
			};
		}

		public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory)
		{
			IObjectFactory objectFactory2 = objectFactory;
			if (objectFactory2 == null)
			{
				throw new ArgumentNullException("objectFactory");
			}
			this.objectFactory = new Lazy<IObjectFactory>(() => objectFactory2, isThreadSafe: true);
			return this;
		}

		public DeserializerBuilder WithObjectFactory(Func<Type, object> objectFactory)
		{
			if (objectFactory == null)
			{
				throw new ArgumentNullException("objectFactory");
			}
			return WithObjectFactory(new LambdaObjectFactory(objectFactory));
		}

		public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer)
		{
			return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> w)
			{
				w.OnTop();
			});
		}

		public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where)
		{
			INodeDeserializer nodeDeserializer2 = nodeDeserializer;
			if (nodeDeserializer2 == null)
			{
				throw new ArgumentNullException("nodeDeserializer");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2));
			return this;
		}

		public DeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer
		{
			WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory2 = nodeDeserializerFactory;
			if (nodeDeserializerFactory2 == null)
			{
				throw new ArgumentNullException("nodeDeserializerFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped)));
			return this;
		}

		public DeserializerBuilder WithoutNodeDeserializer<TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer
		{
			return WithoutNodeDeserializer(typeof(TNodeDeserializer));
		}

		public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType)
		{
			if (nodeDeserializerType == null)
			{
				throw new ArgumentNullException("nodeDeserializerType");
			}
			nodeDeserializerFactories.Remove(nodeDeserializerType);
			return this;
		}

		public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver)
		{
			return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w)
			{
				w.OnTop();
			});
		}

		public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where)
		{
			INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver;
			if (nodeTypeResolver2 == null)
			{
				throw new ArgumentNullException("nodeTypeResolver");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2));
			return this;
		}

		public DeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver
		{
			WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory2 = nodeTypeResolverFactory;
			if (nodeTypeResolverFactory2 == null)
			{
				throw new ArgumentNullException("nodeTypeResolverFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped)));
			return this;
		}

		public DeserializerBuilder WithoutNodeTypeResolver<TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver
		{
			return WithoutNodeTypeResolver(typeof(TNodeTypeResolver));
		}

		public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType)
		{
			if (nodeTypeResolverType == null)
			{
				throw new ArgumentNullException("nodeTypeResolverType");
			}
			nodeTypeResolverFactories.Remove(nodeTypeResolverType);
			return this;
		}

		public override DeserializerBuilder WithTagMapping(TagName tag, Type type)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (tagMappings.TryGetValue(tag, out Type value))
			{
				throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag");
			}
			tagMappings.Add(tag, type);
			return this;
		}

		public DeserializerBuilder WithTypeMapping<TInterface, TConcrete>() where TConcrete : TInterface
		{
			Type typeFromHandle = typeof(TInterface);
			Type typeFromHandle2 = typeof(TConcrete);
			if (!typeFromHandle.IsAssignableFrom(typeFromHandle2))
			{
				throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'.");
			}
			if (typeMappings.ContainsKey(typeFromHandle))
			{
				typeMappings[typeFromHandle] = typeFromHandle2;
			}
			else
			{
				typeMappings.Add(typeFromHandle, typeFromHandle2);
			}
			return this;
		}

		public DeserializerBuilder WithoutTagMapping(TagName tag)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (!tagMappings.Remove(tag))
			{
				throw new KeyNotFoundException($"Tag '{tag}' is not registered");
			}
			return this;
		}

		public DeserializerBuilder IgnoreUnmatchedProperties()
		{
			ignoreUnmatched = true;
			return this;
		}

		public IDeserializer Build()
		{
			return Deserializer.FromValueDeserializer(BuildValueDeserializer());
		}

		public IValueDeserializer BuildValueDeserializer()
		{
			return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList()));
		}
	}
	public sealed class EmissionPhaseObjectGraphVisitorArgs
	{
		private readonly IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors;

		public IObjectGraphVisitor<IEmitter> InnerVisitor { get; private set; }

		public IEventEmitter EventEmitter { get; private set; }

		public ObjectSerializer NestedObjectSerializer { get; private set; }

		public IEnumerable<IYamlTypeConverter> TypeConverters { get; private set; }

		public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor<IEmitter> innerVisitor, IEventEmitter eventEmitter, IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors, IEnumerable<IYamlTypeConverter> typeConverters, ObjectSerializer nestedObjectSerializer)
		{
			InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor");
			EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter");
			this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors");
			TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters");
			NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer");
		}

		public T GetPreProcessingPhaseObjectGraphVisitor<T>() where T : IObjectGraphVisitor<Nothing>
		{
			return preProcessingPhaseVisitors.OfType<T>().Single();
		}
	}
	public abstract class EventInfo
	{
		public IObjectDescriptor Source { get; }

		protected EventInfo(IObjectDescriptor source)
		{
			Source = source ?? throw new ArgumentNullException("source");
		}
	}
	public class AliasEventInfo : EventInfo
	{
		public AnchorName Alias { get; }

		public bool NeedsExpansion { get; set; }

		public AliasEventInfo(IObjectDescriptor source, AnchorName alias)
			: base(source)
		{
			if (alias.IsEmpty)
			{
				throw new ArgumentNullException("alias");
			}
			Alias = alias;
		}
	}
	public class ObjectEventInfo : EventInfo
	{
		public AnchorName Anchor { get; set; }

		public TagName Tag { get; set; }

		protected ObjectEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class ScalarEventInfo : ObjectEventInfo
	{
		public string RenderedValue { get; set; }

		public ScalarStyle Style { get; set; }

		public bool IsPlainImplicit { get; set; }

		public bool IsQuotedImplicit { get; set; }

		public ScalarEventInfo(IObjectDescriptor source)
			: base(source)
		{
			Style = source.ScalarStyle;
			RenderedValue = string.Empty;
		}
	}
	public sealed class MappingStartEventInfo : ObjectEventInfo
	{
		public bool IsImplicit { get; set; }

		public MappingStyle Style { get; set; }

		public MappingStartEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class MappingEndEventInfo : EventInfo
	{
		public MappingEndEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class SequenceStartEventInfo : ObjectEventInfo
	{
		public bool IsImplicit { get; set; }

		public SequenceStyle Style { get; set; }

		public SequenceStartEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class SequenceEndEventInfo : EventInfo
	{
		public SequenceEndEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public interface IAliasProvider
	{
		AnchorName GetAlias(object target);
	}
	public interface IDeserializer
	{
		T Deserialize<T>(string input);

		T Deserialize<T>(TextReader input);

		object? Deserialize(TextReader input);

		object? Deserialize(string input, Type type);

		object? Deserialize(TextReader input, Type type);

		T Deserialize<T>(IParser parser);

		object? Deserialize(IParser parser);

		object? Deserialize(IParser parser, Type type);
	}
	public interface IEventEmitter
	{
		void Emit(AliasEventInfo eventInfo, IEmitter emitter);

		void Emit(ScalarEventInfo eventInfo, IEmitter emitter);

		void Emit(MappingStartEventInfo eventInfo, IEmitter emitter);

		void Emit(MappingEndEventInfo eventInfo, IEmitter emitter);

		void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter);

		void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter);
	}
	public interface INamingConvention
	{
		string Apply(string value);
	}
	public interface INodeDeserializer
	{
		bool Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value);
	}
	public interface INodeTypeResolver
	{
		bool Resolve(NodeEvent? nodeEvent, ref Type currentType);
	}
	public interface IObjectDescriptor
	{
		object? Value { get; }

		Type Type { get; }

		Type StaticType { get; }

		ScalarStyle ScalarStyle { get; }
	}
	public static class ObjectDescriptorExtensions
	{
		public static object NonNullValue(this IObjectDescriptor objectDescriptor)
		{
			return objectDescriptor.Value ?? throw new InvalidOperationException("Attempted to use a IObjectDescriptor of type '" + objectDescriptor.Type.FullName + "' whose Value is null at a point whete it is invalid to do so. This may indicate a bug in YamlDotNet.");
		}
	}
	public interface IObjectFactory
	{
		object Create(Type type);
	}
	public interface IObjectGraphTraversalStrategy
	{
		void Traverse<TContext>(IObjectDescriptor graph, IObjectGraphVisitor<TContext> visitor, TContext context);
	}
	public interface IObjectGraphVisitor<TContext>
	{
		bool Enter(IObjectDescriptor value, TContext context);

		bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context);

		bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context);

		void VisitScalar(IObjectDescriptor scalar, TContext context);

		void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context);

		void VisitMappingEnd(IObjectDescriptor mapping, TContext context);

		void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context);

		void VisitSequenceEnd(IObjectDescriptor sequence, TContext context);
	}
	public interface IPropertyDescriptor
	{
		string Name { get; }

		bool CanWrite { get; }

		Type Type { get; }

		Type? TypeOverride { get; set; }

		int Order { get; set; }

		ScalarStyle ScalarStyle { get; set; }

		T GetCustomAttribute<T>() where T : Attribute;

		IObjectDescriptor Read(object target);

		void Write(object target, object? value);
	}
	public interface IRegistrationLocationSelectionSyntax<TBaseRegistrationType>
	{
		void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void Before<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void After<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void OnTop();

		void OnBottom();
	}
	public interface ITrackingRegistrationLocationSelectionSyntax<TBaseRegistrationType>
	{
		void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;
	}
	public interface ISerializer
	{
		void Serialize(TextWriter writer, object graph);

		string Serialize(object graph);

		void Serialize(TextWriter writer, object graph, Type type);

		void Serialize(IEmitter emitter, object graph);

		void Serialize(IEmitter emitter, object graph, Type type);
	}
	public interface ITypeInspector
	{
		IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container);

		IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched);
	}
	public interface ITypeResolver
	{
		Type Resolve(Type staticType, object? actualValue);
	}
	public interface IValueDeserializer
	{
		object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer);
	}
	public interface IValuePromise
	{
		event Action<object?> ValueAvailable;
	}
	public interface IValueSerializer
	{
		void SerializeValue(IEmitter emitter, object? value, Type? type);
	}
	public interface IYamlConvertible
	{
		void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer);

		void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer);
	}
	public delegate object? ObjectDeserializer(Type type);
	public delegate void ObjectSerializer(object? value, Type? type = null);
	[Obsolete("Please use IYamlConvertible instead")]
	public interface IYamlSerializable
	{
		void ReadYaml(IParser parser);

		void WriteYaml(IEmitter emitter);
	}
	public interface IYamlTypeConverter
	{
		bool Accepts(Type type);

		object? ReadYaml(IParser parser, Type type);

		void WriteYaml(IEmitter emitter, object? value, Type type);
	}
	internal sealed class LazyComponentRegistrationList<TArgument, TComponent> : IEnumerable<Func<TArgument, TComponent>>, IEnumerable
	{
		public sealed class LazyComponentRegistration
		{
			public readonly Type ComponentType;

			public readonly Func<TArgument, TComponent> Factory;

			public LazyComponentRegistration(Type componentType, Func<TArgument, TComponent> factory)
			{
				ComponentType = componentType;
				Factory = factory;
			}
		}

		public sealed class TrackingLazyComponentRegistration
		{
			public readonly Type ComponentType;

			public readonly Func<TComponent, TArgument, TComponent> Factory;

			public TrackingLazyComponentRegistration(Type componentType, Func<TComponent, TArgument, TComponent> factory)
			{
				ComponentType = componentType;
				Factory = factory;
			}
		}

		private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax<TComponent>
		{
			private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations;

			private readonly LazyComponentRegistration newRegistration;

			public RegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, LazyComponentRegistration newRegistration)
			{
				this.registrations = registrations;
				this.newRegistration = newRegistration;
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>()
			{
				if (newRegistration.ComponentType != typeof(TRegistrationType))
				{
					registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				}
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries[index] = newRegistration;
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.After<TRegistrationType>()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				int num = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries.Insert(num + 1, newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.Before<TRegistrationType>()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries.Insert(index, newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.OnBottom()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				registrations.entries.Add(newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.OnTop()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				registrations.entries.Insert(0, newRegistration);
			}
		}

		private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax<TComponent>
		{
			private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations;

			private readonly TrackingLazyComponentRegistration newRegistration;

			public TrackingRegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, TrackingLazyComponentRegistration newRegistration)
			{
				this.registrations = registrations;
				this.newRegistration = newRegistration;
			}

			void ITrackingRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>()
			{
				if (newRegistration.ComponentType != typeof(TRegistrationType))
				{
					registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				}
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				Func<TArgument, TComponent> innerComponentFactory = registrations.entries[index].Factory;
				registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg));
			}
		}

		private readonly List<LazyComponentRegistration> entries = new List<LazyComponentRegistration>();

		public int Count => entries.Count;

		public IEnumerable<Func<TArgument, TComponent>> InReverseOrder
		{
			get
			{
				int i = entries.Count - 1;
				while (i >= 0)
				{
					yield return entries[i].Factory;
					int num = i - 1;
					i = num;
				}
			}
		}

		public LazyComponentRegistrationList<TArgument, TComponent> Clone()
		{
			LazyComponentRegistrationList<TArgument, TComponent> lazyComponentRegistrationList = new LazyComponentRegistrationList<TArgument, TComponent>();
			foreach (LazyComponentRegistration entry in entries)
			{
				lazyComponentRegistrationList.entries.Add(entry);
			}
			return lazyComponentRegistrationList;
		}

		public void Add(Type componentType, Func<TArgument, TComponent> factory)
		{
			entries.Add(new LazyComponentRegistration(componentType, factory));
		}

		public void Remove(Type componentType)
		{
			for (int i = 0; i < entries.Count; i++)
			{
				if (entries[i].ComponentType == componentType)
				{
					entries.RemoveAt(i);
					return;
				}
			}
			throw new KeyNotFoundException("A component registration of type '" + componentType.FullName + "' was not found.");
		}

		public IRegistrationLocationSelectionSyntax<TComponent> CreateRegistrationLocationSelector(Type componentType, Func<TArgument, TComponent> factory)
		{
			return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory));
		}

		public ITrackingRegistrationLocationSelectionSyntax<TComponent> CreateTrackingRegistrationLocationSelector(Type componentType, Func<TComponent, TArgument, TComponent> factory)
		{
			return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory));
		}

		public IEnumerator<Func<TArgument, TComponent>> GetEnumerator()
		{
			return entries.Select((LazyComponentRegistration e) => e.Factory).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		private int IndexOfRegistration(Type registrationType)
		{
			for (int i = 0; i < entries.Count; i++)
			{
				if (registrationType == entries[i].ComponentType)
				{
					return i;
				}
			}
			return -1;
		}

		private void EnsureNoDuplicateRegistrationType(Type componentType)
		{
			if (IndexOfRegistration(componentType) != -1)
			{
				throw new InvalidOperationException("A component of type '" + componentType.FullName + "' has already been registered.");
			}
		}

		private int EnsureRegistrationExists<TRegistrationType>()
		{
			int num = IndexOfRegistration(typeof(TRegistrationType));
			if (num == -1)
			{
				throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered.");
			}
			return num;
		}
	}
	internal static class LazyComponentRegistrationListExtensions
	{
		public static TComponent BuildComponentChain<TComponent>(this LazyComponentRegistrationList<TComponent, TComponent> registrations, TComponent innerComponent)
		{
			return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TComponent, TComponent> factory) => factory(inner));
		}

		public static TComponent BuildComponentChain<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TComponent innerComponent, Func<TComponent, TArgument> argumentBuilder)
		{
			Func<TComponent, TArgument> argumentBuilder2 = argumentBuilder;
			return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TArgument, TComponent> factory) => factory(argumentBuilder2(inner)));
		}

		public static List<TComponent> BuildComponentList<TComponent>(this LazyComponentRegistrationList<Nothing, TComponent> registrations)
		{
			return registrations.Select((Func<Nothing, TComponent> factory) => factory(default(Nothing))).ToList();
		}

		public static List<TComponent> BuildComponentList<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TArgument argument)
		{
			TArgument argument2 = argument;
			return registrations.Select((Func<TArgument, TComponent> factory) => factory(argument2)).ToList();
		}
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct Nothing
	{
	}
	public sealed class ObjectDescriptor : IObjectDescriptor
	{
		public object? Value { get; private set; }

		public Type Type { get; private set; }

		public Type StaticType { get; private set; }

		public ScalarStyle ScalarStyle { get; private set; }

		public ObjectDescriptor(object? value, Type type, Type staticType)
			: this(value, type, staticType, ScalarStyle.Any)
		{
		}

		public ObjectDescriptor(object? value, Type type, Type staticType, ScalarStyle scalarStyle)
		{
			Value = value;
			Type = type ?? throw new ArgumentNullException("type");
			StaticType = staticType ?? throw new ArgumentNullException("staticType");
			ScalarStyle = scalarStyle;
		}
	}
	public delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion);
	public sealed class PropertyDescriptor : IPropertyDescriptor
	{
		private readonly IPropertyDescriptor baseDescriptor;

		public string Name { get; set; }

		public Type Type => baseDescriptor.Type;

		public Type? TypeOverride
		{
			get
			{
				return baseDescriptor.TypeOverride;
			}
			set
			{
				baseDescriptor.TypeOverride = value;
			}
		}

		public int Order { get; set; }

		public ScalarStyle ScalarStyle
		{
			get
			{
				return baseDescriptor.ScalarStyle;
			}
			set
			{
				baseDescriptor.ScalarStyle = value;
			}
		}

		public bool CanWrite => baseDescriptor.CanWrite;

		public PropertyDescriptor(IPropertyDescriptor baseDescriptor)
		{
			this.baseDescriptor = baseDescriptor;
			Name = baseDescriptor.Name;
		}

		public void Write(object target, object? value)
		{
			baseDescriptor.Write(target, value);
		}

		public T GetCustomAttribute<T>() where T : Attribute
		{
			return baseDescriptor.GetCustomAttribute<T>();
		}

		public IObjectDescriptor Read(object target)
		{
			return baseDescriptor.Read(target);
		}
	}
	public sealed class Serializer : ISerializer
	{
		private readonly IValueSerializer valueSerializer;

		private readonly EmitterSettings emitterSettings;

		public Serializer()
			: this(new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default)
		{
		}

		private Serializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings)
		{
			this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer");
			this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings");
		}

		public static Serializer FromValueSerializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings)
		{
			return new Serializer(valueSerializer, emitterSettings);
		}

		public void Serialize(TextWriter writer, object graph)
		{
			Serialize(new Emitter(writer, emitterSettings), graph);
		}

		public string Serialize(object graph)
		{
			using StringWriter stringWriter = new StringWriter();
			Serialize(stringWriter, graph);
			return stringWriter.ToString();
		}

		public void Serialize(TextWriter writer, object graph, Type type)
		{
			Serialize(new Emitter(writer, emitterSettings), graph, type);
		}

		public void Serialize(IEmitter emitter, object graph)
		{
			if (emitter == null)
			{
				throw new ArgumentNullException("emitter");
			}
			EmitDocument(emitter, graph, null);
		}

		public void Serialize(IEmitter emitter, object graph, Type type)
		{
			if (emitter == null)
			{
				throw new ArgumentNullException("emitter");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			EmitDocument(emitter, graph, type);
		}

		private void EmitDocument(IEmitter emitter, object graph, Type? type)
		{
			emitter.Emit(new YamlDotNet.Core.Events.StreamStart());
			emitter.Emit(new YamlDotNet.Core.Events.DocumentStart());
			valueSerializer.SerializeValue(emitter, graph, type);
			emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: true));
			emitter.Emit(new YamlDotNet.Core.Events.StreamEnd());
		}
	}
	public sealed class SerializerBuilder : BuilderSkeleton<SerializerBuilder>
	{
		private class ValueSerializer : IValueSerializer
		{
			private readonly IObjectGraphTraversalStrategy traversalStrategy;

			private readonly IEventEmitter eventEmitter;

			private readonly IEnumerable<IYamlTypeConverter> typeConverters;

			private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;

			private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;

			public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<IYamlTypeConverter> typeConverters, LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories)
			{
				this.traversalStrategy = traversalStrategy;
				this.eventEmitter = eventEmitter;
				this.typeConverters = typeConverters;
				this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories;
				this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories;
			}

			public void SerializeValue(IEmitter emitter, object? value, Type? type)
			{
				IEmitter emitter2 = emitter;
				Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object));
				Type staticType = type ?? typeof(object);
				ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType);
				List<IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters);
				foreach (IObjectGraphVisitor<Nothing> item in preProcessingPhaseObjectGraphVisitors)
				{
					traversalStrategy.Traverse(graph, item, default(Nothing));
				}
				IObjectGraphVisitor<IEmitter> visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor<IEmitter> inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer));
				traversalStrategy.Traverse(graph, visitor, emitter2);
				void NestedObjectSerializer(object? v, Type? t)
				{
					SerializeValue(emitter2, v, t);
				}
			}
		}

		private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory;

		private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;

		private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;

		private readonly LazyComponentRegistrationList<IEventEmitter, IEventEmitter> eventEmitterFactories;

		private readonly IDictionary<Type, TagName> tagMappings = new Dictionary<Type, TagName>();

		private int maximumRecursion = 50;

		private EmitterSettings emitterSettings = EmitterSettings.Default;

		private DefaultValuesHandling defaultValuesHandlingConfiguration;

		protected override SerializerBuilder Self => this;

		public SerializerBuilder()
			: base((ITypeResolver)new DynamicTypeResolver())
		{
			typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner));
			typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner);
			typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner));
			typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone()));
			preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> { 
			{
				typeof(AnchorAssigner),
				(IEnumerable<IYamlTypeConverter> typeConverters) => new AnchorAssigner(typeConverters)
			} };
			emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>
			{
				{
					typeof(CustomSerializationObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer)
				},
				{
					typeof(AnchorAssigningObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor<AnchorAssigner>())
				},
				{
					typeof(DefaultValuesObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor)
				},
				{
					typeof(CommentsObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor)
				}
			};
			eventEmitterFactories = new LazyComponentRegistrationList<IEventEmitter, IEventEmitter> { 
			{
				typeof(TypeAssigningEventEmitter),
				(IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings)
			} };
			objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention);
		}

		public SerializerBuilder WithMaximumRecursion(int maximumRecursion)
		{
			if (maximumRecursion <= 0)
			{
				throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer.");
			}
			this.maximumRecursion = maximumRecursion;
			return this;
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter
		{
			return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory, Action<IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter
		{
			Func<IEventEmitter, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory;
			if (eventEmitterFactory2 == null)
			{
				throw new ArgumentNullException("eventEmitterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory2(inner)));
			return Self;
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter
		{
			WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory;
			if (eventEmitterFactory2 == null)
			{
				throw new ArgumentNullException("eventEmitterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory2(wrapped, inner)));
			return Self;
		}

		public SerializerBuilder WithoutEventEmitter<TEventEmitter>() where TEventEmitter : IEventEmitter
		{
			return WithoutEventEmitter(typeof(TEventEmitter));
		}

		public SerializerBuilder WithoutEventEmitter(Type eventEmitterType)
		{
			if (eventEmitterType == null)
			{
				throw new ArgumentNullException("eventEmitterType");
			}
			eventEmitterFactories.Remove(eventEmitterType);
			return this;
		}

		public override SerializerBuilder WithTagMapping(TagName tag, Type type)
		{
			if (tag.IsEmpty)
			{
				throw new ArgumentException("Non-specific tags cannot be maped");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (tagMappings.TryGetValue(type, out var value))
			{
				throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type");
			}
			tagMappings.Add(type, tag);
			return this;
		}

		public SerializerBuilder WithoutTagMapping(Type type)
		{
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (!tagMappings.Remove(type))
			{
				throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered");
			}
			return this;
		}

		public SerializerBuilder EnsureRoundtrip()
		{
			objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention);
			WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc)
			{
				loc.InsteadOf<TypeAssigningEventEmitter>();
			});
			return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> loc)
			{
				loc.OnBottom();
			});
		}

		public SerializerBuilder DisableAliases()
		{
			preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner));
			emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor));
			return this;
		}

		[Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)]
		public SerializerBuilder EmitDefaults()
		{
			return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve);
		}

		public SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration)
		{
			defaultValuesHandlingConfiguration = configuration;
			return this;
		}

		public SerializerBuilder JsonCompatible()
		{
			emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName();
			return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax<IYamlTypeConverter> w)
			{
				w.InsteadOf<YamlDotNet.Serialization.Converters.GuidConverter>();
			}).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc)
			{
				loc.InsteadOf<TypeAssigningEventEmitter>();
			});
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			TObjectGraphVisitor objectGraphVisitor2 = objectGraphVisitor;
			if (objectGraphVisitor2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitor");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<IYamlTypeConverter> _) => objectGraphVisitor2));
			return this;
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory;
			if (objectGraphVisitorFactory2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<Nothing> wrapped, IEnumerable<IYamlTypeConverter> _) => objectGraphVisitorFactory2(wrapped)));
			return this;
		}

		public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor));
		}

		public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType)
		{
			if (objectGraphVisitorType == null)
			{
				throw new ArgumentNullException("objectGraphVisitorType");
			}
			preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType);
			return this;
		}

		public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory)
		{
			this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory;
			return this;
		}

		public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory;
			if (objectGraphVisitorFactory2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(args)));
			return this;
		}

		public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory;
			if (objectGraphVisitorFactory2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<IEmitter> wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(wrapped, args)));
			return this;
		}

		public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor));
		}

		public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType)
		{
			if (objectGraphVisitorType == null)
			{
				throw new ArgumentNullException("objectGraphVisitorType");
			}
			emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType);
			return this;
		}

		public SerializerBuilder WithIndentedSequences()
		{
			emitterSettings = emitterSettings.WithIndentedSequences();
			return this;
		}

		public ISerializer Build()
		{
			return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings);
		}

		public IValueSerializer BuildValueSerializer()
		{
			IEnumerable<IYamlTypeConverter> typeConverters = BuildTypeConverters();
			ITypeInspector typeInspector = BuildTypeInspector();
			IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion);
			IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter());
			return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone());
		}
	}
	public sealed class StreamFragment : IYamlConvertible
	{
		private readonly List<ParsingEvent> events = new List<ParsingEvent>();

		public IList<ParsingEvent> Events => events;

		void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer)
		{
			events.Clear();
			int num = 0;
			do
			{
				if (!parser.MoveNext())
				{
					throw new InvalidOperationException("The parser has reached the end before deserialization completed.");
				}
				ParsingEvent current = parser.Current;
				events.Add(current);
				num += current.NestingIncrease;
			}
			while (num > 0);
		}

		void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer)
		{
			foreach (ParsingEvent @event in events)
			{
				emitter.Emit(@event);
			}
		}
	}
	public sealed class TagMappings
	{
		private readonly IDictionary<string, Type> mappings;

		public TagMappings()
		{
			mappings = new Dictionary<string, Type>();
		}

		public TagMappings(IDictionary<string, Type> mappings)
		{
			this.mappings = new Dictionary<string, Type>(mappings);
		}

		public void Add(string tag, Type mapping)
		{
			mappings.Add(tag, mapping);
		}

		internal Type? GetMapping(string tag)
		{
			if (!mappings.TryGetValue(tag, out Type value))
			{
				return null;
			}
			return value;
		}
	}
	public sealed class YamlAttributeOverrides
	{
		private struct AttributeKey
		{
			public readonly Type AttributeType;

			public readonly string PropertyName;

			public AttributeKey(Type attributeType, string propertyName)
			{
				AttributeType = attributeType;
				PropertyName = propertyName;
			}

			public override bool Equals(object? obj)
			{
				if (obj is AttributeKey attributeKey && AttributeType.Equals(attributeKey.AttributeType))
				{
					return PropertyName.Equals(attributeKey.PropertyName);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return YamlDotNet.Core.HashCode.CombineHashCodes(AttributeType.GetHashCode(), PropertyName.GetHashCode());
			}
		}

		private sealed class AttributeMapping
		{
			public readonly Type RegisteredType;

			public readonly Attribute Attribute;

			public AttributeMapping(Type registeredType, Attribute attribute)
			{
				RegisteredType = registeredType;
				Attribute = attribute;
			}

			public override bool Equals(object? obj)
			{
				if (obj is AttributeMapping attributeMapping && RegisteredType.Equals(attributeMapping.RegisteredType))
				{
					return Attribute.Equals(attributeMapping.Attribute);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return YamlDotNet.Core.HashCode.CombineHashCodes(RegisteredType.GetHashCode(), Attribute.GetHashCode());
			}

			public int Matches(Type matchType)
			{
				int num = 0;
				Type type = matchType;
				while (type != null)
				{
					num++;
					if (type == RegisteredType)
					{
						return num;
					}
					type = type.BaseType();
				}
				if (matchType.GetInterfaces().Contains(RegisteredType))
				{
					return num;
				}
				return 0;
			}
		}

		private readonly Dictionary<AttributeKey, List<AttributeMapping>> overrides = new Dictionary<AttributeKey, List<AttributeMapping>>();

		public T? GetAttribute<T>(Type type, string member) where T : Attribute
		{
			if (overrides.TryGetValue(new AttributeKey(typeof(T), member), out List<AttributeMapping> value))
			{
				int num = 0;
				AttributeMapping attributeMapping = null;
				foreach (AttributeMapping item in value)
				{
					int num2 = item.Matches(type);
					if (num2 > num)
					{
						num = num2;
						attributeMapping = item;
					}
				}
				if (num > 0)
				{
					return (T)attributeMapping.Attribute;
				}
			}
			return null;
		}

		public void Add(Type type, string member, Attribute attribute)
		{
			AttributeMapping item = new AttributeMapping(type, attribute);
			AttributeKey key = new AttributeKey(attribute.GetType(), member);
			if (!overrides.TryGetValue(key, out List<AttributeMapping> value))
			{
				value = new List<AttributeMapping>();
				overrides.Add(key, value);
			}
			else if (value.Contains(item))
			{
				throw new InvalidOperationException($"Attribute ({attribute}) already set for Type {type.FullName}, Member {member}");
			}
			value.Add(item);
		}

		public YamlAttributeOverrides Clone()
		{
			YamlAttributeOverrides yamlAttributeOverrides = new YamlAttributeOverrides();
			foreach (KeyValuePair<AttributeKey, List<AttributeMapping>> @override in overrides)
			{
				foreach (AttributeMapping item in @override.Value)
				{
					yamlAttributeOverrides.Add(item.RegisteredType, @override.Key.PropertyName, item.Attribute);
				}
			}
			return yamlAttributeOverrides;
		}

		public void Add<TClass>(Expression<Func<TClass, object>> propertyAccessor, Attribute attribute)
		{
			PropertyInfo propertyInfo = propertyAccessor.AsProperty();
			Add(typeof(TClass), propertyInfo.Name, attribute);
		}
	}
	public sealed class YamlAttributeOverridesInspector : TypeInspectorSkeleton
	{
		public sealed class OverridePropertyDescriptor : IPropertyDescriptor
		{
			private readonly IPropertyDescriptor baseDescriptor;

			private readonly YamlAttributeOverrides overrides;

			private readonly Type classType;

			public string Name => baseDescriptor.Name;

			public bool CanWrite => baseDescriptor.CanWrite;

			public Type Type => baseDescriptor.Type;

			public Type? TypeOverride
			{
				get
				{
					return baseDescriptor.TypeOverride;
				}
				set
				{
					baseDescriptor.TypeOverride = value;
				}
			}

			public int Order
			{
				get
				{
					return baseDescriptor.Order;
				}
				set
				{
					baseDescriptor.Order = value;
				}
			}

			public ScalarStyle ScalarStyle
			{
				get
				{
					return baseDescriptor.ScalarStyle;
				}
				set
				{
					baseDescriptor.ScalarStyle = value;
				}
			}

			public OverridePropertyDescriptor(IPropertyDescriptor baseDescriptor, YamlAttributeOverrides overrides, Type classType)
			{
				this.baseDescriptor = baseDescriptor;
				this.overrides = overrides;
				this.classType = classType;
			}

			public void Write(object target, object? value)
			{
				baseDescriptor.Write(target, value);
			}

			public T GetCustomAttribute<T>() where T : Attribute
			{
				return overrides.GetAttribute<T>(classType, Name) ?? baseDescriptor.GetCustomAttribute<T>();
			}

			public IObjectDescriptor Read(object target)
			{
				return baseDescriptor.Read(target);
			}
		}

		private readonly ITypeInspector innerTypeDescriptor;

		private readonly YamlAttributeOverrides overrides;

		public YamlAttributeOverridesInspector(ITypeInspector innerTypeDescriptor, YamlAttributeOverrides overrides)
		{
			this.innerTypeDescriptor = innerTypeDescriptor;
			this.overrides = overrides;
		}

		public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
		{
			Type type2 = type;
			IEnumerable<IPropertyDescriptor> enumerable = innerTypeDescriptor.GetProperties(type2, container);
			if (overrides != null)
			{
				enumerable = enumerable.Select((Func<IPropertyDescriptor, IPropertyDescriptor>)((IPropertyDescriptor p) => new OverridePropertyDescriptor(p, overrides, type2)));
			}
			return enumerable;
		}
	}
	public sealed class YamlAttributesTypeInspector : TypeInspectorSkeleton
	{
		private readonly ITypeInspector innerTypeDescriptor;

		public YamlAttributesTypeInspector(ITypeInspector innerTypeDescriptor)
		{
			this.innerTypeDescriptor = innerTypeDescriptor;
		}

		public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
		{
			return from p in (from p in innerTypeDescriptor.GetProperties(type, container)
					where p.GetCustomAttribute<YamlIgnoreAttribute>() == null
					select p).Select((Func<IPropertyDescriptor, IPropertyDescriptor>)delegate(IPropertyDescriptor p)
				{
					PropertyDescriptor propertyDescriptor = new PropertyDescriptor(p);
					YamlMemberAttribute customAttribute = p.GetCustomAttribute<YamlMemberAttribute>();
					if (customAttribute != null)
					{
						if (customAttribute.SerializeAs != null)
						{
							propertyDescriptor.TypeOverride = customAttribute.SerializeAs;
						}
						propertyDescriptor.Order = customAttribute.Order;
						propertyDescriptor.ScalarStyle = customAttribute.ScalarStyle;
						if (customAttribute.Alias != null)
						{
							propertyDescriptor.Name = customAttribute.Alias;
						}
					}
					return propertyDescriptor;
				})
				orderby p.Order
				select p;
		}
	}
	internal static class YamlFormatter
	{
		public static readonly NumberFormatInfo NumberFormat = new NumberFormatInfo
		{
			CurrencyDecimalSeparator = ".",
			CurrencyGroupSeparator = "_",
			CurrencyGroupSizes = new int[1] { 3 },
			CurrencySymbol = string.Empty,
			CurrencyDecimalDigits = 99,
			NumberDecimalSeparator = ".",
			NumberGroupSeparator = "_",
			NumberGroupSizes = new int[1] { 3 },
			NumberDecimalDigits = 99,
			NaNSymbol = ".nan",
			PositiveInfinitySymbol = ".inf",
			NegativeInfinitySymbol = "-.inf"
		};

		public static string FormatNumber(object number)
		{
			return Convert.ToString(number, NumberFormat);
		}

		public static string FormatNumber(double number)
		{
			return number.ToString("G17", NumberFormat);
		}

		public static string FormatNumber(float number)
		{
			return number.ToString("G17", NumberFormat);
		}

		public static string FormatBoolean(object boolean)
		{
			if (!boolean.Equals(true))
			{
				return "false";
			}
			return "true";
		}

		public static string FormatDateTime(object dateTime)
		{
			return ((DateTime)dateTime).ToString("o", CultureInfo.InvariantCulture);
		}

		public static string FormatTimeSpan(object timeSpan)
		{
			return ((TimeSpan)timeSpan).ToString();
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class YamlIgnoreAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class YamlMemberAttribute : Attribute
	{
		private DefaultValuesHandling? defaultValuesHandling;

		public string? Description { get; set; }

		public Type? SerializeAs { get; set; }

		public int Order { get; set; }

		public string? Alias { get; set; }

		public bool ApplyNamingConventions { get; set; }

		public ScalarStyle ScalarStyle { get; set; }

		public DefaultValuesHandling DefaultValuesHandling
		{
			get
			{
				return defaultValuesHandling.GetValueOrDefault();
			}
			set
			{
				defaultValuesHandling = value;
			}
		}

		public bool IsDefaultValuesHandlingSpecified => defaultValuesHandling.HasValue;

		public YamlMemberAttribute()
		{
			ScalarStyle = ScalarStyle.Any;
			ApplyNamingConventions = true;
		}

		public YamlMemberAttribute(Type serializeAs)
			: this()
		{
			SerializeAs = serializeAs ?? throw new ArgumentNullException("serializeAs");
		}
	}
}
namespace YamlDotNet.Serialization.ValueDeserializers
{
	public sealed class AliasValueDeserializer : IValueDeserializer
	{
		private sealed class AliasState : Dictionary<AnchorName, ValuePromise>, IPostDeserializationCallback
		{
			public void OnDeserialization()
			{
				foreach (ValuePromise value in base.Values)
				{
					if (!value.HasValue)
					{
						YamlDotNet.Core.Events.AnchorAlias alias = value.Alias;
						throw new AnchorNotFoundException(alias.Start, alias.End, $"Anchor '{alias.Value}' not found");
					}
				}
			}
		}

		private sealed class ValuePromise : IValuePromise
		{
			private object? value;

			public readonly YamlDotNet.Core.Events.AnchorAlias? Alias;

			public bool HasValue { get; private set; }

			public object? Value
			{
				get
				{
					if (!HasValue)
					{
						throw new InvalidOperationException("Value not set");
					}
					return value;
				}
				set
				{
					if (HasValue)
					{
						throw new InvalidOperationException("Value already set");
					}
					HasValue = true;
					this.value = value;
					this.ValueAvailable?.Invoke(value);
				}
			}

			public event Action<object?>? ValueAvailable;

			public ValuePromise(YamlDotNet.Core.Events.AnchorAlias alias)
			{
				Alias = alias;
			}

			public ValuePromise(object? value)
			{
				HasValue = true;
				this.value = value;
			}
		}

		private readonly IValueDeserializer innerDeserializer;

		public AliasValueDeserializer(IValueDeserializer innerDeserializer)
		{
			this.innerDeserializer = innerDeserializer ?? throw new ArgumentNullException("innerDeserializer");
		}

		public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
		{
			if (parser.TryConsume<YamlDotNet.Core.Events.AnchorAlias>(out var @event))
			{
				if (!state.Get<AliasState>().TryGetValue(@event.Value, out ValuePromise value))
				{
					throw new AnchorNotFoundException(@event.Start, @event.End, $"Alias ${@event.Value} cannot precede anchor declaration");
				}
				if (!value.HasValue)
				{
					return value;
				}
				return value.Value;
			}
			AnchorName anchorName = AnchorName.Empty;
			if (parser.Accept<NodeEvent>(out var event2) && !event2.Anchor.IsEmpty)
			{
				anchorName = event2.Anchor;
				AliasState aliasState = state.Get<AliasState>();
				if (!aliasState.ContainsKey(anchorName))
				{
					aliasState[anchorName] = new ValuePromise(new YamlDotNet.Core.Events.AnchorAlias(anchorName));
				}
			}
			object obj = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer);
			if (!anchorName.IsEmpty)
			{
				AliasState aliasState2 = state.Get<AliasState>();
				if (!aliasState2.TryGetValue(anchorName, out ValuePromise value2))
				{
					aliasState2.Add(anchorName, new ValuePromise(obj));
				}
				else if (!value2.HasValue)
				{
					value2.Value = obj;
				}
				else
				{
					aliasState2[anchorName] = new ValuePromise(obj);
				}
			}
			return obj;
		}
	}
	public sealed class NodeValueDeserializer : IValueDeserializer
	{
		private readonly IList<INodeDeserializer> deserializers;

		private readonly IList<INodeTypeResolver> typeResolvers;

		public NodeValueDeserializer(IList<INodeDeserializer> deserializers, IList<INodeTypeResolver> typeResolvers)
		{
			this.deserializers = deserializers ?? throw new ArgumentNullException("deserializers");
			this.typeResolvers = typeResolvers ?? throw new ArgumentNullException("typeResolvers");
		}

		public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
		{
			IValueDeserializer nestedObjectDeserializer2 = nestedObjectDeserializer;
			SerializerState state2 = state;
			parser.Accept<NodeEvent>(out var @event);
			Type typeFromEvent = GetTypeFromEvent(@event, expectedType);
			try
			{
				foreach (INodeDeserializer deserializer in deserializers)
				{
					if (deserializer.Deserialize(parser, typeFromEvent, (IParser r, Type t) => nestedObjectDeserializer2.DeserializeValue(r, t, state2, nestedObjectDeserializer2), out object value))
					{
						return YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(value, expectedType);
					}
				}
			}
			catch (YamlException)
			{
				throw;
			}
			catch (Exception innerException)
			{
				throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "Exception during deserialization", innerException);
			}
			throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "No node deserializer was able to deserialize the node into type " + expectedType.AssemblyQualifiedName);
		}

		private Type GetTypeFromEvent(NodeEvent? nodeEvent, Type currentType)
		{
			using (IEnumerator<INodeTypeResolver> enumerator = typeResolvers.GetEnumerator())
			{
				while (enumerator.MoveNext() && !enumerator.Current.Resolve(nodeEvent, ref currentType))
				{
				}
			}
			return currentType;
		}
	}
}
namespace YamlDotNet.Serialization.Utilities
{
	public interface IPostDeserializationCallback
	{
		void OnDeserialization();
	}
	internal sealed class ObjectAnchorCollection
	{
		private readonly IDictionary<string, object> objectsByAnchor = new Dictionary<string, object>();

		private readonly IDictionary<object, string> anchorsByObject = new Dictionary<object, string>();

		public object this[string anchor]
		{
			get
			{
				if (objectsByAnchor.TryGetValue(anchor, out object value))
				{
					return value;
				}
				throw new AnchorNotFoundException("The anchor '" + anchor + "' does not exists");
			}
		}

		public void Add(string anchor, object @object)
		{
			objectsByAnchor.Add(anchor, @object);
			if (@object != null)
			{
				anchorsByObject.Add(@object, anchor);
			}
		}

		public bool TryGetAnchor(object @object, [MaybeNullWhen(false)] out string? anchor)
		{
			return anchorsByObject.TryGetValue(@object, out anchor);
		}
	}
	internal static class ReflectionUtility
	{
		public static Type? GetImplementedGenericInterface(Type type, Type genericInterfaceType)
		{
			foreach (Type implementedInterface in GetImplementedInterfaces(type))
			{
				if (implementedInterface.IsGenericType() && implementedInterface.GetGenericTypeDefinition() == genericInterfaceType)
				{
					return implementedInterface;
				}
			}
			return null;
		}

		public static IEnumerable<Type> GetImplementedInterfaces(Type type)
		{
			if (type.IsInterface())
			{
				yield return type;
			}
			Type[] interfaces = type.GetInterfaces();
			for (int i = 0; i < interfaces.Length; i++)
			{
				yield return interfaces[i];
			}
		}
	}
	public sealed class SerializerState : IDisposable
	{
		private readonly IDictionary<Type, object> items = new Dictionary<Type, object>();

		public T Get<T>() where T : class, new()
		{
			if (!items.TryGetValue(typeof(T), out object value))
			{
				value = new T();
				items.Add(typeof(T), value);
			}
			return (T)value;
		}

		public void OnDeserialization()
		{
			foreach (IPostDeserializationCallback item in items.Values.OfType<IPostDeserializationCallback>())
			{
				item.OnDeserialization();
			}
		}

		public void Dispose()
		{
			foreach (IDisposable item in items.Values.OfType<IDisposable>())
			{
				item.Dispose();
			}
		}
	}
	internal static class StringExtensions
	{
		private static string ToCamelOrPascalCase(string str, Func<char, char> firstLetterTransform)
		{
			string text = Regex.Replace(str, "([_\\-])(?<char>[a-z])", (Match match) => match.Groups["char"].Value.ToUpperInvariant(), RegexOptions.IgnoreCase);
			return firstLetterTransform(text[0]) + text.Substring(1);
		}

		public static string ToCamelCase(this string str)
		{
			return ToCamelOrPascalCase(str, char.ToLowerInvariant);
		}

		public static string ToPascalCase(this string str)
		{
			return ToCamelOrPascalCase(str, char.ToUpperInvariant);
		}

		public static string FromCamelCase(this string str, string separator)
		{
			string separator2 = separator;
			str = char.ToLower(str[0]) + str.Substring(1);
			str = Regex.Replace(str.ToCamelCase(), "(?<char>[A-Z])", (Match match) => separator2 + match.Groups["char"].Value.ToLowerInvariant());
			return str;
		}
	}
	public static class TypeConverter
	{
		public static T ChangeType<T>(object? value)
		{
			return (T)ChangeType(value, typeof(T));
		}

		public static T ChangeType<T>(object? value, IFormatProvider provider)
		{
			return (T)ChangeType(value, typeof(T), provider);
		}

		public static T ChangeType<T>(object? value, CultureInfo culture)
		{
			return (T)ChangeType(value, typeof(T), culture);
		}

		public static object? ChangeType(object? value, Type destinationType)
		{
			return ChangeType(value, destinationType, CultureInfo.InvariantCulture);
		}

		public static object? ChangeType(object? value, Type destinationType, IFormatProvider provider)
		{
			return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider));
		}

		public static object? ChangeType(object? value, Type destinationType, CultureInfo culture)
		{
			if (value == null || value.IsDbNull())
			{
				if (!destinationType.IsValueType())
				{
					return null;
				}
				return Activator.CreateInstance(destinationType);
			}
			Type type = value.GetType();
			if (destinationType == type || destinationType.IsAssignableFrom(type))
			{
				return value;
			}
			if (destinationType.IsGenericType() && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>))
			{
				Type destinationType2 = destinationType.GetGenericArguments()[0];
				object obj = ChangeType(value, destinationType2, culture);
				return Activator.CreateInstance(destinationType, obj);
			}
			if (destinationType.IsEnum())
			{
				if (!(value is string value2))
				{
					return value;
				}
				return Enum.Parse(destinationType, value2, ignoreCase: true);
			}
			if (destinationType == typeof(bool))
			{
				if ("0".Equals(value))
				{
					return false;
				}
				if ("1".Equals(value))
				{
					return true;
				}
			}
			System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type);
			if (converter != null && converter.CanConvertTo(destinationType))
			{
				return converter.ConvertTo(null, culture, value, destinationType);
			}
			System.ComponentModel.TypeConverter converter2 = TypeDescriptor.GetConverter(destinationType);
			if (converter2 != null && converter2.CanConvertFrom(type))
			{
				return converter2.ConvertFrom(null, culture, value);
			}
			Type[] array = new Type[2] { type, destinationType };
			for (int i = 0; i < array.Length; i++)
			{
				foreach (MethodInfo publicStaticMethod2 in array[i].GetPublicStaticMethods())
				{
					if (!publicStaticMethod2.IsSpecialName || (!(publicStaticMethod2.Name == "op_Implicit") && !(publicStaticMethod2.Name == "op_Explicit")) || !destinationType.IsAssignableFrom(publicStaticMethod2.ReturnParameter.ParameterType))
					{
						continue;
					}
					ParameterInfo[] parameters = publicStaticMethod2.GetParameters();
					if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(type))
					{
						try
						{
							return publicStaticMethod2.Invoke(null, new object[1] { value });
						}
						catch (TargetInvocationException ex)
						{
							throw ex.Unwrap();
						}
					}
				}
			}
			if (type == typeof(string))
			{
				try
				{
					MethodInfo publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider));
					if (publicStaticMethod != null)
					{
						return publicStaticMethod.Invoke(null, new object[2] { value, culture });
					}
					publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string));
					if (publicStaticMethod != null)
					{
						return publicStaticMethod.Invoke(null, new object[1] { value });
					}
				}
				catch (TargetInvocationException ex2)
				{
					throw ex2.Unwrap();
				}
			}
			if (destinationType == typeof(TimeSpan))
			{
				return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture));
			}
			return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture);
		}

		[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
		public static void RegisterTypeConverter<TConvertible, TConverter>() where TConverter : System.ComponentModel.TypeConverter
		{
			if (!TypeDescriptor.GetAttributes(typeof(TConvertible)).OfType<TypeConverterAttribute>().Any((TypeConverterAttribute a) => a.ConverterTypeName == typeof(TConverter).AssemblyQualifiedName))
			{
				TypeDescriptor.AddAttributes(typeof(TConvertible), new TypeConverterAttribute(typeof(TConverter)));
			}
		}
	}
}
namespace YamlDotNet.Serialization.TypeResolvers
{
	public sealed class DynamicTypeResolver : ITypeResolver
	{
		public Type Resolve(Type staticType, object? actualValue)
		{
			if (actualValue == null)
			{
				return staticType;
			}
			return actualValue.GetType();
		}
	}
	public sealed class StaticTypeResolver : ITypeResolver
	{
		public Type Resolve(Type staticType, object? actualValue)
		{
			return staticType;
		}
	}
}
namespace YamlDotNet.Serialization.TypeInspectors
{
	public sealed class CachedTypeInspector : TypeInspectorSkeleton
	{
		private readonly ITypeInspector innerTypeDescriptor;

		private readonly ConcurrentDictionary<Type, List<IPropertyDescriptor>> cache = new ConcurrentDictionary<Type, List<IPropertyDescriptor>>();

		public CachedTypeInspector(ITypeInspector innerTypeDescriptor)
		{
			this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor");
		}

		public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
		{
			object container2 = container;
			return cache.GetOrAdd(type, (Type t) => innerTypeDescriptor.GetProperties(t, container2).ToList());
		}
	}
	public sealed class CompositeTypeInspector : TypeInspectorSkeleton
	{
		private readonly IEnumerable<ITypeInspector> typeInspectors;

		public CompositeTypeInspector(params ITypeInspector[] typeInspectors)
			: this((IEnumerable<ITypeInspector>)typeInspectors)
		{
		}

		public CompositeTypeInspector(IEnumerable<ITypeInspector> typeInspectors)
		{
			this.typeInspectors = typeInspectors?.ToList() ?? throw new ArgumentNullException("typeInspectors");
		}

		public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
		{
			Type type2 = type;
			object container2 = container;
			return typeInspectors.SelectMany((ITypeInspector i) => i.GetProperties(type2, container2));
		}
	}
	public sealed class NamingConventionTypeInspector : TypeInspectorSkeleton
	{
		private readonly ITypeInspector innerTypeDescriptor;

		private readonly INamingConvention namingConvention;

		public NamingConventionTypeInspector(ITypeInspector innerTypeDescriptor, INamingConvention namingConvention)
		{
			this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor");
			this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention");
		}

		public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
		{
			return innerTypeDescriptor.GetProperties(type, container).Select(delegate(IPropertyDescriptor p)
			{
				YamlMemberAttribute customAttribute = p.GetCustomAttribute<YamlMemberAttribute>();
				return (customAttribute != null && !customAttribute.ApplyNamingConventions) ? p : new PropertyDescriptor(p)
				{
					Name = namingConvention.Apply(p.Name)
				};
			});
		}
	}
	public sealed class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton
	{
		private readonly ITypeInspector innerTypeDescriptor;

		public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor)
		{
			this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor");
		}

		public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
		{
			return from p in innerTypeDescriptor.GetProperties(type, container)
				where p.CanWrite
				select p;
		}
	}
	public sealed class ReadableFieldsTypeInspector : TypeInspectorSkeleton
	{
		private sealed class ReflectionFieldDescriptor : IPropertyDescriptor
		{
			private readonly FieldInfo fieldInfo;

			private readonly ITypeResolver typeResolver;

			public string Name => fieldInfo.Name;

			public Type Type => fieldInfo.FieldType;

			public Type? TypeOverride { get; set; }

			public int Order { get; set; }

			public bool CanWrite => !fieldInfo.IsInitOnly;

			public ScalarStyle ScalarStyle { get; set; }

			public ReflectionFieldDescriptor(FieldInfo fieldInfo, ITypeResolver typeResolver)
			{
				this.fieldInfo = fieldInfo;
				this.typeResolver = typeResolver;
				ScalarStyle = ScalarStyle.Any;
			}

			public void Write(object target, object? value)
			{
				fieldInfo.SetValue(target, value);
			}

			public T GetCustomAttribute<T>() where T : Attribute
			{
				return (T)fieldInfo.GetCustomAttributes(typeof(T), inherit: true).FirstOrDefault();
			}

			public IObjectDescriptor Read(object target)
			{
				object value = fieldInfo.GetValue(target);
				Type type = TypeOverride ?? typeResolver.Resolve(Type, value);
				return new ObjectDescriptor(value, type, Type, ScalarStyle);
			}
		}

		private readonly ITypeResolver typeResolver;

		public ReadableFieldsTypeInspector(ITypeResolver typeResolver)
		{
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
		}

		public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
		{
			return type.GetPublicFields().Select((Func<FieldInfo, IPropertyDescriptor>)((FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver)));
		}
	}
	public sealed class ReadablePropertiesTypeInspector : TypeInspectorSkeleton
	{
		private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor
		{
			private readonly PropertyInfo propertyInfo;

			private readonly ITypeResolver typeResolver;

			public string Name => propertyInfo.Name;

			public Type Type => propertyInfo.PropertyType;

			public Type? TypeOverride { get; set; }

			public int Order { get; set; }

			public bool CanWrite => propertyInfo.CanWrite;

			public ScalarStyle ScalarStyle { get; set; }

			public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver)
			{
				this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo");
				this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
				ScalarStyle = ScalarStyle.Any;
			}

			public void Write(object target, object? value)
			{
				propertyInfo.SetValue(target, value, null);
			}

			public T GetCustomAttribute<T>() where T : Attribute
			{
				return (T)propertyInfo.GetAllCustomAttributes<T>().FirstOrDefault();
			}

			public IObjectDescriptor Read(object target)
			{
				object obj = propertyInfo.ReadValue(target);
				Type type = TypeOverride ?? typeResolver.Resolve(Type, obj);
				return new ObjectDescriptor(obj, type, Type, ScalarStyle);
			}
		}

		private readonly ITypeResolver typeResolver;

		private readonly bool includeNonPublicProperties;

		public ReadablePropertiesTypeInspector(ITypeResolver typeResolver)
			: this(typeResolver, includeNonPublicProperties: false)
		{
		}

		public ReadablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties)
		{
			this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
			this.includeNonPublicProperties = includeNonPublicProperties;
		}

		private static bool IsValidProperty(PropertyInfo property)
		{
			if (property.CanRead)
			{
				return property.GetGetMethod(nonPublic: true).GetParameters().Length == 0;
			}
			return false;
		}

		public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
		{
			return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func<PropertyInfo, IPropertyDescriptor>)((PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver)));
		}
	}
	public abstract class TypeInspectorSkeleton : ITypeInspector
	{
		public abstract IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container);

		public IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched)
		{
			string name2 = name;
			IEnumerable<IPropertyDescriptor> enumerable = from p in GetProperties(type, container)
				where p.Name == name2
				select p;
			using IEnumerator<IPropertyDescriptor> enumerator = enumerable.GetEnumerator();
			if (!enumerator.MoveNext())
			{
				if (ignoreUnmatched)
				{
					return null;
				}
				throw new SerializationException("Property '" + name2 + "' not found on type '" + type.FullName + "'.");
			}
			IPropertyDescriptor current = enumerator.Current;
			if (enumerator.MoveNext())
			{
				throw new SerializationException("Multiple properties with the name/alias '" + name2 + "' already exists on type '" + type.FullName + "', maybe you're misusing YamlAlias or maybe you are using the wrong naming convention? The matching properties are: " + string.Join(", ", enumerable.Select((IPropertyDescriptor p) => p.Name).ToArray()));
			}
			return current;
		}
	}
}
namespace YamlDotNet.Serialization.Schemas
{
	public sealed class FailsafeSchema
	{
		public static class Tags
		{
			public static readonly TagName Map = new TagName("tag:yaml.org,2002:map");

			public static readonly TagName Seq = new TagName("tag:yaml.org,2002:seq");

			public static readonly TagName Str = new TagName("tag:yaml.org,2002:str");
		}
	}
	public sealed class JsonSchema
	{
		public static class Tags
		{
			public static readonly TagName Null = new TagName("tag:yaml.org,2002:null");

			public static readonly TagName Bool = new TagName("tag:yaml.org,2002:bool");

			public static readonly TagName Int = new TagName("tag:yaml.org,2002:int");

			public static readonly TagName Float = new TagName("tag:yaml.org,2002:float");
		}
	}
	public sealed class CoreSchema
	{
		public static class Tags
		{
		}
	}
	public sealed class DefaultSchema
	{
		public stat

BepInEx/plugins/Azumatt-FirstPersonMode/FirstPersonMode.dll

Decompiled 8 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using FirstPersonMode.Util;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("FirstPersonMode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Azumatt")]
[assembly: AssemblyProduct("FirstPersonMode")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")]
[assembly: AssemblyFileVersion("1.2.3")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.3.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace FirstPersonMode
{
	[HarmonyPatch(typeof(InstanceRenderer), "OnEnable")]
	internal static class InstanceRendererOnEnablePatch
	{
		private static readonly int CamCull = Shader.PropertyToID("_CamCull");

		private static void Prefix(InstanceRenderer __instance)
		{
			Transform parent = ((Component)__instance).gameObject.transform.parent;
			if (((parent != null) ? ((Object)parent).name : null) == "grassroot")
			{
				__instance.m_material.SetFloat(CamCull, 0f);
			}
		}
	}
	[HarmonyPatch(typeof(Pickable), "Awake")]
	internal static class PickableAwakePatch
	{
		private static void Postfix(Pickable __instance)
		{
			Renderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<Renderer>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Material[] materials = componentsInChildren[i].materials;
				for (int j = 0; j < materials.Length; j++)
				{
					materials[j].SetFloat("_CamCull", 0f);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Character), "SetVisible")]
	public static class CharacterSetVisiblePatch
	{
		private static bool Prefix(ref Character __instance, bool visible)
		{
			//IL_0066: 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)
			if (FirstPersonModePlugin.FirstPersonEnabled.Value != FirstPersonModePlugin.Toggle.On)
			{
				return true;
			}
			if ((Object)(object)__instance.m_lodGroup == (Object)null || __instance.m_lodVisible == visible || (__instance.IsPlayer() && !visible))
			{
				return false;
			}
			__instance.m_lodVisible = visible;
			__instance.m_lodGroup.localReferencePoint = (Vector3)(__instance.m_lodVisible ? __instance.m_originalLocalRef : new Vector3(999999f, 999999f, 999999f));
			return false;
		}
	}
	[HarmonyPatch(typeof(GameCamera), "Awake")]
	public static class GameCameraAwakePatch
	{
		private static void Postfix(ref GameCamera __instance)
		{
			if (FirstPersonModePlugin.FirstPersonEnabled.Value == FirstPersonModePlugin.Toggle.On)
			{
				FirstPersonModePlugin.CameraConstants.ZoomSens = __instance.m_zoomSens;
				FirstPersonModePlugin.CameraConstants.MinDistance = __instance.m_minDistance;
				FirstPersonModePlugin.CameraConstants.MaxDistance = __instance.m_maxDistance;
			}
		}
	}
	[HarmonyPatch(typeof(VisEquipment), "SetHelmetEquipped")]
	public static class UpdateVisEquipment_SetHelmetequiped2Nothing
	{
		private static bool _helmetVisRemovedPrefabrestored;

		private static bool _helmetVisRemoved;

		private static void Prefix(VisEquipment __instance, bool ___m_isPlayer, int hash, int hairHash, ref int ___m_currentHelmetItemHash, ref GameObject ___m_helmetItemInstance, ref bool ___m_helmetHideHair, ref Transform ___m_helmet)
		{
			if (FirstPersonModePlugin.NoHeadMode.Value == FirstPersonModePlugin.Toggle.On || (Object)(object)__instance == (Object)null || !Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent<Player>()) || (Object)(object)((Component)__instance).gameObject.GetComponent<Player>() != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			if (___m_currentHelmetItemHash != hash)
			{
				_helmetVisRemoved = false;
			}
			if ((Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(hash);
			if (!Object.op_Implicit((Object)(object)itemPrefab))
			{
				return;
			}
			if (FirstPersonModePlugin.DynamicPerson.IsFirstPerson && !_helmetVisRemoved)
			{
				int childCount = itemPrefab.transform.childCount;
				for (int i = 0; i < childCount; i++)
				{
					Transform child = itemPrefab.transform.GetChild(i);
					string name = ((Object)((Component)child).gameObject).name;
					if (name == "attach" || name == "attach_skin")
					{
						Renderer[] componentsInChildren = ((Component)child).gameObject.GetComponentsInChildren<Renderer>();
						for (int j = 0; j < componentsInChildren.Length; j++)
						{
							componentsInChildren[j].shadowCastingMode = (ShadowCastingMode)3;
						}
					}
				}
				___m_currentHelmetItemHash = -1;
				_helmetVisRemoved = true;
				_helmetVisRemovedPrefabrestored = false;
			}
			else if (!FirstPersonModePlugin.DynamicPerson.IsFirstPerson && _helmetVisRemoved)
			{
				_helmetVisRemoved = false;
				___m_currentHelmetItemHash = -1;
			}
		}

		private static void Postfix(VisEquipment __instance, bool ___m_isPlayer, int hash, int hairHash, ref int ___m_currentHelmetItemHash, ref GameObject ___m_helmetItemInstance, ref bool ___m_helmetHideHair, ref Transform ___m_helmet)
		{
			if (FirstPersonModePlugin.NoHeadMode.Value == FirstPersonModePlugin.Toggle.On || !Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent<Player>()) || _helmetVisRemovedPrefabrestored || (Object)(object)((Component)__instance).gameObject.GetComponent<Player>() != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(hash);
			if (!Object.op_Implicit((Object)(object)itemPrefab))
			{
				return;
			}
			int childCount = itemPrefab.transform.childCount;
			for (int i = 0; i < childCount; i++)
			{
				Transform child = itemPrefab.transform.GetChild(i);
				string name = ((Object)((Component)child).gameObject).name;
				if (name == "attach" || name == "attach_skin")
				{
					Renderer[] componentsInChildren = ((Component)child).gameObject.GetComponentsInChildren<Renderer>();
					for (int j = 0; j < componentsInChildren.Length; j++)
					{
						componentsInChildren[j].shadowCastingMode = (ShadowCastingMode)1;
					}
				}
			}
			_helmetVisRemovedPrefabrestored = true;
		}
	}
	[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
	public static class GameCameraUpdatePatch
	{
		private static void Postfix(ref GameCamera __instance, float dt)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			if (FirstPersonModePlugin.FirstPersonEnabled.Value != FirstPersonModePlugin.Toggle.On || (FirstPersonModePlugin.CHEInBuildMode != null && FirstPersonModePlugin.CHEIsLoaded && (bool)FirstPersonModePlugin.CHEInBuildMode.Invoke(null, null)))
			{
				return;
			}
			if (__instance.m_freeFly)
			{
				__instance.UpdateFreeFly(dt);
				__instance.UpdateCameraShake(dt);
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			bool flag = FirstPersonModePlugin.DynamicPerson.IsFirstPerson;
			bool flag2 = FirstPersonModePlugin.ToggleFirstPersonHotkey.Value.IsKeyDown();
			if (__instance.m_distance <= 1f && !flag && !flag2)
			{
				flag = true;
				FirstPersonModePlugin.DynamicPerson.IsFirstPerson = true;
				Functions.SetupFP(ref __instance, ref localPlayer);
			}
			else if ((double)__instance.m_minDistance > 0.0 && flag && !flag2)
			{
				flag = false;
				FirstPersonModePlugin.DynamicPerson.IsFirstPerson = false;
				__instance.m_3rdOffset = FirstPersonModePlugin.DynamicPerson.NoFp3RdOffset;
				__instance.m_fpsOffset = FirstPersonModePlugin.DynamicPerson.NoFpFPSOffset;
				__instance.m_minDistance = FirstPersonModePlugin.CameraConstants.MinDistance;
				__instance.m_maxDistance = FirstPersonModePlugin.CameraConstants.MaxDistance;
				__instance.m_zoomSens = FirstPersonModePlugin.CameraConstants.ZoomSens;
				__instance.m_fov = 65f;
				((Character)localPlayer).m_head.localScale = Vector3.one;
				((Character)localPlayer).m_eye.localScale = Vector3.one;
			}
			if (flag2)
			{
				if (FirstPersonModePlugin.DynamicPerson.IsFirstPerson = !flag)
				{
					Functions.SetupFP(ref __instance, ref localPlayer);
				}
				else
				{
					__instance.m_distance = 1.5f;
					__instance.m_3rdOffset = FirstPersonModePlugin.DynamicPerson.NoFp3RdOffset;
					__instance.m_fpsOffset = FirstPersonModePlugin.DynamicPerson.NoFpFPSOffset;
					__instance.m_minDistance = FirstPersonModePlugin.CameraConstants.MinDistance;
					__instance.m_maxDistance = FirstPersonModePlugin.CameraConstants.MaxDistance;
					__instance.m_zoomSens = FirstPersonModePlugin.CameraConstants.ZoomSens;
					__instance.m_fov = 65f;
					((Character)localPlayer).m_head.localScale = Vector3.one;
					((Character)localPlayer).m_eye.localScale = Vector3.one;
				}
			}
			__instance.m_camera.fieldOfView = __instance.m_fov;
			__instance.m_skyCamera.fieldOfView = __instance.m_fov;
			if (!Functions.ShouldIgnoreAdjustments(localPlayer))
			{
				if (FirstPersonModePlugin.DynamicPerson.IsFirstPerson)
				{
					Functions.HandleFirstPersonMode(ref __instance);
				}
				else
				{
					Functions.HandleNotFirstPersonMode(ref __instance, localPlayer);
				}
			}
			if (((Character)localPlayer).IsDead() && Object.op_Implicit((Object)(object)localPlayer.GetRagdoll()))
			{
				((Component)__instance).transform.LookAt(localPlayer.GetRagdoll().GetAverageBodyPosition());
			}
			else
			{
				Functions.SetCameraTransform(ref __instance, localPlayer, dt);
			}
			__instance.UpdateCameraShake(dt);
		}
	}
	[HarmonyPatch(typeof(DamageText), "Awake")]
	internal static class DamageTextAwakePatch
	{
		private static void Prefix(DamageText __instance)
		{
			__instance.m_maxTextDistance = 100f;
			__instance.m_smallFontDistance = 35f;
		}
	}
	[HarmonyPatch(typeof(Hud), "UpdateShipHud")]
	internal static class UpdateHud_fixshiphud
	{
		private static void Postfix(Hud __instance, Player player)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			if (FirstPersonModePlugin.FirstPersonEnabled.Value != FirstPersonModePlugin.Toggle.On)
			{
				return;
			}
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera == (Object)null)
			{
				return;
			}
			if (FirstPersonModePlugin.DynamicPerson.IsFirstPerson)
			{
				__instance.m_shipControlsRoot.transform.position = new Vector3((float)mainCamera.pixelWidth * 0.5f, (float)mainCamera.pixelHeight * 0.2f, 0f);
				return;
			}
			Ship controlledShip = player.GetControlledShip();
			if ((Object)(object)controlledShip != (Object)null)
			{
				__instance.m_shipControlsRoot.transform.position = mainCamera.WorldToScreenPoint(controlledShip.m_controlGuiPos.position);
			}
		}
	}
	[BepInPlugin("Azumatt.FirstPersonMode", "FirstPersonMode", "1.2.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class FirstPersonModePlugin : BaseUnityPlugin
	{
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct DynamicPerson
		{
			public static bool IsFirstPerson = false;

			public static Vector3 NoFp3RdOffset = Vector3.zero;

			public static Vector3 NoFpFPSOffset = Vector3.zero;

			public static float MaxDeviation = 40f;

			public static Quaternion PlayerRotation = Quaternion.identity;

			public static Rigidbody PlayerRigidbody = null;
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct CameraConstants
		{
			public static float ZoomSens = 10f;

			public static float MinDistance = 1f;

			public static float MaxDistance = 8f;

			public static float NearClipPlaneMax = 0.02f;

			public static float NearClipPlaneMin = 0.01f;
		}

		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			public string Category;

			[UsedImplicitly]
			public Action<ConfigEntryBase> CustomDrawer;
		}

		internal const string ModName = "FirstPersonMode";

		internal const string ModVersion = "1.2.3";

		internal const string Author = "Azumatt";

		private const string ModGUID = "Azumatt.FirstPersonMode";

		private static string ConfigFileName = "Azumatt.FirstPersonMode.cfg";

		private static string ConfigFileFullPath;

		internal static string ConnectionError;

		private readonly Harmony _harmony = new Harmony("Azumatt.FirstPersonMode");

		public static bool CHEIsLoaded;

		private Assembly _cheAssembly;

		public static MethodInfo? CHEInBuildMode;

		public static readonly ManualLogSource FirstPersonModeLogger;

		internal static ConfigEntry<Toggle> FirstPersonEnabled;

		internal static ConfigEntry<Toggle> NoHeadMode;

		internal static ConfigEntry<float> DefaultFOV;

		internal static ConfigEntry<KeyboardShortcut> ToggleFirstPersonHotkey;

		internal static ConfigEntry<KeyboardShortcut> RaiseFOVHotkey;

		internal static ConfigEntry<KeyboardShortcut> LowerFOVHotkey;

		internal static ConfigEntry<float> NearClipPlaneMinConfig;

		internal static ConfigEntry<float> NearClipPlaneMaxConfig;

		public void Awake()
		{
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			FirstPersonEnabled = config("1 - Toggles", "Enable First Person", Toggle.On, "If on, First Person is enabled.");
			NoHeadMode = config("1 - Toggles", "Hide Head", Toggle.Off, "If on, the camera will not use the culling mode and will instead shrink the head to hide it. This method is a bit better overall as your armor isn't see through, but looks a little weird. Headless people always do.");
			DefaultFOV = config("2 - Camera", "Default FOV", 65f, "Default FOV for First Person.");
			NearClipPlaneMinConfig = config("2 - Camera", "NearClipPlaneMin", 0.17f, "Adjusts the nearest distance at which objects are rendered in first person view. Increase to reduce body visibility; too high might clip nearby objects.");
			NearClipPlaneMaxConfig = config("2 - Camera", "NearClipPlaneMax", 0.17f, "Adjusts the nearest distance at which objects are rendered in first person view. Increase to reduce body visibility; too high might clip nearby objects.");
			ToggleFirstPersonHotkey = config<KeyboardShortcut>("3 - Keyboard Shortcuts", "Toggle First Person Shortcut", new KeyboardShortcut((KeyCode)104, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Keyboard Shortcut needed to toggle First Person.");
			RaiseFOVHotkey = config<KeyboardShortcut>("3 - Keyboard Shortcuts", "Raise FOV Shortcut", new KeyboardShortcut((KeyCode)280, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Keyboard Shortcut needed to raise FOV.");
			LowerFOVHotkey = config<KeyboardShortcut>("3 - Keyboard Shortcuts", "Lower FOV Shortcut", new KeyboardShortcut((KeyCode)281, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Keyboard Shortcut needed to lower FOV.");
			CHEIsLoaded = Chainloader.PluginInfos.ContainsKey("Azumatt.BuildCameraCHE");
			if (CHEIsLoaded)
			{
				_cheAssembly = ((object)Chainloader.PluginInfos["Azumatt.BuildCameraCHE"].Instance).GetType().Assembly;
				CHEInBuildMode = _cheAssembly.GetType("Valheim_Build_Camera.Utils")?.GetMethod("InBuildMode", BindingFlags.Static | BindingFlags.Public);
			}
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			SetupWatcher();
		}

		private void Start()
		{
			AutoDoc();
		}

		private void AutoDoc()
		{
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		private void SetupWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			fileSystemWatcher.Changed += ReadConfigValues;
			fileSystemWatcher.Created += ReadConfigValues;
			fileSystemWatcher.Renamed += ReadConfigValues;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(ConfigFileFullPath))
			{
				return;
			}
			try
			{
				FirstPersonModeLogger.LogDebug((object)"ReadConfigValues called");
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch
			{
				FirstPersonModeLogger.LogError((object)("There was an issue loading your " + ConfigFileName));
				FirstPersonModeLogger.LogError((object)"Please check your config entries for spelling and format!");
			}
		}

		private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description)
		{
			return ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
		}

		private ConfigEntry<T> config<T>(string group, string name, T value, string description)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}

		static FirstPersonModePlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			ConnectionError = "";
			FirstPersonModeLogger = Logger.CreateLogSource("FirstPersonMode");
			FirstPersonEnabled = null;
			NoHeadMode = null;
			DefaultFOV = null;
			ToggleFirstPersonHotkey = null;
			RaiseFOVHotkey = null;
			LowerFOVHotkey = null;
			NearClipPlaneMinConfig = null;
			NearClipPlaneMaxConfig = null;
		}
	}
}
namespace FirstPersonMode.Util
{
	public static class KeyboardExtensions
	{
		public static bool IsKeyDown(this KeyboardShortcut shortcut)
		{
			//IL_0002: 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)
			if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey))
			{
				return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey);
			}
			return false;
		}

		public static bool IsKeyHeld(this KeyboardShortcut shortcut)
		{
			//IL_0002: 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)
			if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey))
			{
				return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey);
			}
			return false;
		}
	}
	public static class Functions
	{
		internal static bool ShouldIgnoreAdjustments(Player localPlayer)
		{
			Chat instance = Chat.instance;
			if ((instance == null || !instance.HasFocus()) && !Console.IsVisible() && !InventoryGui.IsVisible() && !StoreGui.IsVisible() && !Menu.IsVisible() && !Minimap.IsOpen() && !((Character)localPlayer).InCutscene())
			{
				return ((Character)localPlayer).InPlaceMode();
			}
			return true;
		}

		internal static void SetupFP(ref GameCamera __instance, ref Player localPlayer)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			FirstPersonModePlugin.DynamicPerson.NoFp3RdOffset = __instance.m_3rdOffset;
			FirstPersonModePlugin.DynamicPerson.NoFpFPSOffset = __instance.m_fpsOffset;
			__instance.m_3rdOffset = Vector3.zero;
			__instance.m_fpsOffset = Vector3.zero;
			__instance.m_minDistance = 0f;
			__instance.m_maxDistance = 0f;
			__instance.m_zoomSens = 0f;
			__instance.m_nearClipPlaneMax = FirstPersonModePlugin.NearClipPlaneMaxConfig.Value;
			__instance.m_nearClipPlaneMin = FirstPersonModePlugin.NearClipPlaneMinConfig.Value;
			__instance.m_fov = FirstPersonModePlugin.DefaultFOV.Value;
			if (FirstPersonModePlugin.NoHeadMode.Value == FirstPersonModePlugin.Toggle.On)
			{
				((Character)localPlayer).m_head.localScale = Vector3.zero;
				((Character)localPlayer).m_eye.localScale = Vector3.zero;
				__instance.m_nearClipPlaneMax = FirstPersonModePlugin.CameraConstants.NearClipPlaneMax;
				__instance.m_nearClipPlaneMin = FirstPersonModePlugin.CameraConstants.NearClipPlaneMin;
			}
		}

		internal static void HandleFirstPersonMode(ref GameCamera __instance)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (FirstPersonModePlugin.RaiseFOVHotkey.Value.IsKeyDown())
			{
				GameCamera obj = __instance;
				obj.m_fov += 1f;
				((Terminal)Console.instance).AddString($"Changed fov to: {__instance.m_fov}");
			}
			else if (FirstPersonModePlugin.LowerFOVHotkey.Value.IsKeyDown())
			{
				GameCamera obj2 = __instance;
				obj2.m_fov -= 1f;
				((Terminal)Console.instance).AddString($"Changed fov to: {__instance.m_fov}");
			}
		}

		internal static void HandleNotFirstPersonMode(ref GameCamera __instance, Player localPlayer)
		{
			_ = __instance.m_minDistance;
			float axis = Input.GetAxis("Mouse ScrollWheel");
			GameCamera obj = __instance;
			obj.m_distance -= axis * __instance.m_zoomSens;
			float num = (((Object)(object)localPlayer.GetControlledShip() != (Object)null) ? __instance.m_maxDistanceBoat : __instance.m_maxDistance);
			__instance.m_distance = Mathf.Clamp(__instance.m_distance, 0f, num);
		}

		internal static void SetCameraTransform(ref GameCamera __instance, Player localPlayer, float dt)
		{
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			if (FirstPersonModePlugin.DynamicPerson.IsFirstPerson)
			{
				Vector3 val = ((Character)localPlayer).GetHeadPoint();
				Vector3 val2 = ((Component)((Character)localPlayer).m_eye).transform.rotation * new Vector3(0f, 0.15f, 0.071f);
				if (Object.op_Implicit((Object)(object)Utils.FindChild(((Component)localPlayer).transform, "Azu_transform")))
				{
					val = Utils.FindChild(Utils.FindChild(((Component)localPlayer).transform, "Azu_transform"), "Head").position;
					val2 = ((Component)((Character)localPlayer).m_eye).transform.rotation * new Vector3(0f, 0.15f, 0.142f);
					__instance.m_nearClipPlaneMax = 0.47f;
				}
				__instance.m_nearClipPlaneMax = FirstPersonModePlugin.NearClipPlaneMaxConfig.Value;
				((Component)__instance).transform.position = val + val2;
				if (((Character)localPlayer).TakeInput() && Input.GetAxis("Mouse ScrollWheel") < 0f && !((Character)localPlayer).InPlaceMode())
				{
					GameCamera obj = __instance;
					obj.m_minDistance += 2f;
					FirstPersonModePlugin.FirstPersonModeLogger.LogDebug((object)("m_minDistance: " + __instance.m_minDistance));
				}
				Quaternion rotation = ((Character)localPlayer).m_eye.rotation;
				float y = ((Quaternion)(ref rotation)).eulerAngles.y;
				rotation = ((Character)localPlayer).m_body.rotation;
				float value = 0f - CalculateDeviationAngle(y, ((Quaternion)(ref rotation)).eulerAngles.y);
				if (Math.Abs(value) > FirstPersonModePlugin.DynamicPerson.MaxDeviation)
				{
					rotation = ((Character)localPlayer).m_body.rotation;
					float num = ((Quaternion)(ref rotation)).eulerAngles.y * 1f;
					num += (Math.Abs(value) - FirstPersonModePlugin.DynamicPerson.MaxDeviation) * (float)Math.Sign(value);
					Quaternion rotation2 = ((Character)localPlayer).m_body.rotation;
					FirstPersonModePlugin.DynamicPerson.PlayerRotation = Quaternion.Euler(((Quaternion)(ref rotation2)).eulerAngles.x, num, ((Quaternion)(ref rotation2)).eulerAngles.z);
					FirstPersonModePlugin.DynamicPerson.PlayerRigidbody = ((Character)localPlayer).m_body;
					FirstPersonModePlugin.DynamicPerson.PlayerRigidbody.rotation = FirstPersonModePlugin.DynamicPerson.PlayerRotation;
				}
			}
			else
			{
				Vector3 position = default(Vector3);
				Quaternion rotation3 = default(Quaternion);
				__instance.GetCameraPosition(dt, ref position, ref rotation3);
				((Component)__instance).transform.position = position;
				((Component)__instance).transform.rotation = rotation3;
			}
		}

		public static float CalculateDeviationAngle(float angle1, float angle2)
		{
			float num = (angle2 - angle1 + 540f) % 360f - 180f;
			if (!(num >= -180f))
			{
				return num + 360f;
			}
			return num;
		}
	}
}

BepInEx/plugins/BasilPanda-NoStamCosts/NoStamCosts.dll

Decompiled 8 months ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ValheimNoStam")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ValheimNoStam")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f9629e9e-6e4d-42f5-9147-24ef2102c21d")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace ValheimNoStam
{
	[BepInPlugin("Basil_NoStamCosts", "NoStamCosts", "0.1.2")]
	public class NoStamCosts : BaseUnityPlugin
	{
		public const string MODNAME = "NoStamCosts";

		public const string AUTHOR = "Basil";

		public const string GUID = "Basil_NoStamCosts";

		public const string VERSION = "0.1.2";

		internal readonly ManualLogSource log;

		internal readonly Harmony harmony;

		internal readonly Assembly assembly;

		public readonly string modFolder;

		public static ConfigEntry<int> StaminaCostSetting;

		public void InitConfig()
		{
			StaminaCostSetting = ((BaseUnityPlugin)this).Config.Bind<int>("Stamina Cost Setting", "StaminaCostSetting", 1, "0 = Off, 1 = No stamina costs only when using the hammer, hoe or cultivator, 2 = No stamina costs in god mode, 3 = No stamina costs even when not in god mode");
		}

		public NoStamCosts()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			log = ((BaseUnityPlugin)this).Logger;
			harmony = new Harmony("Basil_NoStamCosts");
			assembly = Assembly.GetExecutingAssembly();
			modFolder = Path.GetDirectoryName(assembly.Location);
		}

		public void Awake()
		{
			InitConfig();
			harmony.PatchAll(assembly);
		}
	}
}
namespace ValheimNoStam.Patches
{
	[HarmonyPatch(typeof(Player), "UseStamina")]
	internal static class NoStaminaCostPatch
	{
		private static void Prefix(Player __instance, ref float v)
		{
			switch (NoStamCosts.StaminaCostSetting.Value)
			{
			case 0:
				break;
			case 1:
				if (((Humanoid)__instance).GetRightItem() != null)
				{
					switch (((Humanoid)__instance).GetRightItem().m_shared.m_name)
					{
					case "$item_hammer":
					case "$item_hoe":
					case "$item_cultivator":
						v = 0f;
						break;
					}
				}
				break;
			case 2:
				if (((Character)__instance).InGodMode())
				{
					v = 0f;
				}
				break;
			case 3:
				v = 0f;
				break;
			}
		}
	}
}

BepInEx/plugins/castix-FloatingItems/FloatingItems/FloatingItems.dll

Decompiled 8 months ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("FloatingItems")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FloatingItems")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("ee45e149-de1b-4177-9efa-969b5bf48c1d")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace FloatingItems;

[BepInPlugin("castix_FloatingItems", "FloatingItems", "1.0.0")]
public class FloatingItems : BaseUnityPlugin
{
	public const string MODNAME = "FloatingItems";

	public const string AUTHOR = "castix";

	public const string GUID = "castix_FloatingItems";

	public const string VERSION = "1.0.0";

	internal readonly ManualLogSource log;

	internal readonly Harmony harmony;

	internal readonly Assembly assembly;

	public readonly string modFolder;

	public FloatingItems()
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Expected O, but got Unknown
		log = ((BaseUnityPlugin)this).Logger;
		harmony = new Harmony("castix_FloatingItems");
		assembly = Assembly.GetExecutingAssembly();
		modFolder = Path.GetDirectoryName(assembly.Location);
		Harmony.CreateAndPatchAll(typeof(Patches), (string)null);
	}
}
public static class Patches
{
	[HarmonyPatch(typeof(ItemDrop), "Awake")]
	[HarmonyPrefix]
	private static void FloatingItems(ItemDrop __instance)
	{
		((Component)__instance).gameObject.AddComponent<Floating>();
	}

	[HarmonyPatch(typeof(Floating), "Awake")]
	[HarmonyPrefix]
	private static void FloatingOffset(Floating __instance)
	{
		if (__instance.m_waterLevelOffset <= 0f)
		{
			__instance.m_waterLevelOffset = 0.7f;
		}
	}
}

BepInEx/plugins/coemt-Belts/Belts.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using Soldiers.Patches;
using UnityEngine;
using UnityEngine.UI;

[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyFileVersion("1.1.2")]
[assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyProduct("Belts")]
[assembly: AssemblyCompany("coemt")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("Belts")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.2.0")]
[module: <0ecf6360-f2dc-4c9f-8283-a35d58b79436>RefSafetyRules(11)]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<06719a23-5104-4bf8-94fa-67bda37c6a6f>Embedded]
	internal sealed class <06719a23-5104-4bf8-94fa-67bda37c6a6f>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<06719a23-5104-4bf8-94fa-67bda37c6a6f>Embedded]
	[CompilerGenerated]
	internal sealed class <6105c9b5-1062-4eea-9a73-bf83d69f68e5>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <6105c9b5-1062-4eea-9a73-bf83d69f68e5>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <6105c9b5-1062-4eea-9a73-bf83d69f68e5>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[<06719a23-5104-4bf8-94fa-67bda37c6a6f>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[<06719a23-5104-4bf8-94fa-67bda37c6a6f>Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <0ecf6360-f2dc-4c9f-8283-a35d58b79436>RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public <0ecf6360-f2dc-4c9f-8283-a35d58b79436>RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Soldiers.Patches
{
	public class SE_ModifyStats : StatusEffect
	{
		public float Health;

		public float Stamina;

		private float maxClampValue = 999f;

		private static float _baseEitr;

		private static float _origHealth;

		private static float _origStamina;

		[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(1)]
		public override void Setup(Character character)
		{
			Player val = (Player)(object)((character is Player) ? character : null);
			if ((Object)(object)val != (Object)null)
			{
				if (_origHealth != 0f)
				{
					_origHealth = val.m_baseHP;
				}
				if (_origStamina != 0f)
				{
					_origStamina = val.m_baseStamina;
				}
				val.m_baseHP += Health;
				val.m_baseStamina += Stamina;
			}
			((StatusEffect)this).Setup(character);
		}

		public override void Stop()
		{
			Character character = base.m_character;
			Player val = (Player)(object)((character is Player) ? character : null);
			if ((Object)(object)val != (Object)null)
			{
				val.m_baseHP = Mathf.Clamp(val.m_baseHP - Health, _origHealth, maxClampValue);
				val.m_baseStamina = Mathf.Clamp(val.m_baseStamina - Stamina, _origStamina, maxClampValue);
			}
			((StatusEffect)this).Stop();
		}
	}
}
namespace ItemManager
{
	[PublicAPI]
	public enum CraftingTable
	{
		Disabled,
		Inventory,
		[InternalName("piece_workbench")]
		Workbench,
		[InternalName("piece_cauldron")]
		Cauldron,
		[InternalName("forge")]
		Forge,
		[InternalName("piece_artisanstation")]
		ArtisanTable,
		[InternalName("piece_stonecutter")]
		StoneCutter,
		[InternalName("piece_magetable")]
		MageTable,
		[InternalName("blackforge")]
		BlackForge,
		Custom
	}
	[PublicAPI]
	public enum ConversionPiece
	{
		Disabled,
		[InternalName("smelter")]
		Smelter,
		[InternalName("charcoal_kiln")]
		CharcoalKiln,
		[InternalName("blastfurnace")]
		BlastFurnace,
		[InternalName("windmill")]
		Windmill,
		[InternalName("piece_spinningwheel")]
		SpinningWheel,
		[InternalName("eitrrefinery")]
		EitrRefinery,
		Custom
	}
	[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(1)]
	[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
	public class InternalName : Attribute
	{
		public readonly string internalName;

		public InternalName(string internalName)
		{
			this.internalName = internalName;
		}
	}
	[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(1)]
	[PublicAPI]
	[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
	public class RequiredResourceList
	{
		public readonly List<Requirement> Requirements = new List<Requirement>();

		public bool Free = false;

		public void Add(string itemName, int amount, int quality = 0)
		{
			Requirements.Add(new Requirement
			{
				itemName = itemName,
				amount = amount,
				quality = quality
			});
		}

		public void Add(string itemName, ConfigEntry<int> amountConfig, int quality = 0)
		{
			Requirements.Add(new Requirement
			{
				itemName = itemName,
				amountConfig = amountConfig,
				quality = quality
			});
		}
	}
	[PublicAPI]
	[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(1)]
	[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
	public class CraftingStationList
	{
		public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>();

		public void Add(CraftingTable table, int level)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = table,
				level = level
			});
		}

		public void Add(string customTable, int level)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = CraftingTable.Custom,
				level = level,
				custom = customTable
			});
		}
	}
	[PublicAPI]
	[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(1)]
	[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
	public class ItemRecipe
	{
		public readonly RequiredResourceList RequiredItems = new RequiredResourceList();

		public readonly RequiredResourceList RequiredUpgradeItems = new RequiredResourceList();

		public readonly CraftingStationList Crafting = new CraftingStationList();

		public int CraftAmount = 1;

		public bool RequireOnlyOneIngredient = false;

		public float QualityResultAmountMultiplier = 1f;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		public ConfigEntryBase RecipeIsActive = null;
	}
	[PublicAPI]
	public class Trade
	{
		public Trader Trader = Trader.None;

		public uint Price = 0u;

		public uint Stack = 1u;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		public string RequiredGlobalKey = null;
	}
	[Flags]
	[PublicAPI]
	public enum Trader
	{
		None = 0,
		Haldor = 1,
		Hildir = 2
	}
	public struct Requirement
	{
		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(1)]
		public string itemName;

		public int amount;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		public ConfigEntry<int> amountConfig;

		[Description("Set to a non-zero value to apply the requirement only for a specific quality")]
		public int quality;
	}
	public struct CraftingStationConfig
	{
		public CraftingTable Table;

		public int level;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		public string custom;
	}
	[Flags]
	public enum Configurability
	{
		Disabled = 0,
		Recipe = 1,
		Stats = 2,
		Drop = 4,
		Trader = 8,
		Full = 0xF
	}
	[PublicAPI]
	[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
	[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(1)]
	public class DropTargets
	{
		public readonly List<DropTarget> Drops = new List<DropTarget>();

		public void Add(string creatureName, float chance, int min = 1, int? max = null, bool levelMultiplier = true)
		{
			Drops.Add(new DropTarget
			{
				creature = creatureName,
				chance = chance,
				min = min,
				max = (max ?? min),
				levelMultiplier = levelMultiplier
			});
		}
	}
	public struct DropTarget
	{
		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(1)]
		public string creature;

		public int min;

		public int max;

		public float chance;

		public bool levelMultiplier;
	}
	public enum Toggle
	{
		On = 1,
		Off = 0
	}
	[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
	[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(1)]
	[PublicAPI]
	public class Item
	{
		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
		private class ItemConfig
		{
			[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 2, 1 })]
			public ConfigEntry<string> craft;

			[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 2, 1 })]
			public ConfigEntry<string> upgrade;

			public ConfigEntry<CraftingTable> table = null;

			public ConfigEntry<int> tableLevel = null;

			public ConfigEntry<string> customTable = null;

			[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
			public ConfigEntry<int> maximumTableLevel;

			public ConfigEntry<Toggle> requireOneIngredient = null;

			public ConfigEntry<float> qualityResultAmountMultiplier = null;
		}

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
		private class TraderConfig
		{
			public ConfigEntry<Trader> trader = null;

			public ConfigEntry<uint> price = null;

			public ConfigEntry<uint> stack = null;

			public ConfigEntry<string> requiredGlobalKey = null;
		}

		[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)]
		private class RequirementQuality
		{
			public int quality;
		}

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
		[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(2)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			public string Category;

			[UsedImplicitly]
			[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 2, 1 })]
			public Action<ConfigEntryBase> CustomDrawer;

			public Func<bool> browsability;
		}

		[PublicAPI]
		[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)]
		public enum DamageModifier
		{
			Normal,
			Resistant,
			Weak,
			Immune,
			Ignore,
			VeryResistant,
			VeryWeak,
			None
		}

		[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)]
		private delegate void setDmgFunc(ref DamageTypes dmg, float value);

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
		private class SerializedRequirements
		{
			public readonly List<Requirement> Reqs;

			public SerializedRequirements(List<Requirement> reqs)
			{
				Reqs = reqs;
			}

			public SerializedRequirements(string reqs)
				: this(reqs.Split(new char[1] { ',' }).Select([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (string r) =>
				{
					string[] array = r.Split(new char[1] { ':' });
					Requirement result = default(Requirement);
					result.itemName = array[0];
					result.amount = ((array.Length <= 1 || !int.TryParse(array[1], out var result2)) ? 1 : result2);
					result.quality = ((array.Length > 2 && int.TryParse(array[2], out var result3)) ? result3 : 0);
					return result;
				}).ToList())
			{
			}

			public override string ToString()
			{
				return string.Join(",", Reqs.Select([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}" + ((r.quality > 0) ? $":{r.quality}" : "")));
			}

			[return: <6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
			public static ItemDrop fetchByName(ObjectDB objectDB, string name)
			{
				GameObject itemPrefab = objectDB.GetItemPrefab(name);
				ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val == (Object)null)
				{
					Debug.LogWarning((object)("The required item '" + name + "' does not exist."));
				}
				return val;
			}

			public static Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade)
			{
				//IL_0100: Unknown result type (might be due to invalid IL or missing references)
				//IL_0105: Unknown result type (might be due to invalid IL or missing references)
				//IL_010d: Unknown result type (might be due to invalid IL or missing references)
				//IL_019b: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01af: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b2: Expected O, but got Unknown
				//IL_01b7: Expected O, but got Unknown
				//IL_012c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0135: Expected O, but got Unknown
				Dictionary<string, Requirement> dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func<Requirement, string>)([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Requirement r) => r.itemName), (Func<Requirement, Requirement>)([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Requirement r) =>
				{
					//IL_000e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0013: Unknown result type (might be due to invalid IL or missing references)
					//IL_0030: 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)
					ItemDrop val6 = ResItem(r);
					return (val6 == null) ? ((Requirement)null) : new Requirement
					{
						m_amount = (r.amountConfig?.Value ?? r.amount),
						m_resItem = val6,
						m_amountPerLevel = 0
					};
				}));
				List<Requirement> list = dictionary.Values.Where([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Requirement v) => v != null).ToList();
				foreach (Requirement item in upgrade.Reqs.Where((Requirement r) => r.itemName != ""))
				{
					if (item.quality > 0)
					{
						ItemDrop val = ResItem(item);
						if (val != null)
						{
							Requirement val2 = new Requirement
							{
								m_resItem = val,
								m_amountPerLevel = (item.amountConfig?.Value ?? item.amount),
								m_amount = 0
							};
							list.Add(val2);
							requirementQuality.Add(val2, new RequirementQuality
							{
								quality = item.quality
							});
						}
						continue;
					}
					if (!dictionary.TryGetValue(item.itemName, out var value) || value == null)
					{
						ItemDrop val3 = ResItem(item);
						if (val3 != null)
						{
							string itemName = item.itemName;
							Requirement val4 = new Requirement
							{
								m_resItem = val3,
								m_amount = 0
							};
							Requirement val5 = val4;
							dictionary[itemName] = val4;
							value = val5;
							list.Add(value);
						}
					}
					if (value != null)
					{
						value.m_amountPerLevel = item.amountConfig?.Value ?? item.amount;
					}
				}
				return list.ToArray();
				[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(2)]
				ItemDrop ResItem(Requirement r)
				{
					return fetchByName(objectDB, r.itemName);
				}
			}
		}

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)]
		private class SerializedDrop
		{
			public readonly List<DropTarget> Drops;

			public SerializedDrop(List<DropTarget> drops)
			{
				Drops = drops;
			}

			public SerializedDrop(string drops)
			{
				Drops = ((drops == "") ? ((IEnumerable<string>)Array.Empty<string>()) : ((IEnumerable<string>)drops.Split(new char[1] { ',' }))).Select([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (string r) =>
				{
					string[] array = r.Split(new char[1] { ':' });
					if (array.Length <= 2 || !int.TryParse(array[2], out var result))
					{
						result = 1;
					}
					if (array.Length <= 3 || !int.TryParse(array[3], out var result2))
					{
						result2 = result;
					}
					bool levelMultiplier = array.Length <= 4 || array[4] != "0";
					DropTarget result3 = default(DropTarget);
					result3.creature = array[0];
					result3.chance = ((array.Length > 1 && float.TryParse(array[1], out var result4)) ? result4 : 1f);
					result3.min = result;
					result3.max = result2;
					result3.levelMultiplier = levelMultiplier;
					return result3;
				}).ToList();
			}

			public override string ToString()
			{
				return string.Join(",", Drops.Select([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (DropTarget r) => $"{r.creature}:{r.chance.ToString(CultureInfo.InvariantCulture)}:{r.min}:" + ((r.min == r.max) ? "" : $"{r.max}") + (r.levelMultiplier ? "" : ":0")));
			}

			[return: <6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
			private static Character fetchByName(ZNetScene netScene, string name)
			{
				GameObject prefab = netScene.GetPrefab(name);
				Character val = ((prefab != null) ? prefab.GetComponent<Character>() : null);
				if ((Object)(object)val == (Object)null)
				{
					Debug.LogWarning((object)("The drop target character '" + name + "' does not exist."));
				}
				return val;
			}

			public Dictionary<Character, Drop> toCharacterDrops(ZNetScene netScene, GameObject item)
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: 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_007a: Expected O, but got Unknown
				Dictionary<Character, Drop> dictionary = new Dictionary<Character, Drop>();
				foreach (DropTarget drop in Drops)
				{
					Character val = fetchByName(netScene, drop.creature);
					if (val != null)
					{
						dictionary[val] = new Drop
						{
							m_prefab = item,
							m_amountMin = drop.min,
							m_amountMax = drop.max,
							m_chance = drop.chance,
							m_levelMultiplier = drop.levelMultiplier
						};
					}
				}
				return dictionary;
			}
		}

		private static readonly List<Item> registeredItems = new List<Item>();

		private static readonly Dictionary<ItemDrop, Item> itemDropMap = new Dictionary<ItemDrop, Item>();

		private static Dictionary<Item, Dictionary<string, List<Recipe>>> activeRecipes = new Dictionary<Item, Dictionary<string, List<Recipe>>>();

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 1, 1, 2 })]
		private static Dictionary<Recipe, ConfigEntryBase> hiddenCraftRecipes = new Dictionary<Recipe, ConfigEntryBase>();

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 1, 1, 2 })]
		private static Dictionary<Recipe, ConfigEntryBase> hiddenUpgradeRecipes = new Dictionary<Recipe, ConfigEntryBase>();

		private static Dictionary<Item, Dictionary<string, ItemConfig>> itemCraftConfigs = new Dictionary<Item, Dictionary<string, ItemConfig>>();

		private static Dictionary<Item, ConfigEntry<string>> itemDropConfigs = new Dictionary<Item, ConfigEntry<string>>();

		private Dictionary<CharacterDrop, Drop> characterDrops = new Dictionary<CharacterDrop, Drop>();

		private readonly Dictionary<ConfigEntryBase, Action> statsConfigs = new Dictionary<ConfigEntryBase, Action>();

		private static readonly ConditionalWeakTable<Requirement, RequirementQuality> requirementQuality = new ConditionalWeakTable<Requirement, RequirementQuality>();

		public static Configurability DefaultConfigurability = Configurability.Full;

		public Configurability? Configurable = null;

		private Configurability configurationVisible = Configurability.Full;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		private TraderConfig traderConfig;

		public readonly GameObject Prefab;

		[Description("Specifies the maximum required crafting station level to upgrade and repair the item.\nDefault is calculated from crafting station level and maximum quality.")]
		public int MaximumRequiredStationLevel = int.MaxValue;

		[Description("Assigns the item as a drop item to a creature.\nUses a creature name, a drop chance and a minimum and maximum amount.")]
		public readonly DropTargets DropsFrom = new DropTargets();

		[Description("Configures whether the item can be bought at the trader.\nDon't forget to set cost to something above 0 or the item will be sold for free.")]
		public readonly Trade Trade = new Trade();

		internal List<Conversion> Conversions = new List<Conversion>();

		internal List<ItemConversion> conversions = new List<ItemConversion>();

		public Dictionary<string, ItemRecipe> Recipes = new Dictionary<string, ItemRecipe>();

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		private LocalizeKey _name;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		private LocalizeKey _description;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		private static object configManager;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		private static Localization _english;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static bool hasConfigSync = true;

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		private static object _configSync;

		private Configurability configurability => Configurable ?? DefaultConfigurability;

		[Description("Specifies the resources needed to craft the item.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the item should need.")]
		public RequiredResourceList RequiredItems => this[""].RequiredItems;

		[Description("Specifies the resources needed to upgrade the item.\nUse .Add to add resources with their internal ID and an amount. This amount will be multipled by the item quality level.\nUse one .Add for each resource type the upgrade should need.")]
		public RequiredResourceList RequiredUpgradeItems => this[""].RequiredUpgradeItems;

		[Description("Specifies the crafting station needed to craft the item.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.\nUse one .Add for each crafting station.")]
		public CraftingStationList Crafting => this[""].Crafting;

		[Description("Specifies a config entry which toggles whether a recipe is active.")]
		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		public ConfigEntryBase RecipeIsActive
		{
			[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(2)]
			get
			{
				return this[""].RecipeIsActive;
			}
			[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(2)]
			set
			{
				this[""].RecipeIsActive = value;
			}
		}

		[Description("Specifies the number of items that should be given to the player with a single craft of the item.\nDefaults to 1.")]
		public int CraftAmount
		{
			get
			{
				return this[""].CraftAmount;
			}
			set
			{
				this[""].CraftAmount = value;
			}
		}

		public bool RequireOnlyOneIngredient
		{
			get
			{
				return this[""].RequireOnlyOneIngredient;
			}
			set
			{
				this[""].RequireOnlyOneIngredient = value;
			}
		}

		public float QualityResultAmountMultiplier
		{
			get
			{
				return this[""].QualityResultAmountMultiplier;
			}
			set
			{
				this[""].QualityResultAmountMultiplier = value;
			}
		}

		public ItemRecipe this[string name]
		{
			get
			{
				if (Recipes.TryGetValue(name, out var value))
				{
					return value;
				}
				return Recipes[name] = new ItemRecipe();
			}
		}

		public LocalizeKey Name
		{
			get
			{
				LocalizeKey name = _name;
				if (name != null)
				{
					return name;
				}
				SharedData shared = Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
				if (shared.m_name.StartsWith("$"))
				{
					_name = new LocalizeKey(shared.m_name);
				}
				else
				{
					string text = "$item_" + ((Object)Prefab).name.Replace(" ", "_");
					_name = new LocalizeKey(text).English(shared.m_name);
					shared.m_name = text;
				}
				return _name;
			}
		}

		public LocalizeKey Description
		{
			get
			{
				LocalizeKey description = _description;
				if (description != null)
				{
					return description;
				}
				SharedData shared = Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
				if (shared.m_description.StartsWith("$"))
				{
					_description = new LocalizeKey(shared.m_description);
				}
				else
				{
					string text = "$itemdesc_" + ((Object)Prefab).name.Replace(" ", "_");
					_description = new LocalizeKey(text).English(shared.m_description);
					shared.m_description = text;
				}
				return _description;
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Expected O, but got Unknown
				if (_plugin == null)
				{
					IEnumerable<TypeInfo> source;
					try
					{
						source = Assembly.GetExecutingAssembly().DefinedTypes.ToList();
					}
					catch (ReflectionTypeLoadException ex)
					{
						source = from t in ex.Types
							where t != null
							select t.GetTypeInfo();
					}
					_plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
				}
				return _plugin;
			}
		}

		[<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(2)]
		private static object configSync
		{
			[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(2)]
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " ItemManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		public Item(string assetBundleFileName, string prefabName, string folderName = "assets")
			: this(PrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName)
		{
		}

		public Item(AssetBundle bundle, string prefabName)
			: this(PrefabManager.RegisterPrefab(bundle, prefabName, addToObjectDb: true), skipRegistering: true)
		{
		}

		public Item(GameObject prefab, bool skipRegistering = false)
		{
			if (!skipRegistering)
			{
				PrefabManager.RegisterPrefab(prefab, addToObjectDb: true);
			}
			Prefab = prefab;
			registeredItems.Add(this);
			itemDropMap[Prefab.GetComponent<ItemDrop>()] = this;
			Prefab.GetComponent<ItemDrop>().m_itemData.m_dropPrefab = Prefab;
		}

		public void ToggleConfigurationVisibility(Configurability visible)
		{
			configurationVisible = visible;
			if (itemDropConfigs.TryGetValue(this, out var value))
			{
				Toggle((ConfigEntryBase)(object)value, Configurability.Drop);
			}
			if (itemCraftConfigs.TryGetValue(this, out var value2))
			{
				foreach (ItemConfig value4 in value2.Values)
				{
					ToggleObj(value4, Configurability.Recipe);
				}
			}
			foreach (Conversion conversion in Conversions)
			{
				if (conversion.config != null)
				{
					ToggleObj(conversion.config, Configurability.Recipe);
				}
			}
			foreach (KeyValuePair<ConfigEntryBase, Action> statsConfig in statsConfigs)
			{
				Toggle(statsConfig.Key, Configurability.Stats);
				if ((visible & Configurability.Stats) != 0)
				{
					statsConfig.Value();
				}
			}
			reloadConfigDisplay();
			void Toggle(ConfigEntryBase cfg, Configurability check)
			{
				object[] tags = cfg.Description.Tags;
				foreach (object obj2 in tags)
				{
					if (obj2 is ConfigurationManagerAttributes configurationManagerAttributes)
					{
						configurationManagerAttributes.Browsable = (visible & check) != 0 && (configurationManagerAttributes.browsability == null || configurationManagerAttributes.browsability());
					}
				}
			}
			void ToggleObj(object obj, Configurability check)
			{
				FieldInfo[] fields = obj.GetType().GetFields();
				foreach (FieldInfo fieldInfo in fields)
				{
					object? value3 = fieldInfo.GetValue(obj);
					ConfigEntryBase val = (ConfigEntryBase)((value3 is ConfigEntryBase) ? value3 : null);
					if (val != null)
					{
						Toggle(val, check);
					}
				}
			}
		}

		internal static void reloadConfigDisplay()
		{
			configManager?.GetType().GetMethod("BuildSettingList").Invoke(configManager, Array.Empty<object>());
		}

		private void UpdateItemTableConfig(string recipeKey, CraftingTable table, string customTableValue)
		{
			if (activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(recipeKey, out var value))
			{
				value.First().m_enabled = table != CraftingTable.Disabled;
				if (table == CraftingTable.Inventory || table == CraftingTable.Disabled)
				{
					value.First().m_craftingStation = null;
				}
				else if (table == CraftingTable.Custom)
				{
					Recipe obj = value.First();
					GameObject prefab = ZNetScene.instance.GetPrefab(customTableValue);
					obj.m_craftingStation = ((prefab != null) ? prefab.GetComponent<CraftingStation>() : null);
				}
				else
				{
					value.First().m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName(table)).GetComponent<CraftingStation>();
				}
			}
		}

		private void UpdateCraftConfig(string recipeKey, SerializedRequirements craftRequirements, SerializedRequirements upgradeRequirements)
		{
			if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || !activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out var value))
			{
				return;
			}
			foreach (Recipe item in value)
			{
				item.m_resources = SerializedRequirements.toPieceReqs(ObjectDB.instance, craftRequirements, upgradeRequirements);
			}
		}

		internal static void Patch_FejdStartup()
		{
			//IL_1001: Unknown result type (might be due to invalid IL or missing references)
			//IL_1006: Unknown result type (might be due to invalid IL or missing references)
			//IL_2356: Unknown result type (might be due to invalid IL or missing references)
			//IL_2360: Expected O, but got Unknown
			//IL_10ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_10d1: Invalid comparison between Unknown and I4
			//IL_10d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_10d6: Invalid comparison between Unknown and I4
			//IL_0ccc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cd6: Expected O, but got Unknown
			//IL_10d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_10dc: Invalid comparison between Unknown and I4
			//IL_1242: Unknown result type (might be due to invalid IL or missing references)
			//IL_1245: Invalid comparison between Unknown and I4
			//IL_10de: Unknown result type (might be due to invalid IL or missing references)
			//IL_10e1: Invalid comparison between Unknown and I4
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Expected O, but got Unknown
			//IL_1247: Unknown result type (might be due to invalid IL or missing references)
			//IL_124a: Invalid comparison between Unknown and I4
			//IL_10e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_10e7: Invalid comparison between Unknown and I4
			//IL_0dfa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e04: Expected O, but got Unknown
			//IL_0ea6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0eb0: Expected O, but got Unknown
			//IL_124c: Unknown result type (might be due to invalid IL or missing references)
			//IL_124f: Invalid comparison between Unknown and I4
			//IL_10e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_10ec: Invalid comparison between Unknown and I4
			//IL_0f5b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f65: Expected O, but got Unknown
			//IL_145f: Unknown result type (might be due to invalid IL or missing references)
			//IL_1462: Invalid comparison between Unknown and I4
			//IL_1251: Unknown result type (might be due to invalid IL or missing references)
			//IL_1255: Invalid comparison between Unknown and I4
			//IL_10ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_10f2: Invalid comparison between Unknown and I4
			//IL_045e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Expected O, but got Unknown
			//IL_1464: Unknown result type (might be due to invalid IL or missing references)
			//IL_1468: Invalid comparison between Unknown and I4
			//IL_1257: Unknown result type (might be due to invalid IL or missing references)
			//IL_125b: Invalid comparison between Unknown and I4
			//IL_10f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_10f8: Invalid comparison between Unknown and I4
			//IL_146a: Unknown result type (might be due to invalid IL or missing references)
			//IL_146d: Invalid comparison between Unknown and I4
			//IL_10fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_10fd: Invalid comparison between Unknown and I4
			//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b7: Expected O, but got Unknown
			//IL_1551: Unknown result type (might be due to invalid IL or missing references)
			//IL_1556: Unknown result type (might be due to invalid IL or missing references)
			//IL_1558: Unknown result type (might be due to invalid IL or missing references)
			//IL_155b: Invalid comparison between Unknown and I4
			//IL_146f: Unknown result type (might be due to invalid IL or missing references)
			//IL_1473: Invalid comparison between Unknown and I4
			//IL_10ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_1103: Invalid comparison between Unknown and I4
			//IL_155d: Unknown result type (might be due to invalid IL or missing references)
			//IL_1561: Invalid comparison between Unknown and I4
			//IL_1475: Unknown result type (might be due to invalid IL or missing references)
			//IL_1479: Invalid comparison between Unknown and I4
			//IL_1105: Unknown result type (might be due to invalid IL or missing references)
			//IL_1109: Invalid comparison between Unknown and I4
			//IL_0796: Unknown result type (might be due to invalid IL or missing references)
			//IL_07a0: Expected O, but got Unknown
			//IL_06eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f5: Expected O, but got Unknown
			//IL_15d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_15da: Invalid comparison between Unknown and I4
			//IL_15dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_15df: Invalid comparison between Unknown and I4
			//IL_08b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_08ba: Expected O, but got Unknown
			//IL_15e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_15e5: Invalid comparison between Unknown and I4
			//IL_1738: Unknown result type (might be due to invalid IL or missing references)
			//IL_173b: Invalid comparison between Unknown and I4
			//IL_15e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_15ea: Invalid comparison between Unknown and I4
			//IL_15ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_15f0: Invalid comparison between Unknown and I4
			//IL_15f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_15f6: Invalid comparison between Unknown and I4
			//IL_194a: Unknown result type (might be due to invalid IL or missing references)
			//IL_1951: Invalid comparison between Unknown and I4
			//IL_1a26: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a2b: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a2d: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a31: Invalid comparison between Unknown and I4
			//IL_1a33: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a37: Invalid comparison between Unknown and I4
			//IL_16a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_16ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_1aad: Unknown result type (might be due to invalid IL or missing references)
			//IL_1ab0: Invalid comparison between Unknown and I4
			//IL_1ab2: Unknown result type (might be due to invalid IL or missing references)
			//IL_1ab6: Invalid comparison between Unknown and I4
			//IL_1ab8: Unknown result type (might be due to invalid IL or missing references)
			//IL_1abc: Invalid comparison between Unknown and I4
			//IL_1abe: Unknown result type (might be due to invalid IL or missing references)
			//IL_1ac1: Invalid comparison between Unknown and I4
			//IL_1f49: Unknown result type (might be due to invalid IL or missing references)
			//IL_1f4c: Invalid comparison between Unknown and I4
			Type type = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager");
			if (DefaultConfigurability != 0)
			{
				bool saveOnConfigSet = plugin.Config.SaveOnConfigSet;
				plugin.Config.SaveOnConfigSet = false;
				foreach (Item item4 in registeredItems.Where([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Item i) => i.configurability != Configurability.Disabled))
				{
					Item item3 = item4;
					string name2 = item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name;
					string englishName = new Regex("['\\[\"\\]]").Replace(english.Localize(name2), "").Trim();
					string localizedName = Localization.instance.Localize(name2).Trim();
					int order = 0;
					if ((item3.configurability & Configurability.Recipe) != 0)
					{
						itemCraftConfigs[item3] = new Dictionary<string, ItemConfig>();
						foreach (string item5 in item3.Recipes.Keys.DefaultIfEmpty(""))
						{
							string configKey = item5;
							string text = ((configKey == "") ? "" : (" (" + configKey + ")"));
							if (!item3.Recipes.ContainsKey(configKey) || item3.Recipes[configKey].Crafting.Stations.Count <= 0)
							{
								continue;
							}
							ItemConfig itemConfig2 = (itemCraftConfigs[item3][configKey] = new ItemConfig());
							ItemConfig cfg = itemConfig2;
							List<ConfigurationManagerAttributes> hideWhenNoneAttributes = new List<ConfigurationManagerAttributes>();
							cfg.table = config(englishName, "Crafting Station" + text, item3.Recipes[configKey].Crafting.Stations.First().Table, new ConfigDescription("Crafting station where " + englishName + " is available.", (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Order = (order -= 1),
									Browsable = ((item3.configurationVisible & Configurability.Recipe) != 0),
									Category = localizedName
								}
							}));
							ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes
							{
								Order = (order -= 1),
								browsability = CustomTableBrowsability,
								Browsable = (CustomTableBrowsability() && (item3.configurationVisible & Configurability.Recipe) != 0),
								Category = localizedName
							};
							cfg.customTable = config(englishName, "Custom Crafting Station" + text, item3.Recipes[configKey].Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
							cfg.table.SettingChanged += TableConfigChanged;
							cfg.customTable.SettingChanged += TableConfigChanged;
							ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes
							{
								Order = (order -= 1),
								browsability = TableLevelBrowsability,
								Browsable = (TableLevelBrowsability() && (item3.configurationVisible & Configurability.Recipe) != 0),
								Category = localizedName
							};
							hideWhenNoneAttributes.Add(configurationManagerAttributes);
							cfg.tableLevel = config(englishName, "Crafting Station Level" + text, item3.Recipes[configKey].Crafting.Stations.First().level, new ConfigDescription("Required crafting station level to craft " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes }));
							cfg.tableLevel.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
							{
								if (activeRecipes.ContainsKey(item3) && activeRecipes[item3].TryGetValue(configKey, out var value6))
								{
									value6.First().m_minStationLevel = cfg.tableLevel.Value;
								}
							};
							if (item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality > 1)
							{
								cfg.maximumTableLevel = config(englishName, "Maximum Crafting Station Level" + text, (item3.MaximumRequiredStationLevel == int.MaxValue) ? (item3.Recipes[configKey].Crafting.Stations.First().level + item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality - 1) : item3.MaximumRequiredStationLevel, new ConfigDescription("Maximum crafting station level to upgrade and repair " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes }));
							}
							cfg.requireOneIngredient = config(englishName, "Require only one resource" + text, item3.Recipes[configKey].RequireOnlyOneIngredient ? Toggle.On : Toggle.Off, new ConfigDescription("Whether only one of the ingredients is needed to craft " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Order = (order -= 1),
									Category = localizedName
								}
							}));
							ConfigurationManagerAttributes qualityResultAttributes = new ConfigurationManagerAttributes
							{
								Order = (order -= 1),
								browsability = QualityResultBrowsability,
								Browsable = (QualityResultBrowsability() && (item3.configurationVisible & Configurability.Recipe) != 0),
								Category = localizedName
							};
							cfg.requireOneIngredient.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
							{
								if (activeRecipes.ContainsKey(item3) && activeRecipes[item3].TryGetValue(configKey, out var value5))
								{
									foreach (Recipe item6 in value5)
									{
										item6.m_requireOnlyOneIngredient = cfg.requireOneIngredient.Value == Toggle.On;
									}
								}
								qualityResultAttributes.Browsable = QualityResultBrowsability();
								reloadConfigDisplay();
							};
							cfg.qualityResultAmountMultiplier = config(englishName, "Quality Multiplier" + text, item3.Recipes[configKey].QualityResultAmountMultiplier, new ConfigDescription("Multiplies the crafted amount based on the quality of the resources when crafting " + englishName + ". Only works, if Require Only One Resource is true.", (AcceptableValueBase)null, new object[1] { qualityResultAttributes }));
							cfg.qualityResultAmountMultiplier.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
							{
								if (activeRecipes.ContainsKey(item3) && activeRecipes[item3].TryGetValue(configKey, out var value4))
								{
									foreach (Recipe item7 in value4)
									{
										item7.m_qualityResultAmountMultiplier = cfg.qualityResultAmountMultiplier.Value;
									}
								}
							};
							if ((!item3.Recipes[configKey].RequiredItems.Free || item3.Recipes[configKey].RequiredItems.Requirements.Count > 0) && item3.Recipes[configKey].RequiredItems.Requirements.All((Requirement r) => r.amountConfig == null))
							{
								cfg.craft = itemConfig("Crafting Costs" + text, new SerializedRequirements(item3.Recipes[configKey].RequiredItems.Requirements).ToString(), "Item costs to craft " + englishName, isUpgrade: false);
							}
							if (item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality > 1 && (!item3.Recipes[configKey].RequiredUpgradeItems.Free || item3.Recipes[configKey].RequiredUpgradeItems.Requirements.Count > 0) && item3.Recipes[configKey].RequiredUpgradeItems.Requirements.All((Requirement r) => r.amountConfig == null))
							{
								cfg.upgrade = itemConfig("Upgrading Costs" + text, new SerializedRequirements(item3.Recipes[configKey].RequiredUpgradeItems.Requirements).ToString(), "Item costs per level to upgrade " + englishName, isUpgrade: true);
							}
							if (cfg.craft != null)
							{
								cfg.craft.SettingChanged += ConfigChanged;
							}
							if (cfg.upgrade != null)
							{
								cfg.upgrade.SettingChanged += ConfigChanged;
							}
							void ConfigChanged(object o, EventArgs e)
							{
								item3.UpdateCraftConfig(configKey, new SerializedRequirements(cfg.craft?.Value ?? ""), new SerializedRequirements(cfg.upgrade?.Value ?? ""));
							}
							bool CustomTableBrowsability()
							{
								return cfg.table.Value == CraftingTable.Custom;
							}
							bool ItemBrowsability()
							{
								return cfg.table.Value != CraftingTable.Disabled;
							}
							bool QualityResultBrowsability()
							{
								return cfg.requireOneIngredient.Value == Toggle.On;
							}
							void TableConfigChanged(object o, EventArgs e)
							{
								item3.UpdateItemTableConfig(configKey, cfg.table.Value, cfg.customTable.Value);
								customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom;
								foreach (ConfigurationManagerAttributes item8 in hideWhenNoneAttributes)
								{
									item8.Browsable = cfg.table.Value != CraftingTable.Disabled;
								}
								reloadConfigDisplay();
							}
							bool TableLevelBrowsability()
							{
								return cfg.table.Value != CraftingTable.Disabled;
							}
							ConfigEntry<string> itemConfig(string name, string value, string desc, bool isUpgrade)
							{
								//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
								//IL_00be: Expected O, but got Unknown
								ConfigurationManagerAttributes configurationManagerAttributes3 = new ConfigurationManagerAttributes
								{
									CustomDrawer = drawRequirementsConfigTable(item3, isUpgrade),
									Order = (order -= 1),
									browsability = ItemBrowsability,
									Browsable = (ItemBrowsability() && (item3.configurationVisible & Configurability.Recipe) != 0),
									Category = localizedName
								};
								hideWhenNoneAttributes.Add(configurationManagerAttributes3);
								return config(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes3 }));
							}
						}
						if ((item3.configurability & Configurability.Drop) != 0)
						{
							ConfigEntry<string> val3 = (itemDropConfigs[item3] = config(englishName, "Drops from", new SerializedDrop(item3.DropsFrom.Drops).ToString(), new ConfigDescription(englishName + " drops from this creature.", (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									CustomDrawer = drawDropsConfigTable,
									Category = localizedName,
									Browsable = ((item3.configurationVisible & Configurability.Drop) != 0)
								}
							})));
							ConfigEntry<string> val4 = val3;
							val4.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
							{
								item3.UpdateCharacterDrop();
							};
						}
						for (int j = 0; j < item3.Conversions.Count; j++)
						{
							string text2 = ((item3.Conversions.Count > 1) ? $"{j + 1}. " : "");
							Conversion conversion = item3.Conversions[j];
							conversion.config = new Conversion.ConversionConfig();
							int index = j;
							conversion.config.input = config(englishName, text2 + "Conversion Input Item", conversion.Input, new ConfigDescription("Duration of conversion to create " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Category = localizedName,
									Browsable = ((item3.configurationVisible & Configurability.Recipe) != 0)
								}
							}));
							conversion.config.input.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
							{
								if (index < item3.conversions.Count)
								{
									ObjectDB instance = ObjectDB.instance;
									if (instance != null)
									{
										ItemDrop from = SerializedRequirements.fetchByName(instance, conversion.config.input.Value);
										item3.conversions[index].m_from = from;
										UpdatePiece();
									}
								}
							};
							conversion.config.piece = config(englishName, text2 + "Conversion Piece", conversion.Piece, new ConfigDescription("Duration of conversion to create " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Category = localizedName,
									Browsable = ((item3.configurationVisible & Configurability.Recipe) != 0)
								}
							}));
							conversion.config.piece.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
							{
								UpdatePiece();
							};
							conversion.config.customPiece = config(englishName, text2 + "Conversion Custom Piece", conversion.customPiece ?? "", new ConfigDescription("Duration of conversion to create " + englishName, (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Category = localizedName,
									Browsable = ((item3.configurationVisible & Configurability.Recipe) != 0)
								}
							}));
							conversion.config.customPiece.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
							{
								UpdatePiece();
							};
							void UpdatePiece()
							{
								if (index < item3.conversions.Count && Object.op_Implicit((Object)(object)ZNetScene.instance))
								{
									string text3 = ((conversion.config.piece.Value == ConversionPiece.Disabled) ? null : ((conversion.config.piece.Value == ConversionPiece.Custom) ? conversion.config.customPiece.Value : getInternalName(conversion.config.piece.Value)));
									string activePiece = conversion.config.activePiece;
									if (conversion.config.activePiece != null)
									{
										Smelter component = ZNetScene.instance.GetPrefab(conversion.config.activePiece).GetComponent<Smelter>();
										int num = component.m_conversion.IndexOf(item3.conversions[index]);
										if (num >= 0)
										{
											Smelter[] array3 = Resources.FindObjectsOfTypeAll<Smelter>();
											foreach (Smelter val6 in array3)
											{
												if (Utils.GetPrefabName(((Component)val6).gameObject) == activePiece)
												{
													val6.m_conversion.RemoveAt(num);
												}
											}
										}
										conversion.config.activePiece = null;
									}
									if (item3.conversions[index].m_from != null && conversion.config.piece.Value != 0)
									{
										GameObject prefab = ZNetScene.instance.GetPrefab(text3);
										if (((prefab != null) ? prefab.GetComponent<Smelter>() : null) != null)
										{
											conversion.config.activePiece = text3;
											Smelter[] array4 = Resources.FindObjectsOfTypeAll<Smelter>();
											foreach (Smelter val7 in array4)
											{
												if (Utils.GetPrefabName(((Component)val7).gameObject) == text3)
												{
													val7.m_conversion.Add(item3.conversions[index]);
												}
											}
										}
									}
								}
							}
						}
					}
					if ((item3.configurability & Configurability.Stats) != 0)
					{
						item3.statsConfigs.Clear();
						SharedData shared2 = item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
						ItemType itemType = shared2.m_itemType;
						statcfg<float>("Weight", "Weight of " + englishName + ".", (SharedData shared) => shared.m_weight, delegate(SharedData shared, float value)
						{
							shared.m_weight = value;
						});
						statcfg<int>("Trader Value", "Trader value of " + englishName + ".", (SharedData shared) => shared.m_value, delegate(SharedData shared, int value)
						{
							shared.m_value = value;
						});
						if ((int)itemType == 4 || (int)itemType == 7 || (int)itemType == 12 || (int)itemType == 6 || (int)itemType == 11 || (int)itemType == 5 || (int)itemType == 17 || (int)itemType == 19 || (int)itemType == 3 || (int)itemType == 14 || (int)itemType == 22)
						{
							statcfg<float>("Durability", "Durability of " + englishName + ".", (SharedData shared) => shared.m_maxDurability, delegate(SharedData shared, float value)
							{
								shared.m_maxDurability = value;
							});
							statcfg<float>("Durability per Level", "Durability gain per level of " + englishName + ".", (SharedData shared) => shared.m_durabilityPerLevel, delegate(SharedData shared, float value)
							{
								shared.m_durabilityPerLevel = value;
							});
							statcfg<float>("Movement Speed Modifier", "Movement speed modifier of " + englishName + ".", (SharedData shared) => shared.m_movementModifier, delegate(SharedData shared, float value)
							{
								shared.m_movementModifier = value;
							});
						}
						if ((int)itemType == 4 || (int)itemType == 5 || (int)itemType == 3 || (int)itemType == 14 || (int)itemType == 22)
						{
							statcfg<float>("Block Armor", "Block armor of " + englishName + ".", (SharedData shared) => shared.m_blockPower, delegate(SharedData shared, float value)
							{
								shared.m_blockPower = value;
							});
							statcfg<float>("Block Armor per Level", "Block armor per level for " + englishName + ".", (SharedData shared) => shared.m_blockPowerPerLevel, delegate(SharedData shared, float value)
							{
								shared.m_blockPowerPerLevel = value;
							});
							statcfg<float>("Block Force", "Block force of " + englishName + ".", (SharedData shared) => shared.m_deflectionForce, delegate(SharedData shared, float value)
							{
								shared.m_deflectionForce = value;
							});
							statcfg<float>("Block Force per Level", "Block force per level for " + englishName + ".", (SharedData shared) => shared.m_deflectionForcePerLevel, delegate(SharedData shared, float value)
							{
								shared.m_deflectionForcePerLevel = value;
							});
							statcfg<float>("Parry Bonus", "Parry bonus of " + englishName + ".", (SharedData shared) => shared.m_timedBlockBonus, delegate(SharedData shared, float value)
							{
								shared.m_timedBlockBonus = value;
							});
						}
						else if ((int)itemType == 7 || (int)itemType == 12 || (int)itemType == 6 || (int)itemType == 11 || (int)itemType == 17)
						{
							statcfg<float>("Armor", "Armor of " + englishName + ".", (SharedData shared) => shared.m_armor, delegate(SharedData shared, float value)
							{
								shared.m_armor = value;
							});
							statcfg<float>("Armor per Level", "Armor per level for " + englishName + ".", (SharedData shared) => shared.m_armorPerLevel, delegate(SharedData shared, float value)
							{
								shared.m_armorPerLevel = value;
							});
						}
						SkillType skillType = shared2.m_skillType;
						if ((int)skillType == 7 || (int)skillType == 12)
						{
							statcfg<int>("Tool tier", "Tool tier of " + englishName + ".", (SharedData shared) => shared.m_toolTier, delegate(SharedData shared, int value)
							{
								shared.m_toolTier = value;
							});
						}
						if ((int)itemType == 5 || (int)itemType == 7 || (int)itemType == 12 || (int)itemType == 6 || (int)itemType == 11 || (int)itemType == 17)
						{
							Dictionary<DamageType, DamageModifier> modifiers = shared2.m_damageModifiers.ToDictionary((DamageModPair d) => d.m_type, (DamageModPair d) => (DamageModifier)d.m_modifier);
							DamageType[] first = (DamageType[])Enum.GetValues(typeof(DamageType));
							DamageType[] array = new DamageType[5];
							RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
							foreach (DamageType item9 in first.Except((IEnumerable<DamageType>)(object)array))
							{
								DamageType damageType = item9;
								statcfg<DamageModifier>(((object)(DamageType)(ref damageType)).ToString() + " Resistance", ((object)(DamageType)(ref damageType)).ToString() + " resistance of " + englishName + ".", (SharedData _) => modifiers.TryGetValue(damageType, out var value3) ? value3 : DamageModifier.None, delegate(SharedData shared, DamageModifier value)
								{
									//IL_0003: Unknown result type (might be due to invalid IL or missing references)
									//IL_000c: Unknown result type (might be due to invalid IL or missing references)
									//IL_0011: Unknown result type (might be due to invalid IL or missing references)
									//IL_0019: Unknown result type (might be due to invalid IL or missing references)
									//IL_001e: Unknown result type (might be due to invalid IL or missing references)
									//IL_001f: Unknown result type (might be due to invalid IL or missing references)
									//IL_002c: Unknown result type (might be due to invalid IL or missing references)
									//IL_0031: Unknown result type (might be due to invalid IL or missing references)
									//IL_0037: Unknown result type (might be due to invalid IL or missing references)
									//IL_009d: Unknown result type (might be due to invalid IL or missing references)
									//IL_0066: Unknown result type (might be due to invalid IL or missing references)
									DamageModPair val8 = default(DamageModPair);
									val8.m_type = damageType;
									val8.m_modifier = (DamageModifier)value;
									DamageModPair val9 = val8;
									for (int num2 = 0; num2 < shared.m_damageModifiers.Count; num2++)
									{
										if (shared.m_damageModifiers[num2].m_type == damageType)
										{
											if (value == DamageModifier.None)
											{
												shared.m_damageModifiers.RemoveAt(num2);
											}
											else
											{
												shared.m_damageModifiers[num2] = val9;
											}
											return;
										}
									}
									if (value != DamageModifier.None)
									{
										shared.m_damageModifiers.Add(val9);
									}
								});
							}
						}
						if ((int)itemType == 2 && shared2.m_food > 0f)
						{
							statcfg<float>("Health", "Health value of " + englishName + ".", (SharedData shared) => shared.m_food, delegate(SharedData shared, float value)
							{
								shared.m_food = value;
							});
							statcfg<float>("Stamina", "Stamina value of " + englishName + ".", (SharedData shared) => shared.m_foodStamina, delegate(SharedData shared, float value)
							{
								shared.m_foodStamina = value;
							});
							statcfg<float>("Eitr", "Eitr value of " + englishName + ".", (SharedData shared) => shared.m_foodEitr, delegate(SharedData shared, float value)
							{
								shared.m_foodEitr = value;
							});
							statcfg<float>("Duration", "Duration of " + englishName + ".", (SharedData shared) => shared.m_foodBurnTime, delegate(SharedData shared, float value)
							{
								shared.m_foodBurnTime = value;
							});
							statcfg<float>("Health Regen", "Health regen value of " + englishName + ".", (SharedData shared) => shared.m_foodRegen, delegate(SharedData shared, float value)
							{
								shared.m_foodRegen = value;
							});
						}
						if ((int)shared2.m_skillType == 10)
						{
							statcfg<float>("Health Cost", "Health cost of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackHealth, delegate(SharedData shared, float value)
							{
								shared.m_attack.m_attackHealth = value;
							});
							statcfg<float>("Health Cost Percentage", "Health cost percentage of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackHealthPercentage, delegate(SharedData shared, float value)
							{
								shared.m_attack.m_attackHealthPercentage = value;
							});
						}
						skillType = shared2.m_skillType;
						if ((int)skillType == 10 || (int)skillType == 9)
						{
							statcfg<float>("Eitr Cost", "Eitr cost of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackEitr, delegate(SharedData shared, float value)
							{
								shared.m_attack.m_attackEitr = value;
							});
						}
						if ((int)itemType == 3 || (int)itemType == 14 || (int)itemType == 22 || (int)itemType == 4)
						{
							statcfg<float>("Knockback", "Knockback of " + englishName + ".", (SharedData shared) => shared.m_attackForce, delegate(SharedData shared, float value)
							{
								shared.m_attackForce = value;
							});
							statcfg<float>("Backstab Bonus", "Backstab bonus of " + englishName + ".", (SharedData shared) => shared.m_backstabBonus, delegate(SharedData shared, float value)
							{
								shared.m_backstabBonus = value;
							});
							statcfg<float>("Attack Stamina", "Attack stamina of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackStamina, delegate(SharedData shared, float value)
							{
								shared.m_attack.m_attackStamina = value;
							});
							SetDmg("True", (DamageTypes dmg) => dmg.m_damage, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_damage = val;
							});
							SetDmg("Slash", (DamageTypes dmg) => dmg.m_slash, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_slash = val;
							});
							SetDmg("Pierce", (DamageTypes dmg) => dmg.m_pierce, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_pierce = val;
							});
							SetDmg("Blunt", (DamageTypes dmg) => dmg.m_blunt, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_blunt = val;
							});
							SetDmg("Chop", (DamageTypes dmg) => dmg.m_chop, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_chop = val;
							});
							SetDmg("Pickaxe", (DamageTypes dmg) => dmg.m_pickaxe, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_pickaxe = val;
							});
							SetDmg("Fire", (DamageTypes dmg) => dmg.m_fire, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_fire = val;
							});
							SetDmg("Poison", (DamageTypes dmg) => dmg.m_poison, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_poison = val;
							});
							SetDmg("Frost", (DamageTypes dmg) => dmg.m_frost, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_frost = val;
							});
							SetDmg("Lightning", (DamageTypes dmg) => dmg.m_lightning, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_lightning = val;
							});
							SetDmg("Spirit", (DamageTypes dmg) => dmg.m_spirit, delegate(ref DamageTypes dmg, float val)
							{
								dmg.m_spirit = val;
							});
							if ((int)itemType == 4)
							{
								statcfg<int>("Projectiles", "Number of projectiles that " + englishName + " shoots at once.", (SharedData shared) => shared.m_attack.m_projectileBursts, delegate(SharedData shared, int value)
								{
									shared.m_attack.m_projectileBursts = value;
								});
								statcfg<float>("Burst Interval", "Time between the projectiles " + englishName + " shoots at once.", (SharedData shared) => shared.m_attack.m_burstInterval, delegate(SharedData shared, float value)
								{
									shared.m_attack.m_burstInterval = value;
								});
								statcfg<float>("Minimum Accuracy", "Minimum accuracy for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileAccuracyMin, delegate(SharedData shared, float value)
								{
									shared.m_attack.m_projectileAccuracyMin = value;
								});
								statcfg<float>("Accuracy", "Accuracy for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileAccuracy, delegate(SharedData shared, float value)
								{
									shared.m_attack.m_projectileAccuracy = value;
								});
								statcfg<float>("Minimum Velocity", "Minimum velocity for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileVelMin, delegate(SharedData shared, float value)
								{
									shared.m_attack.m_projectileVelMin = value;
								});
								statcfg<float>("Velocity", "Velocity for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileVel, delegate(SharedData shared, float value)
								{
									shared.m_attack.m_projectileVel = value;
								});
								statcfg<float>("Maximum Draw Time", "Time until " + englishName + " is fully drawn at skill level 0.", (SharedData shared) => shared.m_attack.m_drawDurationMin, delegate(SharedData shared, float value)
								{
									shared.m_attack.m_drawDurationMin = value;
								});
								statcfg<float>("Stamina Drain", "Stamina drain per second while drawing " + englishName + ".", (SharedData shared) => shared.m_attack.m_drawStaminaDrain, delegate(SharedData shared, float value)
								{
									shared.m_attack.m_drawStaminaDrain = value;
								});
							}
						}
					}
					List<ConfigurationManagerAttributes> traderAttributes;
					if ((item3.configurability & Configurability.Trader) != 0)
					{
						traderAttributes = new List<ConfigurationManagerAttributes>();
						item3.traderConfig = new TraderConfig
						{
							trader = config(englishName, "Trader Selling", item3.Trade.Trader, new ConfigDescription("Which traders sell " + englishName + ".", (AcceptableValueBase)null, new object[1]
							{
								new ConfigurationManagerAttributes
								{
									Order = (order -= 1),
									Browsable = ((item3.configurationVisible & Configurability.Trader) != 0),
									Category = localizedName
								}
							}))
						};
						item3.traderConfig.trader.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
						{
							item3.ReloadTraderConfiguration();
							foreach (ConfigurationManagerAttributes item10 in traderAttributes)
							{
								item10.Browsable = TraderBrowsability();
							}
							reloadConfigDisplay();
						};
						item3.traderConfig.price = traderConfig<uint>("Trader Price", item3.Trade.Price, "Price of " + englishName + " at the trader.");
						item3.traderConfig.stack = traderConfig<uint>("Trader Stack", item3.Trade.Stack, "Stack size of " + englishName + " in the trader. Also known as the number of items sold by a trader in one transaction.");
						item3.traderConfig.requiredGlobalKey = traderConfig<string>("Trader Required Global Key", item3.Trade.RequiredGlobalKey ?? "", "Required global key to unlock " + englishName + " at the trader.");
						if (item3.traderConfig.trader.Value != 0)
						{
							PrefabManager.AddItemToTrader(item3.Prefab, item3.traderConfig.trader.Value, item3.traderConfig.price.Value, item3.traderConfig.stack.Value, item3.traderConfig.requiredGlobalKey.Value);
						}
					}
					else if (item3.Trade.Trader != 0)
					{
						PrefabManager.AddItemToTrader(item3.Prefab, item3.Trade.Trader, item3.Trade.Price, item3.Trade.Stack, item3.Trade.RequiredGlobalKey);
					}
					void SetDmg(string dmgType, Func<DamageTypes, float> readDmg, setDmgFunc setDmg)
					{
						statcfg<float>(dmgType + " Damage", dmgType + " damage dealt by " + englishName + ".", (SharedData shared) => readDmg(shared.m_damages), delegate(SharedData shared, float val)
						{
							setDmg(ref shared.m_damages, val);
						});
						statcfg<float>(dmgType + " Damage Per Level", dmgType + " damage dealt increase per level for " + englishName + ".", (SharedData shared) => readDmg(shared.m_damagesPerLevel), delegate(SharedData shared, float val)
						{
							setDmg(ref shared.m_damagesPerLevel, val);
						});
					}
					bool TraderBrowsability()
					{
						return item3.traderConfig.trader.Value != Trader.None;
					}
					void statcfg<T>(string configName, string description, [<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 1, 1, 0 })] Func<SharedData, T> readDefault, [<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 1, 1, 0 })] Action<SharedData, T> setValue)
					{
						//IL_0079: Unknown result type (might be due to invalid IL or missing references)
						//IL_0083: Expected O, but got Unknown
						SharedData shared3 = item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared;
						ConfigEntry<T> cfg2 = config(englishName, configName, readDefault(shared3), new ConfigDescription(description, (AcceptableValueBase)null, new object[1]
						{
							new ConfigurationManagerAttributes
							{
								Category = localizedName,
								Browsable = ((item3.configurationVisible & Configurability.Stats) != 0)
							}
						}));
						if ((item3.configurationVisible & Configurability.Stats) != 0)
						{
							setValue(shared3, cfg2.Value);
						}
						item3.statsConfigs.Add((ConfigEntryBase)(object)cfg2, ApplyConfig);
						cfg2.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
						{
							if ((item3.configurationVisible & Configurability.Stats) != 0)
							{
								ApplyConfig();
							}
						};
						void ApplyConfig()
						{
							item3.ApplyToAllInstances(delegate(ItemData item)
							{
								setValue(item.m_shared, cfg2.Value);
							});
						}
					}
					[return: <6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 1, 0 })]
					ConfigEntry<T> traderConfig<T>(string name, [<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(0)] T value, string desc)
					{
						//IL_009b: Unknown result type (might be due to invalid IL or missing references)
						//IL_00a5: Expected O, but got Unknown
						ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes
						{
							Order = (order -= 1),
							browsability = TraderBrowsability,
							Browsable = (TraderBrowsability() && (item3.configurationVisible & Configurability.Trader) != 0),
							Category = localizedName
						};
						traderAttributes.Add(configurationManagerAttributes2);
						ConfigEntry<T> val5 = config(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 }));
						val5.SettingChanged += [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object _, EventArgs _) =>
						{
							item3.ReloadTraderConfiguration();
						};
						return val5;
					}
				}
				if (saveOnConfigSet)
				{
					plugin.Config.SaveOnConfigSet = true;
					plugin.Config.Save();
				}
			}
			configManager = ((type == null) ? null : Chainloader.ManagerObject.GetComponent(type));
			foreach (Item registeredItem in registeredItems)
			{
				Item item2 = registeredItem;
				foreach (KeyValuePair<string, ItemRecipe> recipe in item2.Recipes)
				{
					KeyValuePair<string, ItemRecipe> kv = recipe;
					RequiredResourceList[] array2 = new RequiredResourceList[2]
					{
						kv.Value.RequiredItems,
						kv.Value.RequiredUpgradeItems
					};
					foreach (RequiredResourceList requiredResourceList in array2)
					{
						for (int l = 0; l < requiredResourceList.Requirements.Count; l++)
						{
							ConfigEntry<int> amountCfg;
							int resourceIndex;
							if ((item2.configurability & Configurability.Recipe) != 0)
							{
								amountCfg = requiredResourceList.Requirements[l].amountConfig;
								if (amountCfg != null)
								{
									resourceIndex = l;
									amountCfg.SettingChanged += ConfigChanged;
								}
							}
							void ConfigChanged(object o, EventArgs e)
							{
								if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(kv.Key, out var value2))
								{
									foreach (Recipe item11 in value2)
									{
										item11.m_resources[resourceIndex].m_amount = amountCfg.Value;
									}
								}
							}
						}
					}
				}
				item2.InitializeNewRegisteredItem();
			}
		}

		private void InitializeNewRegisteredItem()
		{
			foreach (KeyValuePair<string, ItemRecipe> recipe in Recipes)
			{
				KeyValuePair<string, ItemRecipe> kv = recipe;
				ConfigEntryBase enabledCfg = kv.Value.RecipeIsActive;
				if (enabledCfg != null)
				{
					((object)enabledCfg).GetType().GetEvent("SettingChanged").AddEventHandler(enabledCfg, new EventHandler(ConfigChanged));
				}
				void ConfigChanged(object o, EventArgs e)
				{
					if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(kv.Key, out var value))
					{
						foreach (Recipe item in value)
						{
							item.m_enabled = (int)enabledCfg.BoxedValue != 0;
						}
					}
				}
			}
		}

		public void ReloadCraftingConfiguration()
		{
			if (Object.op_Implicit((Object)(object)ObjectDB.instance) && ObjectDB.instance.GetItemPrefab(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name)) == null)
			{
				registerRecipesInObjectDB(ObjectDB.instance);
				ObjectDB.instance.m_items.Add(Prefab);
				ObjectDB.instance.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab);
				ZNetScene.instance.m_prefabs.Add(Prefab);
				ZNetScene.instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab);
			}
			foreach (string item in Recipes.Keys.DefaultIfEmpty(""))
			{
				if (Recipes.TryGetValue(item, out var value) && value.Crafting.Stations.Count > 0)
				{
					UpdateItemTableConfig(item, value.Crafting.Stations.First().Table, value.Crafting.Stations.First().custom ?? "");
					UpdateCraftConfig(item, new SerializedRequirements(value.RequiredItems.Requirements), new SerializedRequirements(value.RequiredUpgradeItems.Requirements));
				}
			}
		}

		private void ReloadTraderConfiguration()
		{
			if (traderConfig.trader.Value == Trader.None)
			{
				PrefabManager.RemoveItemFromTrader(Prefab);
			}
			else
			{
				PrefabManager.AddItemToTrader(Prefab, traderConfig.trader.Value, traderConfig.price.Value, traderConfig.stack.Value, traderConfig.requiredGlobalKey.Value);
			}
		}

		public static void ApplyToAllInstances(GameObject prefab, Action<ItemData> callback)
		{
			callback(prefab.GetComponent<ItemDrop>().m_itemData);
			string name = prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name;
			Inventory[] source = (from c in Player.s_players.Select([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsOfType<Container>()
					select c.GetInventory())
				where c != null
				select c).ToArray();
			foreach (ItemData item in (from i in (from p in ObjectDB.instance.m_items
					select p.GetComponent<ItemDrop>() into c
					where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent<ZNetView>())
					select c).Concat(ItemDrop.s_instances)
				select i.m_itemData).Concat(source.SelectMany([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Inventory i) => i.GetAllItems())))
			{
				if (item.m_shared.m_name == name)
				{
					callback(item);
				}
			}
		}

		public void ApplyToAllInstances(Action<ItemData> callback)
		{
			ApplyToAllInstances(Prefab, callback);
		}

		[<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)]
		[return: <6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(1)]
		private static string getInternalName<T>(T value) where T : struct
		{
			return ((InternalName)typeof(T).GetMember(value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName;
		}

		private void registerRecipesInObjectDB(ObjectDB objectDB)
		{
			//IL_049b: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e9: Expected O, but got Unknown
			activeRecipes[this] = new Dictionary<string, List<Recipe>>();
			itemCraftConfigs.TryGetValue(this, out var value);
			foreach (KeyValuePair<string, ItemRecipe> recipe in Recipes)
			{
				List<Recipe> list = new List<Recipe>();
				foreach (CraftingStationConfig station in recipe.Value.Crafting.Stations)
				{
					ItemConfig itemConfig = value?[recipe.Key];
					Recipe val = ScriptableObject.CreateInstance<Recipe>();
					((Object)val).name = ((Object)Prefab).name + "_Recipe_" + station.Table;
					val.m_amount = recipe.Value.CraftAmount;
					val.m_enabled = itemConfig == null || itemConfig.table.Value != CraftingTable.Disabled;
					val.m_item = Prefab.GetComponent<ItemDrop>();
					val.m_resources = SerializedRequirements.toPieceReqs(objectDB, (itemConfig?.craft == null) ? new SerializedRequirements(recipe.Value.RequiredItems.Requirements) : new SerializedRequirements(itemConfig.craft.Value), (itemConfig?.upgrade == null) ? new SerializedRequirements(recipe.Value.RequiredUpgradeItems.Requirements) : new SerializedRequirements(itemConfig.upgrade.Value));
					CraftingTable craftingTable = ((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value);
					if (craftingTable == CraftingTable.Inventory || craftingTable == CraftingTable.Disabled)
					{
						val.m_craftingStation = null;
					}
					else if (((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value) == CraftingTable.Custom)
					{
						GameObject prefab = ZNetScene.instance.GetPrefab((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value);
						if (prefab != null)
						{
							val.m_craftingStation = prefab.GetComponent<CraftingStation>();
						}
						else
						{
							Debug.LogWarning((object)("Custom crafting station '" + ((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value) + "' does not exist"));
						}
					}
					else
					{
						val.m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value)).GetComponent<CraftingStation>();
					}
					val.m_minStationLevel = ((itemConfig == null || list.Count > 0) ? station.level : itemConfig.tableLevel.Value);
					val.m_requireOnlyOneIngredient = ((itemConfig == null) ? recipe.Value.RequireOnlyOneIngredient : (itemConfig.requireOneIngredient.Value == Toggle.On));
					val.m_qualityResultAmountMultiplier = itemConfig?.qualityResultAmountMultiplier.Value ?? recipe.Value.QualityResultAmountMultiplier;
					ConfigEntryBase recipeIsActive = recipe.Value.RecipeIsActive;
					val.m_enabled = (int)(((recipeIsActive != null) ? recipeIsActive.BoxedValue : null) ?? ((object)1)) != 0;
					list.Add(val);
					RequiredResourceList requiredItems = recipe.Value.RequiredItems;
					if (requiredItems != null && !requiredItems.Free)
					{
						List<Requirement> requirements = requiredItems.Requirements;
						if (requirements != null && requirements.Count == 0)
						{
							hiddenCraftRecipes.Add(val, recipe.Value.RecipeIsActive);
						}
					}
					requiredItems = recipe.Value.RequiredUpgradeItems;
					if (requiredItems != null && !requiredItems.Free)
					{
						List<Requirement> requirements = requiredItems.Requirements;
						if (requirements != null && requirements.Count == 0)
						{
							hiddenUpgradeRecipes.Add(val, recipe.Value.RecipeIsActive);
						}
					}
				}
				activeRecipes[this].Add(recipe.Key, list);
				objectDB.m_recipes.AddRange(list);
			}
			conversions = new List<ItemConversion>();
			for (int i = 0; i < Conversions.Count; i++)
			{
				Conversion conversion = Conversions[i];
				conversions.Add(new ItemConversion
				{
					m_from = SerializedRequirements.fetchByName(ObjectDB.instance, conversion.config?.input.Value ?? conversion.Input),
					m_to = Prefab.GetComponent<ItemDrop>()
				});
				ConversionPiece conversionPiece = conversion.config?.piece.Value ?? conversion.Piece;
				string text = null;
				if (conversionPiece != 0 && conversions[i].m_from != null)
				{
					text = ((conversionPiece != ConversionPiece.Custom) ? getInternalName(conversionPiece) : (conversion.config?.customPiece.Value ?? conversion.customPiece));
					GameObject prefab2 = ZNetScene.instance.GetPrefab(text);
					Smelter val2 = ((prefab2 != null) ? prefab2.GetComponent<Smelter>() : null);
					if (val2 != null)
					{
						val2.m_conversion.Add(conversions[i]);
					}
					else
					{
						text = null;
					}
				}
				if (conversion.config != null)
				{
					conversion.config.activePiece = text;
				}
			}
		}

		[HarmonyPriority(0)]
		internal static void Patch_ObjectDBInit(ObjectDB __instance)
		{
			if ((Object)(object)__instance.GetItemPrefab("Wood") == (Object)null)
			{
				return;
			}
			hiddenCraftRecipes.Clear();
			hiddenUpgradeRecipes.Clear();
			foreach (Item registeredItem in registeredItems)
			{
				registeredItem.registerRecipesInObjectDB(__instance);
			}
		}

		internal static void Patch_TraderGetAvailableItems(Trader __instance, ref List<TradeItem> __result)
		{
			string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject);
			if (1 == 0)
			{
			}
			Trader trader2 = ((prefabName == "Haldor") ? Trader.Haldor : ((prefabName == "Hildir") ? Trader.Hildir : Trader.None));
			if (1 == 0)
			{
			}
			Trader trader = trader2;
			__result.AddRange(from tuple in PrefabManager.CustomTradeItems.Values
				where (tuple.Item1 & trader) != 0
				select tuple.Item2 into tradeItem
				where string.IsNullOrEmpty(tradeItem.m_requiredGlobalKey) || ZoneSystem.instance.GetGlobalKey(tradeItem.m_requiredGlobalKey)
				select tradeItem);
		}

		internal static void Patch_OnAddSmelterInput(ItemData item, bool __result)
		{
			if (__result)
			{
				((Humanoid)Player.m_localPlayer).UnequipItem(item, true);
			}
		}

		internal static void Patch_MaximumRequiredStationLevel(Recipe __instance, ref int __result, int quality)
		{
			if (!itemDropMap.TryGetValue(__instance.m_item, out var value))
			{
				return;
			}
			IEnumerable<ItemConfig> source;
			if (!itemCraftConfigs.TryGetValue(value, out var value2))
			{
				source = Enumerable.Empty<ItemConfig>();
			}
			else
			{
				CraftingStation currentCraftingStation = Player.m_localPlayer.GetCurrentCraftingStation();
				if (currentCraftingStation != null)
				{
					string stationName = Utils.GetPrefabName(((Component)currentCraftingStation).gameObject);
					source = from c in value2.Where([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (KeyValuePair<string, ItemConfig> c) =>
						{
							CraftingTable value3 = c.Value.table.Value;
							if (1 == 0)
							{
							}
							bool result;
							switch (value3)
							{
							case CraftingTable.Disabled:
							case CraftingTable.Inventory:
								result = false;
								break;
							case CraftingTable.Custom:
								result = c.Value.customTable.Value == stationName;
								break;
							default:
								result = getInternalName(c.Value.table.Value) == stationName;
								break;
							}
							if (1 == 0)
							{
							}
							return result;
						})
						select c.Value;
				}
				else
				{
					source = value2.Values;
				}
			}
			__result = Mathf.Min(Mathf.Max(1, __instance.m_minStationLevel) + (quality - 1), (from cfg in source
				where cfg.maximumTableLevel != null
				select cfg.maximumTableLevel.Value).DefaultIfEmpty(value.MaximumRequiredStationLevel).Max());
		}

		internal static void Patch_GetAvailableRecipesPrefix([<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 2, 1, 1, 1, 2 })] ref Dictionary<Assembly, Dictionary<Recipe, ConfigEntryBase>> __state)
		{
			if (__state == null)
			{
				__state = new Dictionary<Assembly, Dictionary<Recipe, ConfigEntryBase>>();
			}
			Dictionary<Recipe, ConfigEntryBase> dictionary;
			if (InventoryGui.instance.InCraftTab())
			{
				dictionary = hiddenCraftRecipes;
			}
			else
			{
				if (!InventoryGui.instance.InUpradeTab())
				{
					return;
				}
				dictionary = hiddenUpgradeRecipes;
			}
			foreach (Recipe key in dictionary.Keys)
			{
				key.m_enabled = false;
			}
			__state[Assembly.GetExecutingAssembly()] = dictionary;
		}

		internal static void Patch_GetAvailableRecipesFinalizer([<6105c9b5-1062-4eea-9a73-bf83d69f68e5>Nullable(new byte[] { 1, 1, 1, 1, 2 })] Dictionary<Assembly, Dictionary<Recipe, ConfigEntryBase>> __state)
		{
			if (!__state.TryGetValue(Assembly.GetExecutingAssembly(), out var value))
			{
				return;
			}
			foreach (KeyValuePair<Recipe, ConfigEntryBase> item in value)
			{
				Recipe key = item.Key;
				ConfigEntryBase value2 = item.Value;
				key.m_enabled = (int)(((value2 != null) ? value2.BoxedValue : null) ?? ((object)1)) != 0;
			}
		}

		internal static IEnumerable<CodeInstruction> Transpile_SetupRequirementList(IEnumerable<CodeInstruction> instructionsEnumerable, ILGenerator ilg)
		{
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Expected O, but got Unknown
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Expected O, but got Unknown
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Expected O, but got Unknown
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Expected O, but got Unknown
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Expected O, but got Unknown
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Expected O, but got Unknown
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Expected O, but got Unknown
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Expected O, but got Unknown
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Expected O, but got Unknown
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Expected O, but got Unknown
			List<CodeInstruction> list = instructionsEnumerable.ToList();
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(InventoryGui), "SetupRequirement", (Type[])null, (Type[])null);
			CodeInstruction val = null;
			CodeInstruction val2 = null;
			LocalBuilder localBuilder = ilg.DeclareLocal(typeof(int));
			Dictionary<Label, int> dictionary = new Dictionary<Label, int>();
			bool flag = false;
			int num = 0;
			int value = 0;
			Label? label = default(Label?);
			for (int i = 0; i < list.Count; i++)
			{
				if (CodeInstructionExtensions.Calls(list[i], methodInfo))
				{
					val = list[i + 2];
					val2 = list[i + 5];
					flag = true;
				}
				if (flag)
				{
					if (CodeInstructionExtensions.Branches(list[i], ref label) && dictionary.TryGetValue(label.Value, out value))
					{
						num = i;
						break;
					}
					continue;
				}
				foreach (Label label4 in list[i].labels)
				{
					dictionary[label4] = i;
				}
			}
			if (list[value - 3].opcode == OpCodes.Dup)
			{
				return list;
			}
			Label label2 = ilg.DefineLabel();
			Label label3 = ilg.DefineLabel();
			list[num + 1].labels.Add(label2);
			list.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[11]
			{
				new CodeInstruction(OpCodes.Ldloc, (object)localBuilder),
				new CodeInstruction(OpCodes.Brfalse, (object)label2),
				val.Clone(),
				new CodeInstruction(OpCodes.Ldarg_0, (object)null),
				new CodeInstruction(OpCodes.Ldfld, (object)AccessTools.DeclaredField(typeof(InventoryGui), "m_recipeRequirementList")),
				new CodeInstruction(OpCodes.Ldlen, (object)null),
				new CodeInstruction(OpCodes.Bgt, (object)label2),
				new CodeInstruction(OpCodes.Ldc_I4_0, (object)null),
				val2.Clone(),
				new CodeInstruction(OpCodes.Ldc_I4_0, (object)null),
				new CodeInstruction(OpCodes.Br, (object)label3)
			});
			list.InsertRange(value - 2, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
			{
				new CodeInstruction(OpCodes.Dup, (object)null)
				{
					labels = new List<Label> { label3 }
				},
				new CodeInstruction(OpCodes.Stloc, (object)localBuilder)
			});
			return list;
		}

		internal static bool Patch_RequirementGetAmount(Requirement __instance, int qualityLevel, ref int __result)
		{
			if (requirementQuality.TryGetValue(__instance, out var value))
			{
				__result = ((value.quality == qualityLevel) ? __instance.m_amountPerLevel : 0);
				return false;
			}
			return true;
		}

		internal static void Patch_ZNetSceneAwake(ZNetScene __instance)
		{
			foreach (Item registeredItem in registeredItems)
			{
				registeredItem.AssignDropToCreature();
			}
		}

		public void AssignDropToCreature()
		{
			foreach (KeyValuePair<CharacterDrop, Drop> characterDrop in characterDrops)
			{
				if (Object.op_Implicit((Object)(object)characterDrop.Key))
				{
					characterDrop.Key.m_drops.Remove(characterDrop.Value);
				}
			}
			characterDrops.Clear();
			SerializedDrop serializedDrop = new SerializedDrop(DropsFrom.Drops);
			if (itemDropConfigs.TryGetValue(this, out var value))
			{
				serializedDrop = new SerializedDrop(value.Value);
			}
			foreach (KeyValuePair<Character, Drop> item in serializedDrop.toCharacterDrops(ZNetScene.s_instance, Prefab))
			{
				CharacterDrop val = ((Component)item.Key).GetComponent<CharacterDrop>();
				if (val == null)
				{
					val = ((Component)item.Key).gameObject.AddComponent<CharacterDrop>();
				}
				val.m_drops.Add(item.Value);
				characterDrops.Add(val, item.Value);
			}
		}

		public void UpdateCharacterDrop()
		{
			if (Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				AssignDropToCreature();
			}
		}

		public void Snapshot(float lightIntensity = 1.3f, Quaternion? cameraRotation = null, Quaternion? itemRotation = null)
		{
			SnapshotItem(Prefab.GetComponent<ItemDrop>(), lightIntensity, cameraRotation, itemRotation);
		}

		public static void SnapshotItem(ItemDrop item, float lightIntensity = 1.3f, Quaternion? cameraRotation = null, Quaternion? itemRotation = null)
		{
			if (Object.op_Implicit((Object)(object)ObjectDB.instance))
			{
				Do();
			}
			else
			{
				((MonoBehaviour)plugin).StartCoroutine(Delay());
			}
			IEnumerator Delay()
			{
				yield return null;
				Do();
			}
			void Do()
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_0185: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0220: Unknown result type (might be due to invalid IL or missing references)
				//IL_0225: Unknown result type (might be due to invalid IL or missing references)
				//IL_0227: Unknown result type (might be due to invalid IL or missing references)
				//IL_0229: Unknown result type (might be due to invalid IL or missing references)
				//IL_022b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0230: Unknown result type (might be due to invalid IL or missing references)
				//IL_024e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0255: Unknown result type (might be due to invalid IL or missing references)
				//IL_0263: Unknown result type (might be due to invalid IL or missing references)
				//IL_026a: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
				//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
				//IL_0303: Unknown result type (might be due to invalid IL or missing references)
				//IL_030d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0315: Unknown result type (might be due to invalid IL or missing references)
				//IL_031a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0351: Unknown result type (might be due to invalid IL or missing references)
				//IL_0358: Expected O, but got Unknown
				//IL_035a: Unknown result type (might be due to invalid IL or missing references)
				//IL_038d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0398: Unknown result type (might be due to invalid IL or missing references)
				Camera component = new GameObject("Camera", new Type[1] { typeof(Camera) }).GetComponent<Camera>();
				component.backgroundColor = Color.clear;
				component.clearFlags = (CameraClearFlags)2;
				component.fieldOfView = 0.5f;
				component.farClipPlane = 10000000f;
				component.cullingMask = 1073741824;
				((Component)component).transform.rotation = (Quaternion)(((??)cameraRotation) ?? Quaternion.Euler(90f, 0f, 45f));
				Light component2 = new GameObject("Light", new Type[1] { typeof(Light) }).GetComponent<Light>();
				((Component)component2).transform.rotation = Quaternion.Euler(150f, 0f, -5f);
				component2.type = (LightType)1;
				component2.cullingMask = 1073741824;
				component2.intensity = lightIntensity;
				Rect val = default(Rect);
				((Rect)(ref val))..ctor(0f, 0f, 64f, 64f);
				Transform val2 = ((Component)item).transform.Find("attach");
				GameObject val3;
				if (val2 != null)
				{
					val3 = Object.Instantiate<GameObject>(((Component)val2).gameObject);
				}
				else
				{
					ZNetView.m_forceDisableInit = true;
					val3 = Object.Instantiate<GameObject>(((Component)item).gameObject);
					ZNetView.m_forceDisableInit = false;
				}
				if (itemRotation.HasValue)
				{
					val3.transform.rotation = itemRotation.Value;
				}
				Transform[] componentsInChildren = val3.GetComponentsInChildren<Transform>();
				foreach (Transform val4 in componentsInChildren)
				{
					((Component)val4).gameObject.layer = 30;
				}
				Renderer[] componentsInChildren2 = val3.GetComponentsInChildren<Renderer>();
				Vector3 val5 = componentsInChildren2.Aggregate(Vector3.positiveInfinity, [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Vector3 cur, Renderer renderer) =>
				{
					//IL_001e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					//IL_000a: Unknown result type (might be due to invalid IL or missing references)
					//IL_000f: Unknown result type (might be due to invalid IL or missing references)
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					Vector3 result2;
					if (!(renderer is ParticleSystemRenderer))
					{
						Bounds bounds2 = renderer.bounds;
						result2 = Vector3.Min(cur, ((Bounds)(ref bounds2)).min);
					}
					else
					{
						result2 = cur;
					}
					return result2;
				});
				Vector3 val6 = componentsInChildren2.Aggregate(Vector3.negativeInfinity, [<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (Vector3 cur, Renderer renderer) =>
				{
					//IL_001e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0008: Unknown result type (might be due to invalid IL or missing references)
					//IL_000a: Unknown result type (might be due to invalid IL or missing references)
					//IL_000f: Unknown result type (might be due to invalid IL or missing references)
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					Vector3 result;
					if (!(renderer is ParticleSystemRenderer))
					{
						Bounds bounds = renderer.bounds;
						result = Vector3.Max(cur, ((Bounds)(ref bounds)).max);
					}
					else
					{
						result = cur;
					}
					return result;
				});
				Vector3 val7 = val6 - val5;
				component.targetTexture = RenderTexture.GetTemporary((int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height);
				float num = Mathf.Max(val7.x, val7.z);
				float num2 = Mathf.Min(val7.x, val7.z);
				float num3 = (num + num2) / Mathf.Sqrt(2f) / Mathf.Tan(component.fieldOfView * ((float)Math.PI / 180f));
				Transform transform = ((Component)component).transform;
				Vector3 val8 = (val5 + val6) / 2f;
				val8.y = val6.y;
				transform.position = val8 + new Vector3(0f, num3, 0f);
				((Component)component2).transform.position = transform.position + new Vector3(-2f, 0f, 0.2f) / 3f * (0f - num3);
				component.Render();
				RenderTexture active = RenderTexture.active;
				RenderTexture.active = component.targetTexture;
				Texture2D val9 = new Texture2D((int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height, (TextureFormat)4, false);
				val9.ReadPixels(val, 0, 0);
				val9.Apply();
				RenderTexture.active = active;
				item.m_itemData.m_shared.m_icons = (Sprite[])(object)new Sprite[1] { Sprite.Create(val9, val, new Vector2(0.5f, 0.5f)) };
				Object.DestroyImmediate((Object)(object)val3);
				component.targetTexture.Release();
				Object.Destroy((Object)(object)component);
				Object.Destroy((Object)(object)component2);
			}
		}

		private static bool CheckItemIsUpgrade(InventoryGui gui)
		{
			ItemData value = gui.m_selectedRecipe.Value;
			return value != null && value.m_quality > 0;
		}

		internal static IEnumerable<CodeInstruction> Transpile_InventoryGui(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> instrs = instructions.ToList();
			FieldInfo amountField = AccessTools.DeclaredField(typeof(Recipe), "m_amount");
			int i = 0;
			while (i < instrs.Count)
			{
				yield return instrs[i];
				if (i > 1 && instrs[i - 2].opcode == OpCodes.Ldfld && CodeInstructionExtensions.OperandIs(instrs[i - 2], (MemberInfo)amountField) && instrs[i - 1].opcode == OpCodes.Ldc_I4_1 && instrs[i].operand is Label)
				{
					yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
					yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(Item), "CheckItemIsUpgrade", (Type[])null, (Type[])null));
					yield return new CodeInstruction(OpCodes.Brtrue, instrs[i].operand);
				}
				int num = i + 1;
				i = num;
			}
		}

		private static Action<ConfigEntryBase> drawRequirementsConfigTable(Item item, bool isUpgrade)
		{
			return delegate(ConfigEntryBase cfg)
			{
				bool locked = cfg.Description.Tags.Select([<d0475ce3-abe5-4139-a18c-3580fbf64682>NullableContext(0)] (object a) => (a.GetType().Name == "ConfigurationManagerAttributes") ? ((bool?)a.GetType().GetField("ReadOnly")?.GetValue(a)) : null).FirstOrDefault((bool? v) => v.HasValue).GetValueOrDefault();
				List<Requirement> newReqs = new List<Requirement>();
				bool wasUpdated = false;
				int RightColumnWidth = (int)(configManager?.GetType().GetProperty("RightColumnWidth", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(nonP

BepInEx/plugins/ComfyMods-ComfyAddAllFuel/AddAllFuel.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("AddAllFuel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AddAllFuel")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("52be6d2b-daf1-446a-88a5-1c2e02280b51")]
[assembly: AssemblyFileVersion("1.7.1")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.7.1.0")]
[module: UnverifiableCode]
namespace AddAllFuel
{
	[BepInPlugin("bruceofthebow.valheim.AddAllFuel", "ComfyAddAllFuel", "1.7.1")]
	public class AddAllFuel : BaseUnityPlugin
	{
		public const string PluginGuid = "bruceofthebow.valheim.AddAllFuel";

		public const string PluginName = "ComfyAddAllFuel";

		public const string PluginVersion = "1.7.1";

		private static readonly bool _debug = true;

		private static List<string> ExcludeNames = new List<string> { "$item_finewood" };

		private static ManualLogSource _logger;

		private Harmony _harmony;

		private void Awake()
		{
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
			_logger = ((BaseUnityPlugin)this).Logger;
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "bruceofthebow.valheim.AddAllFuel");
		}

		public static ItemData FindCookableItem(Smelter __instance, Inventory inventory, bool isAddOne)
		{
			IEnumerable<string> enumerable = null;
			enumerable = ((!PluginConfig.ExcludeFinewood.Value) ? __instance.m_conversion.Select((ItemConversion n) => n.m_from.m_itemData.m_shared.m_name) : (from n in __instance.m_conversion
				where !ExcludeNames.Contains(n.m_from.m_itemData.m_shared.m_name)
				select n.m_from.m_itemData.m_shared.m_name));
			if (enumerable == null)
			{
				return null;
			}
			foreach (string item in enumerable)
			{
				ItemData val = ((inventory != null) ? inventory.GetItem(item, -1, false) : null);
				if (val != null)
				{
					return val;
				}
			}
			return null;
		}

		public static void log(string message)
		{
			if (_debug)
			{
				_logger.LogMessage((object)message);
			}
		}
	}
	public class PluginConfig
	{
		public static ConfigEntry<bool> IsModEnabled { get; private set; }

		public static ConfigEntry<bool> ExcludeFinewood { get; private set; }

		public static ConfigEntry<KeyCode> ModifierKey { get; private set; }

		public static void BindConfig(ConfigFile config)
		{
			IsModEnabled = config.Bind<bool>("Global", "isModEnabled", true, "Globally enable or disable this mod.");
			ExcludeFinewood = config.Bind<bool>("ExcludeFinewood", "excludeFinewood", true, "Filter finewood out of items to add to kilns");
			ModifierKey = config.Bind<KeyCode>("ModifierKey", "ModifierKey", (KeyCode)304, "Modifier key to hold for using add all feature.");
		}
	}
}
namespace AddAllFuel.Patches
{
	[HarmonyPatch(typeof(Fireplace))]
	public static class FireplacePatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("Interact")]
		public static bool FireplaceInteractPrefix(ref Fireplace __instance, Humanoid user, bool hold, bool alt, ref bool __result)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			bool flag = !Input.GetKey(PluginConfig.ModifierKey.Value);
			if (!PluginConfig.IsModEnabled.Value || flag)
			{
				return true;
			}
			__result = false;
			if (hold)
			{
				return false;
			}
			if (!__instance.m_nview.HasOwner())
			{
				__instance.m_nview.ClaimOwnership();
			}
			string name = __instance.m_fuelItem.m_itemData.m_shared.m_name;
			ZLog.Log((object)("Found fuel " + name));
			float num = Mathf.CeilToInt(__instance.m_nview.GetZDO().GetFloat("fuel", 0f));
			if (num > __instance.m_maxFuel - 1f)
			{
				((Character)user).Message((MessageType)2, Localization.instance.Localize("$msg_cantaddmore", new string[1] { name }), 0, (Sprite)null);
				return false;
			}
			ZLog.Log((object)("Checking Inventory for fuel " + name));
			Inventory inventory = user.GetInventory();
			ItemData val = ((inventory != null) ? inventory.GetItem(name, -1, false) : null);
			if (val == null)
			{
				if (flag)
				{
					return true;
				}
				((Character)user).Message((MessageType)2, "$msg_outof " + name, 0, (Sprite)null);
				return false;
			}
			((Character)user).Message((MessageType)2, Localization.instance.Localize("$msg_fireadding", new string[1] { name }), 0, (Sprite)null);
			int val2 = (int)(__instance.m_maxFuel - num);
			int num2 = 1;
			if (!flag)
			{
				num2 = Math.Min(val.m_stack, val2);
			}
			user.GetInventory().RemoveItem(val, num2);
			for (int i = 0; i < num2; i++)
			{
				__instance.m_nview.InvokeRPC("AddFuel", Array.Empty<object>());
			}
			__result = true;
			return false;
		}

		public static void RPC_AddFuel(Fireplace instance, ZNetView m_nview, float count)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			if (m_nview.IsOwner())
			{
				float @float = m_nview.GetZDO().GetFloat("fuel", 0f);
				float num = Mathf.Clamp(@float + count, 0f, instance.m_maxFuel);
				m_nview.GetZDO().Set("fuel", num);
				instance.m_fuelAddedEffects.Create(((Component)instance).transform.position, ((Component)instance).transform.rotation, (Transform)null, 1f, -1);
				ZLog.Log((object)$"Added fuel * {count}");
				Traverse.Create((object)instance).Method("UpdateState", Array.Empty<object>()).GetValue();
			}
		}
	}
	[HarmonyPatch(typeof(Smelter))]
	public static class SmelterPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("OnAddOre")]
		public static bool SmelterOnAddOrePrefix(ref Smelter __instance, ref Switch sw, ref Humanoid user, ItemData item, ref bool __result)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			bool flag = !Input.GetKey(PluginConfig.ModifierKey.Value);
			if (!PluginConfig.IsModEnabled.Value || flag)
			{
				return true;
			}
			__result = false;
			int value = Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>();
			if (value >= __instance.m_maxOre)
			{
				((Character)user).Message((MessageType)2, "$msg_itsfull", 0, (Sprite)null);
				return false;
			}
			if (item == null)
			{
				item = AddAllFuel.FindCookableItem(__instance, user.GetInventory(), flag);
			}
			if (item == null)
			{
				if (flag)
				{
					return true;
				}
				((Character)user).Message((MessageType)2, "$msg_noprocessableitems", 0, (Sprite)null);
				return false;
			}
			if (!Traverse.Create((object)__instance).Method("IsItemAllowed", new object[1] { ((Object)item.m_dropPrefab).name }).GetValue<bool>())
			{
				((Character)user).Message((MessageType)2, "$msg_wontwork", 0, (Sprite)null);
				return false;
			}
			((Character)user).Message((MessageType)2, "$msg_added " + item.m_shared.m_name, 0, (Sprite)null);
			int val = __instance.m_maxOre - value;
			int num = 1;
			if (!flag)
			{
				num = Math.Min(item.m_stack, val);
			}
			user.GetInventory().RemoveItem(item, num);
			for (int i = 0; i < num; i++)
			{
				__instance.m_nview.InvokeRPC("AddOre", new object[1] { ((Object)item.m_dropPrefab).name });
			}
			__result = true;
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch("OnAddFuel")]
		public static bool Prefix(ref Smelter __instance, ref bool __result, Switch sw, Humanoid user, ItemData item)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			bool flag = !Input.GetKey(PluginConfig.ModifierKey.Value);
			if (!PluginConfig.IsModEnabled.Value || flag)
			{
				return true;
			}
			__result = false;
			string name = __instance.m_fuelItem.m_itemData.m_shared.m_name;
			if (item != null && item.m_shared.m_name != name)
			{
				((Character)user).Message((MessageType)2, "$msg_wrongitem", 0, (Sprite)null);
				return false;
			}
			float value = Traverse.Create((object)__instance).Method("GetFuel", Array.Empty<object>()).GetValue<float>();
			if (value > (float)(__instance.m_maxFuel - 1))
			{
				((Character)user).Message((MessageType)2, "$msg_itsfull", 0, (Sprite)null);
				return false;
			}
			item = user.GetInventory().GetItem(name, -1, false);
			if (item == null)
			{
				if (flag)
				{
					return true;
				}
				((Character)user).Message((MessageType)2, "$msg_donthaveany " + name, 0, (Sprite)null);
				return false;
			}
			((Character)user).Message((MessageType)2, "$msg_added " + name, 0, (Sprite)null);
			int val = (int)((float)__instance.m_maxFuel - value);
			int num = 1;
			if (!flag)
			{
				num = Math.Min(item.m_stack, val);
			}
			user.GetInventory().RemoveItem(item, num);
			for (int i = 0; i < num; i++)
			{
				__instance.m_nview.InvokeRPC("AddFuel", Array.Empty<object>());
			}
			__result = true;
			return false;
		}

		public static void RPC_AddOre(Smelter instance, ZNetView m_nview, string name, int count)
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			if (m_nview.IsOwner() && Traverse.Create((object)instance).Method("IsItemAllowed", new object[1] { name }).GetValue<bool>())
			{
				int value = Traverse.Create((object)instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>();
				for (int i = 0; i < count; i++)
				{
					m_nview.GetZDO().Set($"item{value + i}", name);
				}
				m_nview.GetZDO().Set("queued", value + count);
				instance.m_oreAddedEffects.Create(((Component)instance).transform.position, ((Component)instance).transform.rotation, (Transform)null, 1f, -1);
				ZLog.Log((object)$"Added ore {name} * {count}");
			}
		}

		public static void RPC_AddFuel(Smelter instance, ZNetView m_nview, float count)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (m_nview.IsOwner())
			{
				float value = Traverse.Create((object)instance).Method("GetFuel", Array.Empty<object>()).GetValue<float>();
				m_nview.GetZDO().Set("fuel", value + count);
				instance.m_fuelAddedEffects.Create(((Component)instance).transform.position, ((Component)instance).transform.rotation, ((Component)instance).transform, 1f, -1);
				ZLog.Log((object)$"Added fuel * {count}");
			}
		}
	}
}

BepInEx/plugins/CookieMilk-MagicalMounts/MagicalMounts.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using CreatureManager;
using HarmonyLib;
using HarmonyLib.Public.Patching;
using IhvJoiNTPh9JvULZUA;
using ItemManager;
using JetBrains.Annotations;
using KeyManager;
using MagicalMounts;
using MagicalMounts.Patches;
using MagicalMounts.Utils;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Utils;
using MountManager;
using PieceManager;
using ServerSync;
using UnityEngine;
using UnityEngine.Diagnostics;
using UnityEngine.Events;
using UnityEngine.UI;
using sZnGYNh0aPguc4dKmU;

[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCompany("CookieMilk")]
[assembly: AssemblyFileVersion("1.5.9")]
[assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MagicalMounts")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyDescription("")]
[assembly: AssemblyProduct("MagicalMounts")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyConfiguration("")]
[assembly: CompilationRelaxations(8)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.9.0")]
[module: UnverifiableCode]
[module: <1a7616cd-2498-44e7-98af-17e20992c155>RefSafetyRules(11)]
internal class <Module>
{
	internal struct \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e
	{
		internal uint \u206f\u200b\u206c\u206c\u202a\u206a\u206f\u200e\u206e\u202e\u202b\u202c\u206b\u206c\u206b\u202a\u200b\u202b\u200b\u206a\u206c\u200b\u206d\u200b\u202c\u202d\u202b\u202a\u200f\u200d\u206a\u202c\u206f\u206c\u206d\u200f\u202d\u202b\u206d\u200d\u202e;

		private static object CustomizeDispatcher;

		internal void \u200b\u206e\u206e\u206f\u200b\u202b\u202b\u206f\u200b\u202e\u206f\u202e\u200d\u200c\u202d\u206a\u202d\u206a\u206c\u206b\u206c\u202e\u202c\u202c\u200d\u202c\u206f\u202b\u206d\u200d\u202b\u206f\u202d\u202a\u200c\u200b\u200d\u200f\u200e\u200d\u202e()
		{
			int num = 1;
			int num2 = num;
			while (true)
			{
				switch (num2)
				{
				default:
					return;
				case 1:
					\u206f\u200b\u206c\u206c\u202a\u206a\u206f\u200e\u206e\u202e\u202b\u202c\u206b\u206c\u206b\u202a\u200b\u202b\u200b\u206a\u206c\u200b\u206d\u200b\u202c\u202d\u202b\u202a\u200f\u200d\u206a\u202c\u206f\u206c\u206d\u200f\u202d\u202b\u206d\u200d\u202e = 1024u;
					num2 = 0;
					if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_c7121012affd45e483a6d38cab856e79 != 0)
					{
						num2 = 0;
					}
					break;
				case 0:
					return;
				}
			}
		}

		internal uint \u206c\u202b\u202c\u206e\u206b\u202c\u200d\u202e\u200b\u202b\u200f\u206e\u202a\u200c\u202a\u206a\u202d\u202e\u206c\u202a\u200f\u200c\u202e\u206f\u206a\u202a\u202d\u200c\u202c\u202e\u206a\u206d\u206a\u206a\u206d\u206c\u200d\u200f\u200b\u206a\u202e(\u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e rangeDecoder)
		{
			uint num = (rangeDecoder.\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e >> 11) * \u206f\u200b\u206c\u206c\u202a\u206a\u206f\u200e\u206e\u202e\u202b\u202c\u206b\u206c\u206b\u202a\u200b\u202b\u200b\u206a\u206c\u200b\u206d\u200b\u202c\u202d\u202b\u202a\u200f\u200d\u206a\u202c\u206f\u206c\u206d\u200f\u202d\u202b\u206d\u200d\u202e;
			while (true)
			{
				int num2 = 1982634378;
				while (true)
				{
					uint num3;
					switch ((num3 = (uint)num2 ^ 0x1EF0AC1Au) % 11)
					{
					case 2u:
						break;
					case 9u:
					{
						int num8;
						int num9;
						if (rangeDecoder.\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e >= num)
						{
							num8 = -131652879;
							num9 = num8;
						}
						else
						{
							num8 = -554382564;
							num9 = num8;
						}
						num2 = num8 ^ (int)(num3 * 228870667);
						continue;
					}
					case 4u:
					{
						\u206f\u200b\u206c\u206c\u202a\u206a\u206f\u200e\u206e\u202e\u202b\u202c\u206b\u206c\u206b\u202a\u200b\u202b\u200b\u206a\u206c\u200b\u206d\u200b\u202c\u202d\u202b\u202a\u200f\u200d\u206a\u202c\u206f\u206c\u206d\u200f\u202d\u202b\u206d\u200d\u202e += 2048 - \u206f\u200b\u206c\u206c\u202a\u206a\u206f\u200e\u206e\u202e\u202b\u202c\u206b\u206c\u206b\u202a\u200b\u202b\u200b\u206a\u206c\u200b\u206d\u200b\u202c\u202d\u202b\u202a\u200f\u200d\u206a\u202c\u206f\u206c\u206d\u200f\u202d\u202b\u206d\u200d\u202e >> 5;
						int num6;
						int num7;
						if (rangeDecoder.\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e >= 16777216)
						{
							num6 = 1420008454;
							num7 = num6;
						}
						else
						{
							num6 = 1159870819;
							num7 = num6;
						}
						num2 = num6 ^ (int)(num3 * 844019893);
						continue;
					}
					case 0u:
						rangeDecoder.\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e = num;
						num2 = (int)((num3 * 1765100055) ^ 0x56428835);
						continue;
					case 7u:
						rangeDecoder.\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e <<= 8;
						num2 = ((int)num3 * -1685485797) ^ -1717124660;
						continue;
					case 6u:
					{
						int num4;
						int num5;
						if (rangeDecoder.\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e >= 16777216)
						{
							num4 = 1538935088;
							num5 = num4;
						}
						else
						{
							num4 = 955073334;
							num5 = num4;
						}
						num2 = num4 ^ ((int)num3 * -1689772543);
						continue;
					}
					case 8u:
						rangeDecoder.\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e = (rangeDecoder.\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e << 8) | (byte)rangeDecoder.\u200c\u206e\u200c\u202d\u200e\u202c\u200d\u200b\u206c\u200b\u202c\u200f\u202c\u206c\u202b\u206c\u202a\u200d\u206e\u202b\u200e\u200b\u202b\u202a\u200c\u206f\u200f\u206d\u202d\u206c\u206c\u200b\u206e\u202e\u206c\u206c\u200c\u206d\u202a\u200c\u202e.ReadByte();
						num2 = (int)((num3 * 1120314251) ^ 0xAAAC5D3);
						continue;
					case 5u:
						rangeDecoder.\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e -= num;
						rangeDecoder.\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e -= num;
						\u206f\u200b\u206c\u206c\u202a\u206a\u206f\u200e\u206e\u202e\u202b\u202c\u206b\u206c\u206b\u202a\u200b\u202b\u200b\u206a\u206c\u200b\u206d\u200b\u202c\u202d\u202b\u202a\u200f\u200d\u206a\u202c\u206f\u206c\u206d\u200f\u202d\u202b\u206d\u200d\u202e -= \u206f\u200b\u206c\u206c\u202a\u206a\u206f\u200e\u206e\u202e\u202b\u202c\u206b\u206c\u206b\u202a\u200b\u202b\u200b\u206a\u206c\u200b\u206d\u200b\u202c\u202d\u202b\u202a\u200f\u200d\u206a\u202c\u206f\u206c\u206d\u200f\u202d\u202b\u206d\u200d\u202e >> 5;
						num2 = 1104766896;
						continue;
					case 10u:
						return 0u;
					case 3u:
						rangeDecoder.\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e = (rangeDecoder.\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e << 8) | (byte)rangeDecoder.\u200c\u206e\u200c\u202d\u200e\u202c\u200d\u200b\u206c\u200b\u202c\u200f\u202c\u206c\u202b\u206c\u202a\u200d\u206e\u202b\u200e\u200b\u202b\u202a\u200c\u206f\u200f\u206d\u202d\u206c\u206c\u200b\u206e\u202e\u206c\u206c\u200c\u206d\u202a\u200c\u202e.ReadByte();
						rangeDecoder.\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e <<= 8;
						num2 = (int)((num3 * 1263378250) ^ 0x40AB2E26);
						continue;
					default:
						return 1u;
					}
					break;
				}
			}
		}

		internal static bool RateDispatcher()
		{
			return CustomizeDispatcher == null;
		}

		internal static object SetDispatcher()
		{
			return CustomizeDispatcher;
		}
	}

	internal struct \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e
	{
		internal readonly \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] \u206c\u202e\u202c\u206f\u200c\u202a\u206f\u200d\u206c\u202e\u206f\u206d\u200e\u200c\u202e\u200b\u200c\u206c\u202c\u202d\u202b\u206e\u202e\u200f\u206f\u206e\u202a\u206d\u200b\u202c\u200e\u202b\u206e\u202e\u200f\u200d\u206e\u202a\u206f\u202d\u202e;

		internal readonly int \u206c\u202d\u200e\u202b\u200c\u206a\u206e\u202c\u200c\u202e\u200b\u200d\u202d\u200b\u206d\u200c\u206e\u206d\u206f\u206a\u200f\u202b\u200c\u206f\u200c\u202d\u202c\u200d\u206a\u202a\u202d\u200c\u202c\u206a\u206b\u206b\u200c\u206b\u206f\u202e;

		private static object LogoutDispatcher;

		internal \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e(int numBitLevels)
		{
			ErrorPage.CreateRecord();
			\u206c\u202d\u200e\u202b\u200c\u206a\u206e\u202c\u200c\u202e\u200b\u200d\u202d\u200b\u206d\u200c\u206e\u206d\u206f\u206a\u200f\u202b\u200c\u206f\u200c\u202d\u202c\u200d\u206a\u202a\u202d\u200c\u202c\u206a\u206b\u206b\u200c\u206b\u206f\u202e = numBitLevels;
			\u206c\u202e\u202c\u206f\u200c\u202a\u206f\u200d\u206c\u202e\u206f\u206d\u200e\u200c\u202e\u200b\u200c\u206c\u202c\u202d\u202b\u206e\u202e\u200f\u206f\u206e\u202a\u206d\u200b\u202c\u200e\u202b\u206e\u202e\u200f\u200d\u206e\u202a\u206f\u202d\u202e = new \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[1 << numBitLevels];
		}

		internal void \u202e\u200f\u206a\u202e\u202c\u200d\u200e\u206c\u202b\u200c\u206c\u202c\u202d\u206d\u206e\u200c\u200b\u202b\u206d\u202a\u202b\u202d\u200f\u206a\u202c\u206c\u200f\u202b\u202a\u200e\u202a\u202e\u202a\u200c\u206f\u202b\u202b\u200e\u200e\u206b\u202e()
		{
			uint num = 1u;
			while (true)
			{
				int num2 = -425928079;
				while (true)
				{
					uint num3;
					switch ((num3 = (uint)num2 ^ 0xDE5BA7DAu) % 6)
					{
					case 0u:
						break;
					default:
						return;
					case 1u:
						num++;
						num2 = (int)((num3 * 1616911531) ^ 0x52AE2D40);
						continue;
					case 4u:
						\u206c\u202e\u202c\u206f\u200c\u202a\u206f\u200d\u206c\u202e\u206f\u206d\u200e\u200c\u202e\u200b\u200c\u206c\u202c\u202d\u202b\u206e\u202e\u200f\u206f\u206e\u202a\u206d\u200b\u202c\u200e\u202b\u206e\u202e\u200f\u200d\u206e\u202a\u206f\u202d\u202e[num].\u200b\u206e\u206e\u206f\u200b\u202b\u202b\u206f\u200b\u202e\u206f\u202e\u200d\u200c\u202d\u206a\u202d\u206a\u206c\u206b\u206c\u202e\u202c\u202c\u200d\u202c\u206f\u202b\u206d\u200d\u202b\u206f\u202d\u202a\u200c\u200b\u200d\u200f\u200e\u200d\u202e();
						num2 = -422263285;
						continue;
					case 5u:
						num2 = ((int)num3 * -1292788813) ^ 0x66F9784A;
						continue;
					case 3u:
					{
						int num4;
						if (num >= 1 << \u206c\u202d\u200e\u202b\u200c\u206a\u206e\u202c\u200c\u202e\u200b\u200d\u202d\u200b\u206d\u200c\u206e\u206d\u206f\u206a\u200f\u202b\u200c\u206f\u200c\u202d\u202c\u200d\u206a\u202a\u202d\u200c\u202c\u206a\u206b\u206b\u200c\u206b\u206f\u202e)
						{
							num2 = -583424668;
							num4 = num2;
						}
						else
						{
							num2 = -730674050;
							num4 = num2;
						}
						continue;
					}
					case 2u:
						return;
					}
					break;
				}
			}
		}

		internal uint \u206f\u206e\u206c\u202a\u206c\u206a\u206f\u200f\u202a\u200e\u206f\u200d\u202c\u200d\u202c\u202a\u206a\u206f\u200e\u206e\u200d\u200c\u206f\u206b\u202b\u200c\u200d\u202c\u206f\u202c\u200d\u206d\u206a\u206a\u200c\u200f\u202d\u206b\u200f\u202d\u202e(\u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e rangeDecoder)
		{
			uint num = 1u;
			int num4 = default(int);
			while (true)
			{
				int num2 = 1548987092;
				while (true)
				{
					uint num3;
					switch ((num3 = (uint)num2 ^ 0x77506D8Du) % 6)
					{
					case 3u:
						break;
					case 0u:
						num = (num << 1) + \u206c\u202e\u202c\u206f\u200c\u202a\u206f\u200d\u206c\u202e\u206f\u206d\u200e\u200c\u202e\u200b\u200c\u206c\u202c\u202d\u202b\u206e\u202e\u200f\u206f\u206e\u202a\u206d\u200b\u202c\u200e\u202b\u206e\u202e\u200f\u200d\u206e\u202a\u206f\u202d\u202e[num].\u206c\u202b\u202c\u206e\u206b\u202c\u200d\u202e\u200b\u202b\u200f\u206e\u202a\u200c\u202a\u206a\u202d\u202e\u206c\u202a\u200f\u200c\u202e\u206f\u206a\u202a\u202d\u200c\u202c\u202e\u206a\u206d\u206a\u206a\u206d\u206c\u200d\u200f\u200b\u206a\u202e(rangeDecoder);
						num4--;
						num2 = 2033280880;
						continue;
					case 4u:
						num2 = (int)(num3 * 1761981580) ^ -916922360;
						continue;
					case 1u:
						num4 = \u206c\u202d\u200e\u202b\u200c\u206a\u206e\u202c\u200c\u202e\u200b\u200d\u202d\u200b\u206d\u200c\u206e\u206d\u206f\u206a\u200f\u202b\u200c\u206f\u200c\u202d\u202c\u200d\u206a\u202a\u202d\u200c\u202c\u206a\u206b\u206b\u200c\u206b\u206f\u202e;
						num2 = (int)((num3 * 1339658374) ^ 0x15C88A91);
						continue;
					case 5u:
					{
						int num5;
						if (num4 > 0)
						{
							num2 = 1949236773;
							num5 = num2;
						}
						else
						{
							num2 = 557911605;
							num5 = num2;
						}
						continue;
					}
					default:
						return num - (uint)(1 << \u206c\u202d\u200e\u202b\u200c\u206a\u206e\u202c\u200c\u202e\u200b\u200d\u202d\u200b\u206d\u200c\u206e\u206d\u206f\u206a\u200f\u202b\u200c\u206f\u200c\u202d\u202c\u200d\u206a\u202a\u202d\u200c\u202c\u206a\u206b\u206b\u200c\u206b\u206f\u202e);
					}
					break;
				}
			}
		}

		internal uint \u200b\u202d\u202b\u202e\u206b\u206e\u202d\u202e\u206e\u202d\u200f\u206a\u200f\u206e\u200b\u206c\u206f\u206d\u206d\u200c\u200e\u202c\u200d\u200d\u206f\u206d\u202e\u202d\u206e\u200b\u206d\u206e\u200c\u202c\u202b\u206c\u200d\u200c\u202c\u202e(\u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e rangeDecoder)
		{
			uint num = 1u;
			uint num5 = default(uint);
			uint num4 = default(uint);
			int num6 = default(int);
			while (true)
			{
				int num2 = 2005750615;
				while (true)
				{
					uint num3;
					switch ((num3 = (uint)num2 ^ 0xBFE2071u) % 8)
					{
					case 2u:
						break;
					case 5u:
						num5 = \u206c\u202e\u202c\u206f\u200c\u202a\u206f\u200d\u206c\u202e\u206f\u206d\u200e\u200c\u202e\u200b\u200c\u206c\u202c\u202d\u202b\u206e\u202e\u200f\u206f\u206e\u202a\u206d\u200b\u202c\u200e\u202b\u206e\u202e\u200f\u200d\u206e\u202a\u206f\u202d\u202e[num].\u206c\u202b\u202c\u206e\u206b\u202c\u200d\u202e\u200b\u202b\u200f\u206e\u202a\u200c\u202a\u206a\u202d\u202e\u206c\u202a\u200f\u200c\u202e\u206f\u206a\u202a\u202d\u200c\u202c\u202e\u206a\u206d\u206a\u206a\u206d\u206c\u200d\u200f\u200b\u206a\u202e(rangeDecoder);
						num <<= 1;
						num2 = 348215602;
						continue;
					case 3u:
						num += num5;
						num2 = ((int)num3 * -313819568) ^ -984204523;
						continue;
					case 6u:
						num4 = 0u;
						num6 = 0;
						num2 = (int)((num3 * 1044902174) ^ 0x23071FA);
						continue;
					case 1u:
					{
						int num7;
						if (num6 < \u206c\u202d\u200e\u202b\u200c\u206a\u206e\u202c\u200c\u202e\u200b\u200d\u202d\u200b\u206d\u200c\u206e\u206d\u206f\u206a\u200f\u202b\u200c\u206f\u200c\u202d\u202c\u200d\u206a\u202a\u202d\u200c\u202c\u206a\u206b\u206b\u200c\u206b\u206f\u202e)
						{
							num2 = 1609631412;
							num7 = num2;
						}
						else
						{
							num2 = 1683095593;
							num7 = num2;
						}
						continue;
					}
					case 7u:
						num2 = (int)(num3 * 1994434) ^ -751110986;
						continue;
					case 4u:
						num4 |= num5 << num6;
						num6++;
						num2 = (int)((num3 * 380029719) ^ 0x2B09D5C4);
						continue;
					default:
						return num4;
					}
					break;
				}
			}
		}

		internal static uint \u200d\u200f\u206a\u202e\u202a\u200f\u200f\u206b\u200e\u206e\u206a\u206c\u206b\u202a\u206a\u200e\u200f\u200c\u206f\u206d\u206b\u200e\u206e\u200b\u200e\u200b\u200d\u200e\u202e\u200f\u202a\u200c\u206e\u202d\u202b\u200b\u200e\u200d\u200f\u200d\u202e(\u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] Models, uint startIndex, \u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e rangeDecoder, int NumBitLevels)
		{
			uint num = 1u;
			uint num4 = default(uint);
			int num6 = default(int);
			uint num5 = default(uint);
			while (true)
			{
				int num2 = 1509237192;
				while (true)
				{
					uint num3;
					switch ((num3 = (uint)num2 ^ 0x2E266028u) % 9)
					{
					case 2u:
						break;
					case 1u:
						num4 = 0u;
						num6 = 0;
						num2 = ((int)num3 * -155155782) ^ -285141854;
						continue;
					case 8u:
						num += num5;
						num2 = ((int)num3 * -591101799) ^ -226505767;
						continue;
					case 3u:
						num5 = Models[startIndex + num].\u206c\u202b\u202c\u206e\u206b\u202c\u200d\u202e\u200b\u202b\u200f\u206e\u202a\u200c\u202a\u206a\u202d\u202e\u206c\u202a\u200f\u200c\u202e\u206f\u206a\u202a\u202d\u200c\u202c\u202e\u206a\u206d\u206a\u206a\u206d\u206c\u200d\u200f\u200b\u206a\u202e(rangeDecoder);
						num2 = 563323635;
						continue;
					case 7u:
					{
						int num7;
						if (num6 < NumBitLevels)
						{
							num2 = 752210150;
							num7 = num2;
						}
						else
						{
							num2 = 1591216614;
							num7 = num2;
						}
						continue;
					}
					case 0u:
						num <<= 1;
						num2 = (int)(num3 * 608773489) ^ -493030588;
						continue;
					case 4u:
						num6++;
						num2 = (int)((num3 * 928807430) ^ 0x53F5FC7A);
						continue;
					case 6u:
						num4 |= num5 << num6;
						num2 = ((int)num3 * -576342969) ^ 0x6D9F0F7E;
						continue;
					default:
						return num4;
					}
					break;
				}
			}
		}

		internal static bool GetDispatcher()
		{
			return LogoutDispatcher == null;
		}

		internal static object SelectDispatcher()
		{
			return LogoutDispatcher;
		}
	}

	internal class \u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e
	{
		internal uint \u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e;

		internal uint \u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e;

		internal Stream \u200c\u206e\u200c\u202d\u200e\u202c\u200d\u200b\u206c\u200b\u202c\u200f\u202c\u206c\u202b\u206c\u202a\u200d\u206e\u202b\u200e\u200b\u202b\u202a\u200c\u206f\u200f\u206d\u202d\u206c\u206c\u200b\u206e\u202e\u206c\u206c\u200c\u206d\u202a\u200c\u202e;

		internal static \u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e InsertDispatcher;

		internal void \u200f\u206a\u206b\u206d\u200f\u202c\u200e\u200b\u202d\u206b\u202e\u202e\u206a\u206b\u200b\u200d\u202a\u202d\u206b\u200c\u200e\u200c\u202d\u202b\u200b\u202b\u202c\u200b\u206e\u206e\u200c\u200c\u206d\u206d\u206a\u200e\u200b\u202c\u202b\u202e(Stream stream)
		{
			\u200c\u206e\u200c\u202d\u200e\u202c\u200d\u200b\u206c\u200b\u202c\u200f\u202c\u206c\u202b\u206c\u202a\u200d\u206e\u202b\u200e\u200b\u202b\u202a\u200c\u206f\u200f\u206d\u202d\u206c\u206c\u200b\u206e\u202e\u206c\u206c\u200c\u206d\u202a\u200c\u202e = stream;
			int num3 = default(int);
			while (true)
			{
				int num = 1951225852;
				while (true)
				{
					uint num2;
					switch ((num2 = (uint)num ^ 0x56040337u) % 7)
					{
					case 0u:
						break;
					default:
						return;
					case 4u:
						num3++;
						num = (int)((num2 * 1306301884) ^ 0x6A59743F);
						continue;
					case 2u:
						num = (int)((num2 * 971908070) ^ 0x23F412C7);
						continue;
					case 5u:
						\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e = 0u;
						\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e = uint.MaxValue;
						num3 = 0;
						num = (int)(num2 * 870839259) ^ -537125074;
						continue;
					case 1u:
					{
						int num4;
						if (num3 < 5)
						{
							num = 1577588897;
							num4 = num;
						}
						else
						{
							num = 186248279;
							num4 = num;
						}
						continue;
					}
					case 3u:
						\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e = (\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e << 8) | (byte)\u200c\u206e\u200c\u202d\u200e\u202c\u200d\u200b\u206c\u200b\u202c\u200f\u202c\u206c\u202b\u206c\u202a\u200d\u206e\u202b\u200e\u200b\u202b\u202a\u200c\u206f\u200f\u206d\u202d\u206c\u206c\u200b\u206e\u202e\u206c\u206c\u200c\u206d\u202a\u200c\u202e.ReadByte();
						num = 1162101789;
						continue;
					case 6u:
						return;
					}
					break;
				}
			}
		}

		internal void \u206c\u202e\u206b\u206e\u202d\u206e\u206f\u206a\u200c\u200d\u200c\u206f\u206a\u206e\u200e\u202a\u206b\u200e\u206b\u202a\u206a\u200f\u202c\u206c\u206b\u206c\u202c\u202d\u200e\u202d\u206d\u200e\u206f\u206c\u206f\u200d\u206f\u202c\u206e\u206b\u202e()
		{
			int num = 1;
			int num2 = num;
			while (true)
			{
				switch (num2)
				{
				default:
					return;
				case 0:
					return;
				case 1:
					\u200c\u206e\u200c\u202d\u200e\u202c\u200d\u200b\u206c\u200b\u202c\u200f\u202c\u206c\u202b\u206c\u202a\u200d\u206e\u202b\u200e\u200b\u202b\u202a\u200c\u206f\u200f\u206d\u202d\u206c\u206c\u200b\u206e\u202e\u206c\u206c\u200c\u206d\u202a\u200c\u202e = null;
					num2 = 0;
					if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_dd188bd72cff464cacdfe747c5ccfe83 == 0)
					{
						num2 = 0;
					}
					break;
				}
			}
		}

		internal void \u206e\u206b\u206c\u206b\u200c\u200e\u206e\u200d\u202c\u200c\u202e\u202c\u206c\u200b\u202a\u202e\u206c\u200b\u206e\u202b\u200f\u200e\u206e\u206c\u200e\u200d\u206d\u202d\u206b\u200e\u206c\u206e\u202c\u202e\u206f\u206d\u202e\u202e\u206b\u202e()
		{
			while (true)
			{
				int num;
				int num2;
				if (\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e >= 16777216)
				{
					num = 1989391971;
					num2 = num;
				}
				else
				{
					num = 1022750045;
					num2 = num;
				}
				while (true)
				{
					uint num3;
					switch ((num3 = (uint)num ^ 0x9214E7Cu) % 5)
					{
					case 3u:
						num = 1022750045;
						continue;
					default:
						return;
					case 1u:
						\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e = (\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e << 8) | (byte)\u200c\u206e\u200c\u202d\u200e\u202c\u200d\u200b\u206c\u200b\u202c\u200f\u202c\u206c\u202b\u206c\u202a\u200d\u206e\u202b\u200e\u200b\u202b\u202a\u200c\u206f\u200f\u206d\u202d\u206c\u206c\u200b\u206e\u202e\u206c\u206c\u200c\u206d\u202a\u200c\u202e.ReadByte();
						num = 1303420475;
						continue;
					case 2u:
						\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e <<= 8;
						num = (int)(num3 * 170943899) ^ -2136751005;
						continue;
					case 0u:
						break;
					case 4u:
						return;
					}
					break;
				}
			}
		}

		internal uint \u202b\u206c\u202b\u200c\u200f\u200d\u202c\u206b\u200b\u200b\u202b\u202d\u202c\u206f\u200e\u206f\u206d\u206d\u206a\u202b\u202b\u206c\u206e\u200d\u202e\u202e\u206e\u202b\u202e\u200d\u202c\u200c\u202c\u200d\u200d\u206f\u206c\u202a\u200d\u202e(int numTotalBits)
		{
			uint num = \u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e;
			int num5 = default(int);
			uint num4 = default(uint);
			uint num7 = default(uint);
			uint num6 = default(uint);
			while (true)
			{
				int num2 = 936485041;
				while (true)
				{
					uint num3;
					switch ((num3 = (uint)num2 ^ 0x87F2113u) % 15)
					{
					case 2u:
						break;
					case 4u:
						num5--;
						num2 = 1297922704;
						continue;
					case 8u:
						num4 = (num4 << 1) | (1 - num7);
						num2 = (int)(num3 * 1495760711) ^ -1146683380;
						continue;
					case 0u:
					{
						int num10;
						if (num5 <= 0)
						{
							num2 = 523678502;
							num10 = num2;
						}
						else
						{
							num2 = 672421521;
							num10 = num2;
						}
						continue;
					}
					case 10u:
						\u206c\u206f\u206b\u206a\u200f\u200b\u202b\u200e\u202c\u206f\u206e\u200f\u202c\u206b\u206d\u206b\u206e\u200e\u200e\u202b\u206b\u202d\u200e\u202e\u206c\u200b\u206c\u202e\u202c\u200f\u200f\u202a\u200c\u202c\u200c\u202a\u200b\u200b\u202d\u202b\u202e = num;
						\u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e = num6;
						num2 = (int)((num3 * 412195849) ^ 0x46BC73E1);
						continue;
					case 9u:
						num2 = (int)(num3 * 1090376064) ^ -127491056;
						continue;
					case 5u:
					{
						int num8;
						int num9;
						if (num < 16777216)
						{
							num8 = -1142865957;
							num9 = num8;
						}
						else
						{
							num8 = -1893062968;
							num9 = num8;
						}
						num2 = num8 ^ ((int)num3 * -531270862);
						continue;
					}
					case 6u:
						num4 = 0u;
						num2 = (int)(num3 * 1990134535) ^ -1127784959;
						continue;
					case 14u:
						num7 = num6 - num >> 31;
						num2 = ((int)num3 * -1098822989) ^ -1807919345;
						continue;
					case 11u:
						num6 -= num & (num7 - 1);
						num2 = ((int)num3 * -431701353) ^ 0x30D309E3;
						continue;
					case 7u:
						num6 = (num6 << 8) | (byte)\u200c\u206e\u200c\u202d\u200e\u202c\u200d\u200b\u206c\u200b\u202c\u200f\u202c\u206c\u202b\u206c\u202a\u200d\u206e\u202b\u200e\u200b\u202b\u202a\u200c\u206f\u200f\u206d\u202d\u206c\u206c\u200b\u206e\u202e\u206c\u206c\u200c\u206d\u202a\u200c\u202e.ReadByte();
						num <<= 8;
						num2 = ((int)num3 * -880045928) ^ 0x67749F5A;
						continue;
					case 13u:
						num >>= 1;
						num2 = 523516125;
						continue;
					case 3u:
						num6 = \u202d\u206b\u202c\u200d\u206b\u206a\u200d\u206f\u206c\u206d\u206b\u206a\u202a\u206c\u202b\u200c\u200e\u200f\u202c\u200c\u206b\u200d\u206d\u206f\u200f\u202c\u206e\u200d\u200d\u206d\u206b\u206b\u202e\u200b\u202c\u202a\u206f\u206b\u202a\u202e;
						num2 = ((int)num3 * -687667531) ^ -597664280;
						continue;
					case 1u:
						num5 = numTotalBits;
						num2 = (int)((num3 * 1016037944) ^ 0x23A82494);
						continue;
					default:
						return num4;
					}
					break;
				}
			}
		}

		internal \u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e()
		{
			ErrorPage.CreateRecord();
			base..ctor();
			int num = 0;
			if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_0f361b4cebb447cf8ed27c1a7c0fa8f0 == 0)
			{
				num = 0;
			}
			switch (num)
			{
			case 0:
				break;
			}
		}

		internal static bool CalculateDispatcher()
		{
			return InsertDispatcher == null;
		}

		internal static \u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e UpdateDispatcher()
		{
			return InsertDispatcher;
		}
	}

	internal class \u200d\u206f\u200b\u202b\u202e\u200c\u200f\u202b\u202c\u202e\u206e\u200c\u202d\u202d\u200e\u200d\u206b\u206e\u206b\u200f\u206a\u202a\u206d\u206d\u200d\u206e\u206a\u200c\u206c\u202b\u200b\u206e\u202d\u202c\u202b\u202a\u200e\u200c\u206c\u206f\u202e
	{
		internal class \u202e\u200f\u202b\u206a\u206a\u200d\u206e\u206d\u200e\u202e\u200e\u200f\u202b\u202b\u202b\u206a\u200f\u202d\u202b\u206e\u206b\u202d\u202c\u206c\u206f\u202e\u206e\u202a\u206d\u202e\u206e\u202c\u206b\u202a\u200b\u202c\u202e\u200f\u200f\u202c\u202e
		{
			internal readonly \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e[] \u206d\u202d\u202e\u206b\u206f\u202e\u200b\u202c\u206b\u206a\u202e\u206e\u202d\u206b\u206d\u206d\u206d\u206d\u206d\u202b\u202d\u202a\u200d\u200f\u206e\u200b\u200e\u206f\u202e\u200b\u206a\u206d\u206e\u202b\u206e\u206e\u200d\u200f\u206b\u202d\u202e;

			internal readonly \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e[] \u206c\u202a\u200c\u202b\u206e\u200c\u206e\u206e\u200b\u202b\u200d\u200e\u200f\u200f\u202e\u206a\u206e\u206c\u200b\u202a\u206a\u206b\u202a\u206d\u200b\u200e\u206e\u206e\u202a\u206e\u202d\u200c\u206b\u200b\u206e\u202e\u200e\u206d\u202b\u206b\u202e;

			internal \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e \u202c\u200d\u200e\u206a\u206f\u200f\u200d\u202b\u200c\u202e\u200d\u206b\u200f\u200e\u202b\u200e\u202c\u206f\u202d\u202b\u202c\u206d\u200d\u206e\u202a\u206f\u202d\u206b\u202b\u200d\u206d\u202a\u202a\u200e\u200b\u206f\u200b\u202b\u202e\u206f\u202e;

			internal \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e \u202a\u202c\u206b\u202c\u202d\u202a\u202a\u206f\u206b\u200f\u206d\u202a\u202e\u202b\u206e\u206f\u206d\u202a\u206b\u202e\u200b\u206f\u200b\u206e\u202d\u202a\u206b\u202b\u202d\u200f\u202a\u206b\u200f\u206d\u202a\u202c\u202a\u206a\u200f\u200f\u202e;

			internal \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e \u206b\u206b\u206c\u202d\u206a\u206b\u206b\u202e\u202e\u200d\u206a\u200f\u202d\u200b\u202b\u202b\u202a\u200f\u206a\u206d\u200f\u202c\u206f\u206e\u202e\u200e\u200c\u206a\u200b\u206f\u200c\u202e\u200f\u202e\u200f\u200f\u202c\u206d\u202a\u202e;

			internal uint \u200e\u200f\u206f\u206f\u202a\u206e\u200e\u200b\u206b\u206a\u202b\u206d\u202d\u202c\u200e\u202a\u202a\u202c\u200d\u202e\u202c\u202c\u206f\u200c\u206e\u206f\u202d\u206b\u206d\u200c\u202b\u200d\u206a\u206e\u206a\u202d\u202b\u200f\u206e\u200f\u202e;

			internal static \u202e\u200f\u202b\u206a\u206a\u200d\u206e\u206d\u200e\u202e\u200e\u200f\u202b\u202b\u202b\u206a\u200f\u202d\u202b\u206e\u206b\u202d\u202c\u206c\u206f\u202e\u206e\u202a\u206d\u202e\u206e\u202c\u206b\u202a\u200b\u202c\u202e\u200f\u200f\u202c\u202e DefineDispatcher;

			internal void \u202a\u206d\u200c\u206d\u206b\u200c\u200d\u202d\u200d\u200d\u202b\u200e\u200b\u206b\u206d\u206c\u206e\u202d\u200c\u202c\u200c\u202c\u200b\u206b\u200b\u206f\u206e\u200f\u206c\u200d\u202a\u200b\u206c\u200b\u202e\u202b\u206c\u206b\u202e\u202b\u202e(uint numPosStates)
			{
				uint num = \u200e\u200f\u206f\u206f\u202a\u206e\u200e\u200b\u206b\u206a\u202b\u206d\u202d\u202c\u200e\u202a\u202a\u202c\u200d\u202e\u202c\u202c\u206f\u200c\u206e\u206f\u202d\u206b\u206d\u200c\u202b\u200d\u206a\u206e\u206a\u202d\u202b\u200f\u206e\u200f\u202e;
				while (true)
				{
					int num2 = -2085433351;
					while (true)
					{
						uint num3;
						switch ((num3 = (uint)num2 ^ 0x84A7138Bu) % 8)
						{
						case 6u:
							break;
						default:
							return;
						case 1u:
						{
							int num4;
							if (num >= numPosStates)
							{
								num2 = -121616349;
								num4 = num2;
							}
							else
							{
								num2 = -1489368858;
								num4 = num2;
							}
							continue;
						}
						case 4u:
							\u206c\u202a\u200c\u202b\u206e\u200c\u206e\u206e\u200b\u202b\u200d\u200e\u200f\u200f\u202e\u206a\u206e\u206c\u200b\u202a\u206a\u206b\u202a\u206d\u200b\u200e\u206e\u206e\u202a\u206e\u202d\u200c\u206b\u200b\u206e\u202e\u200e\u206d\u202b\u206b\u202e[num] = new \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e(3);
							num2 = ((int)num3 * -114202490) ^ 0x300FE784;
							continue;
						case 0u:
							\u200e\u200f\u206f\u206f\u202a\u206e\u200e\u200b\u206b\u206a\u202b\u206d\u202d\u202c\u200e\u202a\u202a\u202c\u200d\u202e\u202c\u202c\u206f\u200c\u206e\u206f\u202d\u206b\u206d\u200c\u202b\u200d\u206a\u206e\u206a\u202d\u202b\u200f\u206e\u200f\u202e = numPosStates;
							num2 = (int)((num3 * 1716884308) ^ 0x5B1186E0);
							continue;
						case 7u:
							num++;
							num2 = ((int)num3 * -1640465441) ^ -806469749;
							continue;
						case 2u:
							num2 = ((int)num3 * -1337231334) ^ 0x215C5786;
							continue;
						case 5u:
							\u206d\u202d\u202e\u206b\u206f\u202e\u200b\u202c\u206b\u206a\u202e\u206e\u202d\u206b\u206d\u206d\u206d\u206d\u206d\u202b\u202d\u202a\u200d\u200f\u206e\u200b\u200e\u206f\u202e\u200b\u206a\u206d\u206e\u202b\u206e\u206e\u200d\u200f\u206b\u202d\u202e[num] = new \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e(3);
							num2 = -251269273;
							continue;
						case 3u:
							return;
						}
						break;
					}
				}
			}

			internal void \u202b\u206b\u202d\u206c\u206e\u206c\u202e\u206b\u206b\u206a\u202b\u202e\u200f\u206e\u206e\u206d\u200d\u206f\u200c\u202e\u200f\u202b\u206f\u206a\u206c\u200c\u202e\u202d\u206c\u202d\u200e\u202c\u206c\u206f\u200b\u206e\u206e\u200f\u206b\u206a\u202e()
			{
				\u202c\u200d\u200e\u206a\u206f\u200f\u200d\u202b\u200c\u202e\u200d\u206b\u200f\u200e\u202b\u200e\u202c\u206f\u202d\u202b\u202c\u206d\u200d\u206e\u202a\u206f\u202d\u206b\u202b\u200d\u206d\u202a\u202a\u200e\u200b\u206f\u200b\u202b\u202e\u206f\u202e.\u200b\u206e\u206e\u206f\u200b\u202b\u202b\u206f\u200b\u202e\u206f\u202e\u200d\u200c\u202d\u206a\u202d\u206a\u206c\u206b\u206c\u202e\u202c\u202c\u200d\u202c\u206f\u202b\u206d\u200d\u202b\u206f\u202d\u202a\u200c\u200b\u200d\u200f\u200e\u200d\u202e();
				uint num3 = default(uint);
				while (true)
				{
					int num = -3054931;
					while (true)
					{
						uint num2;
						switch ((num2 = (uint)num ^ 0xA4DB6829u) % 7)
						{
						case 0u:
							break;
						case 2u:
							\u206c\u202a\u200c\u202b\u206e\u200c\u206e\u206e\u200b\u202b\u200d\u200e\u200f\u200f\u202e\u206a\u206e\u206c\u200b\u202a\u206a\u206b\u202a\u206d\u200b\u200e\u206e\u206e\u202a\u206e\u202d\u200c\u206b\u200b\u206e\u202e\u200e\u206d\u202b\u206b\u202e[num3].\u202e\u200f\u206a\u202e\u202c\u200d\u200e\u206c\u202b\u200c\u206c\u202c\u202d\u206d\u206e\u200c\u200b\u202b\u206d\u202a\u202b\u202d\u200f\u206a\u202c\u206c\u200f\u202b\u202a\u200e\u202a\u202e\u202a\u200c\u206f\u202b\u202b\u200e\u200e\u206b\u202e();
							num3++;
							num = (int)(num2 * 662375142) ^ -768578202;
							continue;
						case 4u:
							\u206d\u202d\u202e\u206b\u206f\u202e\u200b\u202c\u206b\u206a\u202e\u206e\u202d\u206b\u206d\u206d\u206d\u206d\u206d\u202b\u202d\u202a\u200d\u200f\u206e\u200b\u200e\u206f\u202e\u200b\u206a\u206d\u206e\u202b\u206e\u206e\u200d\u200f\u206b\u202d\u202e[num3].\u202e\u200f\u206a\u202e\u202c\u200d\u200e\u206c\u202b\u200c\u206c\u202c\u202d\u206d\u206e\u200c\u200b\u202b\u206d\u202a\u202b\u202d\u200f\u206a\u202c\u206c\u200f\u202b\u202a\u200e\u202a\u202e\u202a\u200c\u206f\u202b\u202b\u200e\u200e\u206b\u202e();
							num = -1822069461;
							continue;
						case 5u:
						{
							int num4;
							if (num3 >= \u200e\u200f\u206f\u206f\u202a\u206e\u200e\u200b\u206b\u206a\u202b\u206d\u202d\u202c\u200e\u202a\u202a\u202c\u200d\u202e\u202c\u202c\u206f\u200c\u206e\u206f\u202d\u206b\u206d\u200c\u202b\u200d\u206a\u206e\u206a\u202d\u202b\u200f\u206e\u200f\u202e)
							{
								num = -1583588073;
								num4 = num;
							}
							else
							{
								num = -1109614776;
								num4 = num;
							}
							continue;
						}
						case 3u:
							num3 = 0u;
							num = (int)((num2 * 1042103313) ^ 0x2732271E);
							continue;
						case 6u:
							num = ((int)num2 * -794287009) ^ 0x1E1A8787;
							continue;
						default:
							\u202a\u202c\u206b\u202c\u202d\u202a\u202a\u206f\u206b\u200f\u206d\u202a\u202e\u202b\u206e\u206f\u206d\u202a\u206b\u202e\u200b\u206f\u200b\u206e\u202d\u202a\u206b\u202b\u202d\u200f\u202a\u206b\u200f\u206d\u202a\u202c\u202a\u206a\u200f\u200f\u202e.\u200b\u206e\u206e\u206f\u200b\u202b\u202b\u206f\u200b\u202e\u206f\u202e\u200d\u200c\u202d\u206a\u202d\u206a\u206c\u206b\u206c\u202e\u202c\u202c\u200d\u202c\u206f\u202b\u206d\u200d\u202b\u206f\u202d\u202a\u200c\u200b\u200d\u200f\u200e\u200d\u202e();
							\u206b\u206b\u206c\u202d\u206a\u206b\u206b\u202e\u202e\u200d\u206a\u200f\u202d\u200b\u202b\u202b\u202a\u200f\u206a\u206d\u200f\u202c\u206f\u206e\u202e\u200e\u200c\u206a\u200b\u206f\u200c\u202e\u200f\u202e\u200f\u200f\u202c\u206d\u202a\u202e.\u202e\u200f\u206a\u202e\u202c\u200d\u200e\u206c\u202b\u200c\u206c\u202c\u202d\u206d\u206e\u200c\u200b\u202b\u206d\u202a\u202b\u202d\u200f\u206a\u202c\u206c\u200f\u202b\u202a\u200e\u202a\u202e\u202a\u200c\u206f\u202b\u202b\u200e\u200e\u206b\u202e();
							return;
						}
						break;
					}
				}
			}

			internal uint \u202b\u200c\u206f\u200b\u202b\u202b\u202b\u202d\u206f\u200e\u202b\u200c\u202d\u202c\u206a\u206b\u206b\u202a\u200f\u200d\u206a\u206d\u202b\u206b\u206b\u202c\u202a\u206d\u202b\u200c\u200b\u200b\u202c\u202d\u200f\u206b\u202a\u200d\u200e\u206f\u202e(\u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e rangeDecoder, uint posState)
			{
				if (\u202c\u200d\u200e\u206a\u206f\u200f\u200d\u202b\u200c\u202e\u200d\u206b\u200f\u200e\u202b\u200e\u202c\u206f\u202d\u202b\u202c\u206d\u200d\u206e\u202a\u206f\u202d\u206b\u202b\u200d\u206d\u202a\u202a\u200e\u200b\u206f\u200b\u202b\u202e\u206f\u202e.\u206c\u202b\u202c\u206e\u206b\u202c\u200d\u202e\u200b\u202b\u200f\u206e\u202a\u200c\u202a\u206a\u202d\u202e\u206c\u202a\u200f\u200c\u202e\u206f\u206a\u202a\u202d\u200c\u202c\u202e\u206a\u206d\u206a\u206a\u206d\u206c\u200d\u200f\u200b\u206a\u202e(rangeDecoder) == 0)
				{
					goto IL_0011;
				}
				goto IL_008a;
				IL_008a:
				uint num = 8u;
				int num2;
				int num3;
				if (\u202a\u202c\u206b\u202c\u202d\u202a\u202a\u206f\u206b\u200f\u206d\u202a\u202e\u202b\u206e\u206f\u206d\u202a\u206b\u202e\u200b\u206f\u200b\u206e\u202d\u202a\u206b\u202b\u202d\u200f\u202a\u206b\u200f\u206d\u202a\u202c\u202a\u206a\u200f\u200f\u202e.\u206c\u202b\u202c\u206e\u206b\u202c\u200d\u202e\u200b\u202b\u200f\u206e\u202a\u200c\u202a\u206a\u202d\u202e\u206c\u202a\u200f\u200c\u202e\u206f\u206a\u202a\u202d\u200c\u202c\u202e\u206a\u206d\u206a\u206a\u206d\u206c\u200d\u200f\u200b\u206a\u202e(rangeDecoder) != 0)
				{
					num2 = -614839431;
					num3 = num2;
				}
				else
				{
					num2 = -1013988543;
					num3 = num2;
				}
				goto IL_0016;
				IL_0016:
				while (true)
				{
					uint num4;
					switch ((num4 = (uint)num2 ^ 0xDF6F1EABu) % 6)
					{
					case 3u:
						break;
					case 1u:
						return \u206d\u202d\u202e\u206b\u206f\u202e\u200b\u202c\u206b\u206a\u202e\u206e\u202d\u206b\u206d\u206d\u206d\u206d\u206d\u202b\u202d\u202a\u200d\u200f\u206e\u200b\u200e\u206f\u202e\u200b\u206a\u206d\u206e\u202b\u206e\u206e\u200d\u200f\u206b\u202d\u202e[posState].\u206f\u206e\u206c\u202a\u206c\u206a\u206f\u200f\u202a\u200e\u206f\u200d\u202c\u200d\u202c\u202a\u206a\u206f\u200e\u206e\u200d\u200c\u206f\u206b\u202b\u200c\u200d\u202c\u206f\u202c\u200d\u206d\u206a\u206a\u200c\u200f\u202d\u206b\u200f\u202d\u202e(rangeDecoder);
					case 4u:
						num += 8;
						num += \u206b\u206b\u206c\u202d\u206a\u206b\u206b\u202e\u202e\u200d\u206a\u200f\u202d\u200b\u202b\u202b\u202a\u200f\u206a\u206d\u200f\u202c\u206f\u206e\u202e\u200e\u200c\u206a\u200b\u206f\u200c\u202e\u200f\u202e\u200f\u200f\u202c\u206d\u202a\u202e.\u206f\u206e\u206c\u202a\u206c\u206a\u206f\u200f\u202a\u200e\u206f\u200d\u202c\u200d\u202c\u202a\u206a\u206f\u200e\u206e\u200d\u200c\u206f\u206b\u202b\u200c\u200d\u202c\u206f\u202c\u200d\u206d\u206a\u206a\u200c\u200f\u202d\u206b\u200f\u202d\u202e(rangeDecoder);
						num2 = -577238210;
						continue;
					case 0u:
						goto IL_008a;
					case 2u:
						num += \u206c\u202a\u200c\u202b\u206e\u200c\u206e\u206e\u200b\u202b\u200d\u200e\u200f\u200f\u202e\u206a\u206e\u206c\u200b\u202a\u206a\u206b\u202a\u206d\u200b\u200e\u206e\u206e\u202a\u206e\u202d\u200c\u206b\u200b\u206e\u202e\u200e\u206d\u202b\u206b\u202e[posState].\u206f\u206e\u206c\u202a\u206c\u206a\u206f\u200f\u202a\u200e\u206f\u200d\u202c\u200d\u202c\u202a\u206a\u206f\u200e\u206e\u200d\u200c\u206f\u206b\u202b\u200c\u200d\u202c\u206f\u202c\u200d\u206d\u206a\u206a\u200c\u200f\u202d\u206b\u200f\u202d\u202e(rangeDecoder);
						num2 = ((int)num4 * -1131257415) ^ -1483603164;
						continue;
					default:
						return num;
					}
					break;
				}
				goto IL_0011;
				IL_0011:
				num2 = -1886099898;
				goto IL_0016;
			}

			internal \u202e\u200f\u202b\u206a\u206a\u200d\u206e\u206d\u200e\u202e\u200e\u200f\u202b\u202b\u202b\u206a\u200f\u202d\u202b\u206e\u206b\u202d\u202c\u206c\u206f\u202e\u206e\u202a\u206d\u202e\u206e\u202c\u206b\u202a\u200b\u202c\u202e\u200f\u200f\u202c\u202e()
			{
				ErrorPage.CreateRecord();
				\u206d\u202d\u202e\u206b\u206f\u202e\u200b\u202c\u206b\u206a\u202e\u206e\u202d\u206b\u206d\u206d\u206d\u206d\u206d\u202b\u202d\u202a\u200d\u200f\u206e\u200b\u200e\u206f\u202e\u200b\u206a\u206d\u206e\u202b\u206e\u206e\u200d\u200f\u206b\u202d\u202e = new \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e[16];
				\u206c\u202a\u200c\u202b\u206e\u200c\u206e\u206e\u200b\u202b\u200d\u200e\u200f\u200f\u202e\u206a\u206e\u206c\u200b\u202a\u206a\u206b\u202a\u206d\u200b\u200e\u206e\u206e\u202a\u206e\u202d\u200c\u206b\u200b\u206e\u202e\u200e\u206d\u202b\u206b\u202e = new \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e[16];
				\u206b\u206b\u206c\u202d\u206a\u206b\u206b\u202e\u202e\u200d\u206a\u200f\u202d\u200b\u202b\u202b\u202a\u200f\u206a\u206d\u200f\u202c\u206f\u206e\u202e\u200e\u200c\u206a\u200b\u206f\u200c\u202e\u200f\u202e\u200f\u200f\u202c\u206d\u202a\u202e = new \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e(8);
				base..ctor();
				int num = 0;
				if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_c6a7be3aacf2492a9a5894f3a5573481 != 0)
				{
					num = 0;
				}
				switch (num)
				{
				case 0:
					break;
				}
			}

			internal static bool AssetDispatcher()
			{
				return DefineDispatcher == null;
			}

			internal static \u202e\u200f\u202b\u206a\u206a\u200d\u206e\u206d\u200e\u202e\u200e\u200f\u202b\u202b\u202b\u206a\u200f\u202d\u202b\u206e\u206b\u202d\u202c\u206c\u206f\u202e\u206e\u202a\u206d\u202e\u206e\u202c\u206b\u202a\u200b\u202c\u202e\u200f\u200f\u202c\u202e ExcludeDispatcher()
			{
				return DefineDispatcher;
			}
		}

		internal class \u206c\u202a\u206e\u202a\u206f\u202a\u206a\u200b\u200e\u206f\u202d\u200b\u206e\u202c\u200e\u200e\u206b\u202d\u200f\u206e\u202e\u202e\u200e\u202b\u200e\u206c\u202c\u200c\u206a\u200c\u200d\u200b\u202e\u202b\u200c\u200f\u202e\u202d\u202c\u206c\u202e
		{
			internal struct \u206a\u200f\u200d\u202b\u206e\u200d\u206e\u206a\u202d\u202e\u202a\u206a\u206c\u200e\u202e\u206f\u200c\u200f\u206c\u202a\u200f\u206a\u206a\u202a\u200f\u200b\u202e\u202d\u202c\u202a\u206a\u200f\u206f\u206c\u206a\u202b\u200c\u200f\u206d\u202d\u202e
			{
				internal \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] \u206c\u202b\u202e\u202b\u200c\u206b\u200d\u202c\u206a\u202d\u206a\u206b\u202c\u200e\u206d\u206f\u202e\u202a\u202e\u206a\u202d\u200d\u202c\u202b\u206d\u200d\u202e\u200f\u206f\u206a\u206f\u200b\u200d\u206d\u200d\u206f\u200b\u206c\u206e\u202e;

				private static object MoveDispatcher;

				internal void \u206e\u206c\u206d\u206d\u200f\u200f\u206d\u202c\u206c\u202b\u200c\u200b\u202c\u202d\u202e\u200b\u206c\u206b\u202e\u206a\u206a\u206f\u200f\u206e\u206a\u202a\u206b\u206b\u200b\u200f\u200e\u202a\u206a\u202c\u202e\u206d\u202b\u200c\u200b\u202d\u202e()
				{
					int num = 1;
					int num2 = num;
					while (true)
					{
						switch (num2)
						{
						default:
							return;
						case 0:
							return;
						case 1:
							\u206c\u202b\u202e\u202b\u200c\u206b\u200d\u202c\u206a\u202d\u206a\u206b\u202c\u200e\u206d\u206f\u202e\u202a\u202e\u206a\u202d\u200d\u202c\u202b\u206d\u200d\u202e\u200f\u206f\u206a\u206f\u200b\u200d\u206d\u200d\u206f\u200b\u206c\u206e\u202e = new \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[768];
							num2 = 0;
							if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_d66961690ed94dffab1f60f3771932da == 0)
							{
								num2 = 0;
							}
							break;
						}
					}
				}

				internal void \u200e\u202c\u206d\u206b\u200e\u202c\u202d\u206a\u202e\u206f\u206c\u200b\u206c\u206e\u202d\u206a\u206a\u200e\u206a\u202b\u206b\u202a\u202b\u200e\u202c\u202e\u202d\u206c\u202b\u202a\u206b\u206b\u202e\u200e\u200e\u200e\u202b\u200d\u202c\u200d\u202e()
				{
					int num = 0;
					while (true)
					{
						int num2 = 1862833309;
						while (true)
						{
							uint num3;
							switch ((num3 = (uint)num2 ^ 0x44031E33u) % 5)
							{
							case 4u:
								break;
							default:
								return;
							case 3u:
							{
								int num4;
								if (num >= 768)
								{
									num2 = 25376318;
									num4 = num2;
								}
								else
								{
									num2 = 1764805939;
									num4 = num2;
								}
								continue;
							}
							case 2u:
								\u206c\u202b\u202e\u202b\u200c\u206b\u200d\u202c\u206a\u202d\u206a\u206b\u202c\u200e\u206d\u206f\u202e\u202a\u202e\u206a\u202d\u200d\u202c\u202b\u206d\u200d\u202e\u200f\u206f\u206a\u206f\u200b\u200d\u206d\u200d\u206f\u200b\u206c\u206e\u202e[num].\u200b\u206e\u206e\u206f\u200b\u202b\u202b\u206f\u200b\u202e\u206f\u202e\u200d\u200c\u202d\u206a\u202d\u206a\u206c\u206b\u206c\u202e\u202c\u202c\u200d\u202c\u206f\u202b\u206d\u200d\u202b\u206f\u202d\u202a\u200c\u200b\u200d\u200f\u200e\u200d\u202e();
								num++;
								num2 = 1393516309;
								continue;
							case 1u:
								num2 = (int)(num3 * 1613769052) ^ -1024136291;
								continue;
							case 0u:
								return;
							}
							break;
						}
					}
				}

				internal byte \u200e\u202d\u206d\u206c\u200d\u206d\u206a\u206e\u206e\u200f\u206f\u202e\u202e\u202c\u200c\u206a\u200e\u202d\u202d\u200f\u202b\u200e\u202b\u202c\u206d\u202d\u206f\u202d\u206a\u202c\u206d\u202b\u200d\u200f\u200e\u206e\u202d\u200e\u206b\u202e(\u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e rangeDecoder)
				{
					int num = 2;
					uint num5 = default(uint);
					while (true)
					{
						int num2 = num;
						while (true)
						{
							int num3;
							int num4;
							uint num6;
							switch (num2)
							{
							default:
								return (byte)num5;
							case 4:
								if (num5 >= 256)
								{
									num2 = 5;
									continue;
								}
								goto case 3;
							case 6:
								break;
							case 3:
								num3 = -499427690;
								num4 = num3;
								goto IL_00cf;
							case 2:
								num5 = 1u;
								num2 = 1;
								if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_34e6e25f05064a59893cbc19e2d425c4 != 0)
								{
									num2 = 0;
								}
								continue;
							case 1:
								goto IL_00ca;
							case 5:
								{
									num3 = -399813645;
									num4 = num3;
									goto IL_00cf;
								}
								IL_00ca:
								num3 = -499427690;
								goto IL_00cf;
								IL_00cf:
								switch ((num6 = (uint)num3 ^ 0xD2DFDB4Bu) % 3)
								{
								case 1u:
									break;
								case 2u:
									goto end_IL_0012;
								case 0u:
									goto IL_00ca;
								default:
									goto IL_00eb;
								}
								goto default;
								IL_00eb:
								num2 = 0;
								if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_58d338d1425541009b9d264ca5084209 == 0)
								{
									num2 = 0;
								}
								continue;
							}
							break;
							continue;
							end_IL_0012:
							break;
						}
						num5 = (num5 << 1) | \u206c\u202b\u202e\u202b\u200c\u206b\u200d\u202c\u206a\u202d\u206a\u206b\u202c\u200e\u206d\u206f\u202e\u202a\u202e\u206a\u202d\u200d\u202c\u202b\u206d\u200d\u202e\u200f\u206f\u206a\u206f\u200b\u200d\u206d\u200d\u206f\u200b\u206c\u206e\u202e[num5].\u206c\u202b\u202c\u206e\u206b\u202c\u200d\u202e\u200b\u202b\u200f\u206e\u202a\u200c\u202a\u206a\u202d\u202e\u206c\u202a\u200f\u200c\u202e\u206f\u206a\u202a\u202d\u200c\u202c\u202e\u206a\u206d\u206a\u206a\u206d\u206c\u200d\u200f\u200b\u206a\u202e(rangeDecoder);
						num = 4;
					}
				}

				internal byte \u206b\u206d\u202d\u206d\u202e\u206f\u202b\u206a\u202e\u202a\u202b\u202e\u206a\u200c\u200b\u202d\u202d\u202b\u200e\u206f\u202b\u206a\u202e\u206a\u200d\u200b\u202c\u206e\u206d\u206f\u206c\u206e\u202b\u200c\u206a\u206f\u200b\u200f\u200f\u206f\u202e(\u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e rangeDecoder, byte matchByte)
				{
					uint num = 1u;
					uint num6 = default(uint);
					uint num5 = default(uint);
					while (true)
					{
						int num2 = 1074548260;
						while (true)
						{
							uint num3;
							switch ((num3 = (uint)num2 ^ 0x4FD705Eu) % 11)
							{
							case 0u:
								break;
							case 4u:
								num6 = \u206c\u202b\u202e\u202b\u200c\u206b\u200d\u202c\u206a\u202d\u206a\u206b\u202c\u200e\u206d\u206f\u202e\u202a\u202e\u206a\u202d\u200d\u202c\u202b\u206d\u200d\u202e\u200f\u206f\u206a\u206f\u200b\u200d\u206d\u200d\u206f\u200b\u206c\u206e\u202e[(1 + num5 << 8) + num].\u206c\u202b\u202c\u206e\u206b\u202c\u200d\u202e\u200b\u202b\u200f\u206e\u202a\u200c\u202a\u206a\u202d\u202e\u206c\u202a\u200f\u200c\u202e\u206f\u206a\u202a\u202d\u200c\u202c\u202e\u206a\u206d\u206a\u206a\u206d\u206c\u200d\u200f\u200b\u206a\u202e(rangeDecoder);
								num = (num << 1) | num6;
								num2 = (int)(num3 * 1835170164) ^ -102080767;
								continue;
							case 8u:
								num = (num << 1) | \u206c\u202b\u202e\u202b\u200c\u206b\u200d\u202c\u206a\u202d\u206a\u206b\u202c\u200e\u206d\u206f\u202e\u202a\u202e\u206a\u202d\u200d\u202c\u202b\u206d\u200d\u202e\u200f\u206f\u206a\u206f\u200b\u200d\u206d\u200d\u206f\u200b\u206c\u206e\u202e[num].\u206c\u202b\u202c\u206e\u206b\u202c\u200d\u202e\u200b\u202b\u200f\u206e\u202a\u200c\u202a\u206a\u202d\u202e\u206c\u202a\u200f\u200c\u202e\u206f\u206a\u202a\u202d\u200c\u202c\u202e\u206a\u206d\u206a\u206a\u206d\u206c\u200d\u200f\u200b\u206a\u202e(rangeDecoder);
								num2 = 578663353;
								continue;
							case 3u:
							{
								int num7;
								int num8;
								if (num5 == num6)
								{
									num7 = 1095886847;
									num8 = num7;
								}
								else
								{
									num7 = 524597796;
									num8 = num7;
								}
								num2 = num7 ^ (int)(num3 * 2072040467);
								continue;
							}
							case 1u:
								num5 = (uint)(matchByte >> 7) & 1u;
								num2 = 1002676069;
								continue;
							case 2u:
							{
								int num9;
								if (num >= 256)
								{
									num2 = 1990315235;
									num9 = num2;
								}
								else
								{
									num2 = 711366273;
									num9 = num2;
								}
								continue;
							}
							case 10u:
								matchByte <<= 1;
								num2 = (int)((num3 * 774148398) ^ 0x1F3458D3);
								continue;
							case 5u:
							{
								int num4;
								if (num < 256)
								{
									num2 = 1074548260;
									num4 = num2;
								}
								else
								{
									num2 = 1499781478;
									num4 = num2;
								}
								continue;
							}
							case 9u:
								num2 = ((int)num3 * -1487578316) ^ -1195572507;
								continue;
							case 6u:
								num2 = (int)((num3 * 90762239) ^ 0x300DA625);
								continue;
							default:
								return (byte)num;
							}
							break;
						}
					}
				}

				internal static bool QueryDispatcher()
				{
					return MoveDispatcher == null;
				}

				internal static object DisableDispatcher()
				{
					return MoveDispatcher;
				}
			}

			internal \u206a\u200f\u200d\u202b\u206e\u200d\u206e\u206a\u202d\u202e\u202a\u206a\u206c\u200e\u202e\u206f\u200c\u200f\u206c\u202a\u200f\u206a\u206a\u202a\u200f\u200b\u202e\u202d\u202c\u202a\u206a\u200f\u206f\u206c\u206a\u202b\u200c\u200f\u206d\u202d\u202e[] \u200c\u200b\u206e\u206e\u200d\u206b\u200d\u206d\u200e\u202d\u200d\u202d\u202d\u202e\u202a\u206f\u202c\u200f\u202d\u200e\u202b\u200e\u206b\u206f\u200e\u200b\u206a\u200f\u206e\u202e\u200b\u202b\u200d\u202b\u206b\u202d\u206d\u202d\u202e\u206f\u202e;

			internal int \u202e\u202b\u202b\u202d\u206b\u200c\u206b\u206d\u202e\u202b\u200e\u202c\u200c\u200f\u202d\u206d\u200f\u202d\u202c\u206f\u200d\u202b\u206b\u200e\u206b\u200d\u206b\u206a\u200e\u202a\u200b\u206e\u200d\u200f\u202d\u202d\u200e\u202b\u206b\u200e\u202e;

			internal int \u200c\u206b\u206b\u206e\u202b\u202b\u200c\u202d\u200b\u206f\u202e\u202d\u206a\u206d\u202b\u200f\u202e\u206f\u202b\u202e\u202a\u202e\u202e\u202b\u206a\u202a\u200d\u202a\u202d\u206b\u206e\u206d\u202d\u202a\u202e\u200c\u200d\u202d\u206b\u206c\u202e;

			internal uint \u202b\u206f\u200f\u202e\u200e\u202b\u202b\u206f\u206c\u206b\u206d\u206d\u206e\u200b\u202c\u200e\u200b\u202c\u202b\u206b\u200e\u200f\u202b\u200e\u202a\u200b\u200d\u202a\u206b\u202c\u206e\u206a\u202e\u202d\u200d\u202c\u200c\u200d\u206f\u202b\u202e;

			internal static \u206c\u202a\u206e\u202a\u206f\u202a\u206a\u200b\u200e\u206f\u202d\u200b\u206e\u202c\u200e\u200e\u206b\u202d\u200f\u206e\u202e\u202e\u200e\u202b\u200e\u206c\u202c\u200c\u206a\u200c\u200d\u200b\u202e\u202b\u200c\u200f\u202e\u202d\u202c\u206c\u202e InstantiateDispatcher;

			internal void \u206a\u206f\u200c\u200e\u200f\u200c\u202d\u202e\u202e\u200c\u202d\u206f\u202a\u200c\u200b\u206c\u206c\u206b\u202b\u202a\u206d\u206b\u206f\u200b\u202d\u206c\u202b\u200f\u206d\u200c\u200c\u206f\u206f\u200b\u202a\u202e\u202b\u202a\u200d\u206b\u202e(int numPosBits, int numPrevBits)
			{
				if (\u200c\u200b\u206e\u206e\u200d\u206b\u200d\u206d\u200e\u202d\u200d\u202d\u202d\u202e\u202a\u206f\u202c\u200f\u202d\u200e\u202b\u200e\u206b\u206f\u200e\u200b\u206a\u200f\u206e\u202e\u200b\u202b\u200d\u202b\u206b\u202d\u206d\u202d\u202e\u206f\u202e != null)
				{
					goto IL_000b;
				}
				goto IL_010e;
				IL_010e:
				\u202e\u202b\u202b\u202d\u206b\u200c\u206b\u206d\u202e\u202b\u200e\u202c\u200c\u200f\u202d\u206d\u200f\u202d\u202c\u206f\u200d\u202b\u206b\u200e\u206b\u200d\u206b\u206a\u200e\u202a\u200b\u206e\u200d\u200f\u202d\u202d\u200e\u202b\u206b\u200e\u202e = numPosBits;
				\u202b\u206f\u200f\u202e\u200e\u202b\u202b\u206f\u206c\u206b\u206d\u206d\u206e\u200b\u202c\u200e\u200b\u202c\u202b\u206b\u200e\u200f\u202b\u200e\u202a\u200b\u200d\u202a\u206b\u202c\u206e\u206a\u202e\u202d\u200d\u202c\u200c\u200d\u206f\u202b\u202e = (uint)((1 << numPosBits) - 1);
				\u200c\u206b\u206b\u206e\u202b\u202b\u200c\u202d\u200b\u206f\u202e\u202d\u206a\u206d\u202b\u200f\u202e\u206f\u202b\u202e\u202a\u202e\u202e\u202b\u206a\u202a\u200d\u202a\u202d\u206b\u206e\u206d\u202d\u202a\u202e\u200c\u200d\u202d\u206b\u206c\u202e = numPrevBits;
				uint num = (uint)(1 << \u200c\u206b\u206b\u206e\u202b\u202b\u200c\u202d\u200b\u206f\u202e\u202d\u206a\u206d\u202b\u200f\u202e\u206f\u202b\u202e\u202a\u202e\u202e\u202b\u206a\u202a\u200d\u202a\u202d\u206b\u206e\u206d\u202d\u202a\u202e\u200c\u200d\u202d\u206b\u206c\u202e + \u202e\u202b\u202b\u202d\u206b\u200c\u206b\u206d\u202e\u202b\u200e\u202c\u200c\u200f\u202d\u206d\u200f\u202d\u202c\u206f\u200d\u202b\u206b\u200e\u206b\u200d\u206b\u206a\u200e\u202a\u200b\u206e\u200d\u200f\u202d\u202d\u200e\u202b\u206b\u200e\u202e);
				int num2 = -2114754286;
				goto IL_0010;
				IL_0010:
				uint num4 = default(uint);
				while (true)
				{
					uint num3;
					switch ((num3 = (uint)num2 ^ 0x93B091DCu) % 11)
					{
					case 6u:
						break;
					default:
						return;
					case 4u:
						\u200c\u200b\u206e\u206e\u200d\u206b\u200d\u206d\u200e\u202d\u200d\u202d\u202d\u202e\u202a\u206f\u202c\u200f\u202d\u200e\u202b\u200e\u206b\u206f\u200e\u200b\u206a\u200f\u206e\u202e\u200b\u202b\u200d\u202b\u206b\u202d\u206d\u202d\u202e\u206f\u202e = new \u206a\u200f\u200d\u202b\u206e\u200d\u206e\u206a\u202d\u202e\u202a\u206a\u206c\u200e\u202e\u206f\u200c\u200f\u206c\u202a\u200f\u206a\u206a\u202a\u200f\u200b\u202e\u202d\u202c\u202a\u206a\u200f\u206f\u206c\u206a\u202b\u200c\u200f\u206d\u202d\u202e[num];
						num4 = 0u;
						num2 = ((int)num3 * -1335236958) ^ -749020408;
						continue;
					case 8u:
					{
						int num7;
						int num8;
						if (\u202e\u202b\u202b\u202d\u206b\u200c\u206b\u206d\u202e\u202b\u200e\u202c\u200c\u200f\u202d\u206d\u200f\u202d\u202c\u206f\u200d\u202b\u206b\u200e\u206b\u200d\u206b\u206a\u200e\u202a\u200b\u206e\u200d\u200f\u202d\u202d\u200e\u202b\u206b\u200e\u202e == numPosBits)
						{
							num7 = -808363129;
							num8 = num7;
						}
						else
						{
							num7 = -1362886795;
							num8 = num7;
						}
						num2 = num7 ^ ((int)num3 * -750787864);
						continue;
					}
					case 9u:
						goto IL_00a1;
					case 5u:
						\u200c\u200b\u206e\u206e\u200d\u206b\u200d\u206d\u200e\u202d\u200d\u202d\u202d\u202e\u202a\u206f\u202c\u200f\u202d\u200e\u202b\u200e\u206b\u206f\u200e\u200b\u206a\u200f\u206e\u202e\u200b\u202b\u200d\u202b\u206b\u202d\u206d\u202d\u202e\u206f\u202e[num4].\u206e\u206c\u206d\u206d\u200f\u200f\u206d\u202c\u206c\u202b\u200c\u200b\u202c\u202d\u202e\u200b\u206c\u206b\u202e\u206a\u206a\u206f\u200f\u206e\u206a\u202a\u206b\u206b\u200b\u200f\u200e\u202a\u206a\u202c\u202e\u206d\u202b\u200c\u200b\u202d\u202e();
						num2 = -1115012952;
						continue;
					case 3u:
					{
						int num5;
						int num6;
						if (\u200c\u206b\u206b\u206e\u202b\u202b\u200c\u202d\u200b\u206f\u202e\u202d\u206a\u206d\u202b\u200f\u202e\u206f\u202b\u202e\u202a\u202e\u202e\u202b\u206a\u202a\u200d\u202a\u202d\u206b\u206e\u206d\u202d\u202a\u202e\u200c\u200d\u202d\u206b\u206c\u202e == numPrevBits)
						{
							num5 = -1500777603;
							num6 = num5;
						}
						else
						{
							num5 = -1131596931;
							num6 = num5;
						}
						num2 = num5 ^ ((int)num3 * -1341585084);
						continue;
					}
					case 1u:
						goto IL_010e;
					case 10u:
						num4++;
						num2 = ((int)num3 * -1550785437) ^ 0x151C2955;
						continue;
					case 2u:
						num2 = (int)(num3 * 1442262796) ^ -1898387223;
						continue;
					case 7u:
						return;
					case 0u:
						return;
					}
					break;
					IL_00a1:
					int num9;
					if (num4 < num)
					{
						num2 = -1516681369;
						num9 = num2;
					}
					else
					{
						num2 = -1627406358;
						num9 = num2;
					}
				}
				goto IL_000b;
				IL_000b:
				num2 = -850849948;
				goto IL_0010;
			}

			internal void \u202e\u206f\u200b\u200e\u200e\u202e\u202d\u200d\u202d\u200e\u206d\u202d\u202b\u206c\u202d\u200c\u200b\u200c\u206f\u206b\u200c\u206a\u206c\u206c\u202a\u206e\u200c\u202a\u206c\u202e\u200c\u200d\u206c\u206f\u206f\u200b\u200e\u206a\u202d\u200d\u202e()
			{
				uint num = (uint)(1 << \u200c\u206b\u206b\u206e\u202b\u202b\u200c\u202d\u200b\u206f\u202e\u202d\u206a\u206d\u202b\u200f\u202e\u206f\u202b\u202e\u202a\u202e\u202e\u202b\u206a\u202a\u200d\u202a\u202d\u206b\u206e\u206d\u202d\u202a\u202e\u200c\u200d\u202d\u206b\u206c\u202e + \u202e\u202b\u202b\u202d\u206b\u200c\u206b\u206d\u202e\u202b\u200e\u202c\u200c\u200f\u202d\u206d\u200f\u202d\u202c\u206f\u200d\u202b\u206b\u200e\u206b\u200d\u206b\u206a\u200e\u202a\u200b\u206e\u200d\u200f\u202d\u202d\u200e\u202b\u206b\u200e\u202e);
				uint num4 = default(uint);
				while (true)
				{
					int num2 = -2050698625;
					while (true)
					{
						uint num3;
						switch ((num3 = (uint)num2 ^ 0xC1B31F98u) % 7)
						{
						case 4u:
							break;
						default:
							return;
						case 3u:
							\u200c\u200b\u206e\u206e\u200d\u206b\u200d\u206d\u200e\u202d\u200d\u202d\u202d\u202e\u202a\u206f\u202c\u200f\u202d\u200e\u202b\u200e\u206b\u206f\u200e\u200b\u206a\u200f\u206e\u202e\u200b\u202b\u200d\u202b\u206b\u202d\u206d\u202d\u202e\u206f\u202e[num4].\u200e\u202c\u206d\u206b\u200e\u202c\u202d\u206a\u202e\u206f\u206c\u200b\u206c\u206e\u202d\u206a\u206a\u200e\u206a\u202b\u206b\u202a\u202b\u200e\u202c\u202e\u202d\u206c\u202b\u202a\u206b\u206b\u202e\u200e\u200e\u200e\u202b\u200d\u202c\u200d\u202e();
							num2 = -710075721;
							continue;
						case 1u:
							num2 = ((int)num3 * -118683977) ^ 0x545B5B0C;
							continue;
						case 5u:
						{
							int num5;
							if (num4 < num)
							{
								num2 = -444716920;
								num5 = num2;
							}
							else
							{
								num2 = -853520175;
								num5 = num2;
							}
							continue;
						}
						case 0u:
							num4++;
							num2 = (int)(num3 * 1378817340) ^ -2045455846;
							continue;
						case 6u:
							num4 = 0u;
							num2 = ((int)num3 * -886457918) ^ 0x58F1FCE8;
							continue;
						case 2u:
							return;
						}
						break;
					}
				}
			}

			internal uint \u206a\u202a\u206b\u200f\u200e\u202e\u206d\u200f\u202a\u200d\u200f\u200b\u200b\u200d\u200b\u206d\u200c\u202c\u202b\u200d\u206b\u200c\u202a\u206f\u200b\u200c\u202b\u202a\u206b\u206b\u200b\u206f\u200c\u206f\u200b\u206d\u206f\u206c\u200b\u206c\u202e(uint pos, byte prevByte)
			{
				return ((pos & \u202b\u206f\u200f\u202e\u200e\u202b\u202b\u206f\u206c\u206b\u206d\u206d\u206e\u200b\u202c\u200e\u200b\u202c\u202b\u206b\u200e\u200f\u202b\u200e\u202a\u200b\u200d\u202a\u206b\u202c\u206e\u206a\u202e\u202d\u200d\u202c\u200c\u200d\u206f\u202b\u202e) << \u200c\u206b\u206b\u206e\u202b\u202b\u200c\u202d\u200b\u206f\u202e\u202d\u206a\u206d\u202b\u200f\u202e\u206f\u202b\u202e\u202a\u202e\u202e\u202b\u206a\u202a\u200d\u202a\u202d\u206b\u206e\u206d\u202d\u202a\u202e\u200c\u200d\u202d\u206b\u206c\u202e) + (uint)(prevByte >> 8 - \u200c\u206b\u206b\u206e\u202b\u202b\u200c\u202d\u200b\u206f\u202e\u202d\u206a\u206d\u202b\u200f\u202e\u206f\u202b\u202e\u202a\u202e\u202e\u202b\u206a\u202a\u200d\u202a\u202d\u206b\u206e\u206d\u202d\u202a\u202e\u200c\u200d\u202d\u206b\u206c\u202e);
			}

			internal byte \u200c\u202e\u202a\u206a\u202d\u202b\u200d\u202a\u202c\u202b\u206b\u200e\u206f\u200c\u202b\u200e\u206d\u206a\u206e\u206b\u202b\u202c\u202b\u200b\u206c\u200f\u202e\u200c\u200f\u200e\u200f\u206c\u200c\u202c\u206f\u200b\u206f\u202e\u200d\u200c\u202e(\u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e rangeDecoder, uint pos, byte prevByte)
			{
				return \u200c\u200b\u206e\u206e\u200d\u206b\u200d\u206d\u200e\u202d\u200d\u202d\u202d\u202e\u202a\u206f\u202c\u200f\u202d\u200e\u202b\u200e\u206b\u206f\u200e\u200b\u206a\u200f\u206e\u202e\u200b\u202b\u200d\u202b\u206b\u202d\u206d\u202d\u202e\u206f\u202e[\u206a\u202a\u206b\u200f\u200e\u202e\u206d\u200f\u202a\u200d\u200f\u200b\u200b\u200d\u200b\u206d\u200c\u202c\u202b\u200d\u206b\u200c\u202a\u206f\u200b\u200c\u202b\u202a\u206b\u206b\u200b\u206f\u200c\u206f\u200b\u206d\u206f\u206c\u200b\u206c\u202e(pos, prevByte)].\u200e\u202d\u206d\u206c\u200d\u206d\u206a\u206e\u206e\u200f\u206f\u202e\u202e\u202c\u200c\u206a\u200e\u202d\u202d\u200f\u202b\u200e\u202b\u202c\u206d\u202d\u206f\u202d\u206a\u202c\u206d\u202b\u200d\u200f\u200e\u206e\u202d\u200e\u206b\u202e(rangeDecoder);
			}

			internal byte \u206d\u202d\u200f\u206e\u202a\u206b\u200d\u200c\u200b\u202c\u200b\u206e\u206d\u202a\u200b\u206e\u202b\u206f\u206a\u200d\u200e\u200d\u206c\u206a\u200b\u202b\u202e\u200b\u200c\u206f\u206c\u206e\u206f\u200c\u206f\u200f\u202a\u206f\u202a\u206e\u202e(\u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e rangeDecoder, uint pos, byte prevByte, byte matchByte)
			{
				return \u200c\u200b\u206e\u206e\u200d\u206b\u200d\u206d\u200e\u202d\u200d\u202d\u202d\u202e\u202a\u206f\u202c\u200f\u202d\u200e\u202b\u200e\u206b\u206f\u200e\u200b\u206a\u200f\u206e\u202e\u200b\u202b\u200d\u202b\u206b\u202d\u206d\u202d\u202e\u206f\u202e[\u206a\u202a\u206b\u200f\u200e\u202e\u206d\u200f\u202a\u200d\u200f\u200b\u200b\u200d\u200b\u206d\u200c\u202c\u202b\u200d\u206b\u200c\u202a\u206f\u200b\u200c\u202b\u202a\u206b\u206b\u200b\u206f\u200c\u206f\u200b\u206d\u206f\u206c\u200b\u206c\u202e(pos, prevByte)].\u206b\u206d\u202d\u206d\u202e\u206f\u202b\u206a\u202e\u202a\u202b\u202e\u206a\u200c\u200b\u202d\u202d\u202b\u200e\u206f\u202b\u206a\u202e\u206a\u200d\u200b\u202c\u206e\u206d\u206f\u206c\u206e\u202b\u200c\u206a\u206f\u200b\u200f\u200f\u206f\u202e(rangeDecoder, matchByte);
			}

			internal \u206c\u202a\u206e\u202a\u206f\u202a\u206a\u200b\u200e\u206f\u202d\u200b\u206e\u202c\u200e\u200e\u206b\u202d\u200f\u206e\u202e\u202e\u200e\u202b\u200e\u206c\u202c\u200c\u206a\u200c\u200d\u200b\u202e\u202b\u200c\u200f\u202e\u202d\u202c\u206c\u202e()
			{
				ErrorPage.CreateRecord();
				base..ctor();
				int num = 0;
				if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_a9b822f1818f4d38b925be54c1e7956b == 0)
				{
					num = 0;
				}
				switch (num)
				{
				case 0:
					break;
				}
			}

			internal static bool PushDispatcher()
			{
				return InstantiateDispatcher == null;
			}

			internal static \u206c\u202a\u206e\u202a\u206f\u202a\u206a\u200b\u200e\u206f\u202d\u200b\u206e\u202c\u200e\u200e\u206b\u202d\u200f\u206e\u202e\u202e\u200e\u202b\u200e\u206c\u202c\u200c\u206a\u200c\u200d\u200b\u202e\u202b\u200c\u200f\u202e\u202d\u202c\u206c\u202e InitDispatcher()
			{
				return InstantiateDispatcher;
			}
		}

		internal readonly \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] \u206e\u202b\u206e\u200c\u206b\u200f\u202c\u200c\u200d\u200b\u206f\u200f\u206a\u200e\u200c\u202c\u200e\u206f\u206c\u202a\u202d\u202e\u206b\u206d\u206f\u206b\u206f\u206c\u202c\u202a\u206a\u206d\u202c\u200c\u206f\u202d\u200b\u200e\u200c\u202b\u202e;

		internal readonly \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] \u206c\u206d\u206a\u202e\u202a\u200f\u200e\u206e\u206e\u200f\u200d\u202a\u202c\u202b\u206f\u206a\u200f\u200d\u202b\u206f\u200f\u200f\u202a\u202c\u202e\u206b\u206c\u206f\u200c\u202e\u206d\u200e\u206c\u206d\u200b\u200e\u200c\u200e\u200f\u206d\u202e;

		internal readonly \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] \u202d\u202d\u206a\u206f\u202d\u206c\u202d\u200e\u206f\u200f\u206d\u202b\u206a\u206c\u202a\u202e\u202b\u200d\u200d\u206d\u202d\u200c\u200d\u206d\u200f\u202c\u202e\u200e\u206f\u206f\u206a\u200f\u202e\u206b\u206c\u202a\u206b\u206b\u200f\u206a\u202e;

		internal readonly \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] \u200e\u206a\u202c\u202d\u206f\u206f\u206e\u200b\u200e\u200b\u202a\u202e\u206d\u200b\u202e\u200e\u206e\u200c\u200c\u206f\u200c\u200b\u200f\u206a\u202b\u202c\u206f\u202e\u206e\u200d\u200e\u200e\u200c\u202e\u200f\u200d\u202c\u206e\u206e\u206a\u202e;

		internal readonly \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] \u202e\u206a\u202d\u202b\u200f\u202c\u202e\u200b\u206c\u200c\u202e\u200e\u206c\u200e\u200f\u200f\u200f\u200b\u200f\u202e\u202e\u206a\u200f\u202e\u200e\u202a\u202d\u206e\u202a\u200b\u206e\u202a\u202a\u202b\u206a\u202c\u200b\u202c\u206c\u200f\u202e;

		internal readonly \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] \u200b\u200e\u202d\u206c\u206f\u206c\u202d\u202b\u206d\u206e\u200b\u206c\u200d\u206d\u206a\u202a\u202c\u200c\u202a\u200b\u200f\u202a\u202a\u206b\u202a\u206a\u202c\u206b\u202b\u206b\u200b\u202b\u202e\u206b\u202b\u202e\u206b\u200e\u200f\u202b\u202e;

		internal readonly \u202e\u200f\u202b\u206a\u206a\u200d\u206e\u206d\u200e\u202e\u200e\u200f\u202b\u202b\u202b\u206a\u200f\u202d\u202b\u206e\u206b\u202d\u202c\u206c\u206f\u202e\u206e\u202a\u206d\u202e\u206e\u202c\u206b\u202a\u200b\u202c\u202e\u200f\u200f\u202c\u202e \u200f\u206c\u202c\u200c\u202a\u206a\u202e\u200c\u202e\u202e\u206f\u206e\u206e\u206b\u206a\u202b\u200f\u202c\u200e\u200b\u200b\u200c\u202e\u202b\u202e\u206c\u206a\u206d\u206d\u202d\u206d\u200f\u206c\u206c\u200e\u200b\u206b\u200c\u200c\u200e\u202e;

		internal readonly \u206c\u202a\u206e\u202a\u206f\u202a\u206a\u200b\u200e\u206f\u202d\u200b\u206e\u202c\u200e\u200e\u206b\u202d\u200f\u206e\u202e\u202e\u200e\u202b\u200e\u206c\u202c\u200c\u206a\u200c\u200d\u200b\u202e\u202b\u200c\u200f\u202e\u202d\u202c\u206c\u202e \u206d\u206f\u202a\u206b\u200c\u206e\u200c\u206d\u202a\u206b\u200b\u202e\u206e\u206f\u200d\u206d\u202c\u206a\u206a\u200b\u202a\u202e\u206c\u202e\u202c\u206c\u200b\u200d\u202d\u200d\u202a\u206c\u202c\u200b\u200c\u206e\u206c\u200e\u206d\u200f\u202e;

		internal readonly \u206a\u206b\u200f\u200d\u202e\u200e\u202c\u202e\u200c\u200c\u200b\u200f\u206f\u202c\u206d\u206a\u202b\u206c\u202b\u206c\u206f\u200e\u202b\u200f\u200d\u200b\u206c\u206d\u206b\u200d\u206c\u206a\u202a\u200d\u200f\u202e\u202d\u200f\u200f\u206b\u202e \u202c\u206f\u206d\u202c\u202e\u200f\u202e\u206f\u202a\u206a\u206d\u206f\u200b\u200c\u200e\u202d\u200c\u202e\u200b\u200f\u206d\u202c\u202e\u206a\u202a\u206a\u202c\u206d\u206f\u202a\u206a\u206f\u202e\u200d\u206c\u206a\u202e\u200f\u202a\u206d\u202e;

		internal readonly \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[] \u206b\u200d\u202a\u206b\u206f\u206b\u206f\u206e\u206f\u206f\u202a\u206c\u202d\u202b\u202e\u200d\u206b\u202d\u206b\u200e\u200c\u200e\u202e\u200f\u206d\u206d\u206d\u202a\u202b\u202a\u206e\u202b\u200e\u206c\u200e\u202b\u200f\u200c\u206c\u206e\u202e;

		internal readonly \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e[] \u202e\u200b\u200f\u202b\u206d\u206d\u202c\u206f\u200d\u200d\u206c\u200e\u206b\u200e\u206c\u202d\u206b\u206f\u200d\u200f\u202e\u206e\u202c\u202d\u200f\u200e\u206c\u206d\u206b\u206d\u200f\u206e\u206f\u200d\u202a\u200f\u200f\u206d\u200b\u200f\u202e;

		internal readonly \u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e \u202b\u200f\u200b\u200d\u202a\u202a\u200d\u200e\u200b\u200d\u206a\u200e\u206b\u200b\u200b\u200b\u200b\u200b\u200b\u200e\u202e\u200e\u202b\u200e\u200f\u200c\u206f\u202e\u202d\u202e\u206e\u202d\u206f\u202d\u202e\u206c\u206c\u200d\u206b\u200f\u202e;

		internal readonly \u202e\u200f\u202b\u206a\u206a\u200d\u206e\u206d\u200e\u202e\u200e\u200f\u202b\u202b\u202b\u206a\u200f\u202d\u202b\u206e\u206b\u202d\u202c\u206c\u206f\u202e\u206e\u202a\u206d\u202e\u206e\u202c\u206b\u202a\u200b\u202c\u202e\u200f\u200f\u202c\u202e \u202d\u206a\u202e\u206d\u206a\u202a\u206c\u202c\u200c\u206d\u200d\u206a\u200d\u206f\u202d\u202e\u206d\u200e\u200c\u202c\u206c\u200c\u202a\u200f\u202a\u206c\u200b\u200c\u202c\u206b\u206b\u202e\u206f\u202d\u206a\u202b\u206b\u202c\u200c\u202d\u202e;

		internal bool \u200c\u202d\u202c\u206d\u202d\u202e\u206c\u200c\u200d\u200f\u202c\u206e\u200d\u202c\u200e\u202d\u200b\u206d\u206e\u202b\u206a\u206c\u206e\u200c\u202d\u202d\u206f\u206d\u202b\u206f\u202d\u206f\u206e\u200f\u200e\u202e\u200d\u200e\u200b\u206a\u202e;

		internal uint \u206a\u202c\u202c\u206d\u202e\u206e\u206f\u206f\u200d\u206a\u202a\u202e\u202e\u200d\u202b\u202a\u206a\u202d\u200e\u206f\u200f\u206a\u200f\u206c\u206d\u202e\u202c\u200b\u206a\u200d\u200d\u206c\u206f\u202a\u206a\u200d\u200f\u200e\u202c\u202b\u202e;

		internal uint \u206b\u206b\u206d\u202e\u202d\u202e\u206b\u202b\u206c\u200e\u200b\u206d\u200b\u202a\u206b\u200d\u200b\u206e\u200f\u202c\u200c\u206c\u200e\u206d\u206e\u200c\u200b\u202e\u200b\u200d\u200c\u202b\u202b\u202d\u206e\u202e\u200e\u200c\u200d\u206f\u202e;

		internal \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e \u200d\u206b\u202b\u200d\u200f\u206b\u206a\u206d\u206d\u206a\u202c\u206d\u206c\u206b\u200d\u206f\u206e\u206a\u206a\u202c\u206c\u202a\u206a\u202c\u202a\u200e\u202b\u202e\u200d\u206f\u206d\u202e\u206b\u202b\u202e\u202c\u206e\u202d\u202c\u206d\u202e;

		internal uint \u202b\u206a\u200e\u202c\u206e\u200b\u200d\u206a\u206c\u206d\u200c\u206f\u202c\u202e\u202a\u202c\u206e\u206e\u206f\u200c\u202c\u202d\u200c\u200e\u206d\u202a\u206d\u206e\u200c\u206d\u206c\u206e\u202c\u202b\u200c\u206f\u206c\u200c\u200d\u202e;

		private static \u200d\u206f\u200b\u202b\u202e\u200c\u200f\u202b\u202c\u202e\u206e\u200c\u202d\u202d\u200e\u200d\u206b\u206e\u206b\u200f\u206a\u202a\u206d\u206d\u200d\u206e\u206a\u200c\u206c\u202b\u200b\u206e\u202d\u202c\u202b\u202a\u200e\u200c\u206c\u206f\u202e MapDispatcher;

		internal \u200d\u206f\u200b\u202b\u202e\u200c\u200f\u202b\u202c\u202e\u206e\u200c\u202d\u202d\u200e\u200d\u206b\u206e\u206b\u200f\u206a\u202a\u206d\u206d\u200d\u206e\u206a\u200c\u206c\u202b\u200b\u206e\u202d\u202c\u202b\u202a\u200e\u200c\u206c\u206f\u202e()
		{
			ErrorPage.CreateRecord();
			\u206e\u202b\u206e\u200c\u206b\u200f\u202c\u200c\u200d\u200b\u206f\u200f\u206a\u200e\u200c\u202c\u200e\u206f\u206c\u202a\u202d\u202e\u206b\u206d\u206f\u206b\u206f\u206c\u202c\u202a\u206a\u206d\u202c\u200c\u206f\u202d\u200b\u200e\u200c\u202b\u202e = new \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[192];
			\u206c\u206d\u206a\u202e\u202a\u200f\u200e\u206e\u206e\u200f\u200d\u202a\u202c\u202b\u206f\u206a\u200f\u200d\u202b\u206f\u200f\u200f\u202a\u202c\u202e\u206b\u206c\u206f\u200c\u202e\u206d\u200e\u206c\u206d\u200b\u200e\u200c\u200e\u200f\u206d\u202e = new \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[192];
			\u202d\u202d\u206a\u206f\u202d\u206c\u202d\u200e\u206f\u200f\u206d\u202b\u206a\u206c\u202a\u202e\u202b\u200d\u200d\u206d\u202d\u200c\u200d\u206d\u200f\u202c\u202e\u200e\u206f\u206f\u206a\u200f\u202e\u206b\u206c\u202a\u206b\u206b\u200f\u206a\u202e = new \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[12];
			\u200e\u206a\u202c\u202d\u206f\u206f\u206e\u200b\u200e\u200b\u202a\u202e\u206d\u200b\u202e\u200e\u206e\u200c\u200c\u206f\u200c\u200b\u200f\u206a\u202b\u202c\u206f\u202e\u206e\u200d\u200e\u200e\u200c\u202e\u200f\u200d\u202c\u206e\u206e\u206a\u202e = new \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[12];
			\u202e\u206a\u202d\u202b\u200f\u202c\u202e\u200b\u206c\u200c\u202e\u200e\u206c\u200e\u200f\u200f\u200f\u200b\u200f\u202e\u202e\u206a\u200f\u202e\u200e\u202a\u202d\u206e\u202a\u200b\u206e\u202a\u202a\u202b\u206a\u202c\u200b\u202c\u206c\u200f\u202e = new \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[12];
			\u200b\u200e\u202d\u206c\u206f\u206c\u202d\u202b\u206d\u206e\u200b\u206c\u200d\u206d\u206a\u202a\u202c\u200c\u202a\u200b\u200f\u202a\u202a\u206b\u202a\u206a\u202c\u206b\u202b\u206b\u200b\u202b\u202e\u206b\u202b\u202e\u206b\u200e\u200f\u202b\u202e = new \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[12];
			\u200f\u206c\u202c\u200c\u202a\u206a\u202e\u200c\u202e\u202e\u206f\u206e\u206e\u206b\u206a\u202b\u200f\u202c\u200e\u200b\u200b\u200c\u202e\u202b\u202e\u206c\u206a\u206d\u206d\u202d\u206d\u200f\u206c\u206c\u200e\u200b\u206b\u200c\u200c\u200e\u202e = new \u202e\u200f\u202b\u206a\u206a\u200d\u206e\u206d\u200e\u202e\u200e\u200f\u202b\u202b\u202b\u206a\u200f\u202d\u202b\u206e\u206b\u202d\u202c\u206c\u206f\u202e\u206e\u202a\u206d\u202e\u206e\u202c\u206b\u202a\u200b\u202c\u202e\u200f\u200f\u202c\u202e();
			\u206d\u206f\u202a\u206b\u200c\u206e\u200c\u206d\u202a\u206b\u200b\u202e\u206e\u206f\u200d\u206d\u202c\u206a\u206a\u200b\u202a\u202e\u206c\u202e\u202c\u206c\u200b\u200d\u202d\u200d\u202a\u206c\u202c\u200b\u200c\u206e\u206c\u200e\u206d\u200f\u202e = new \u206c\u202a\u206e\u202a\u206f\u202a\u206a\u200b\u200e\u206f\u202d\u200b\u206e\u202c\u200e\u200e\u206b\u202d\u200f\u206e\u202e\u202e\u200e\u202b\u200e\u206c\u202c\u200c\u206a\u200c\u200d\u200b\u202e\u202b\u200c\u200f\u202e\u202d\u202c\u206c\u202e();
			\u202c\u206f\u206d\u202c\u202e\u200f\u202e\u206f\u202a\u206a\u206d\u206f\u200b\u200c\u200e\u202d\u200c\u202e\u200b\u200f\u206d\u202c\u202e\u206a\u202a\u206a\u202c\u206d\u206f\u202a\u206a\u206f\u202e\u200d\u206c\u206a\u202e\u200f\u202a\u206d\u202e = new \u206a\u206b\u200f\u200d\u202e\u200e\u202c\u202e\u200c\u200c\u200b\u200f\u206f\u202c\u206d\u206a\u202b\u206c\u202b\u206c\u206f\u200e\u202b\u200f\u200d\u200b\u206c\u206d\u206b\u200d\u206c\u206a\u202a\u200d\u200f\u202e\u202d\u200f\u200f\u206b\u202e();
			\u206b\u200d\u202a\u206b\u206f\u206b\u206f\u206e\u206f\u206f\u202a\u206c\u202d\u202b\u202e\u200d\u206b\u202d\u206b\u200e\u200c\u200e\u202e\u200f\u206d\u206d\u206d\u202a\u202b\u202a\u206e\u202b\u200e\u206c\u200e\u202b\u200f\u200c\u206c\u206e\u202e = new \u202d\u206e\u202c\u206f\u202e\u206e\u206b\u202e\u200f\u202a\u200d\u202d\u200d\u200e\u206c\u206e\u202a\u200c\u206c\u206c\u200e\u202a\u202e\u202b\u206b\u202c\u200f\u200c\u206f\u202b\u202b\u206b\u200e\u200d\u200f\u202a\u206f\u200c\u200b\u202a\u202e[114];
			\u202e\u200b\u200f\u202b\u206d\u206d\u202c\u206f\u200d\u200d\u206c\u200e\u206b\u200e\u206c\u202d\u206b\u206f\u200d\u200f\u202e\u206e\u202c\u202d\u200f\u200e\u206c\u206d\u206b\u206d\u200f\u206e\u206f\u200d\u202a\u200f\u200f\u206d\u200b\u200f\u202e = new \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e[4];
			\u202b\u200f\u200b\u200d\u202a\u202a\u200d\u200e\u200b\u200d\u206a\u200e\u206b\u200b\u200b\u200b\u200b\u200b\u200b\u200e\u202e\u200e\u202b\u200e\u200f\u200c\u206f\u202e\u202d\u202e\u206e\u202d\u206f\u202d\u202e\u206c\u206c\u200d\u206b\u200f\u202e = new \u206f\u200e\u200e\u206b\u200e\u200b\u206b\u200f\u206b\u206e\u202a\u206d\u206d\u206c\u200f\u206f\u206c\u202b\u206b\u200c\u202b\u206a\u202c\u200d\u206c\u202c\u206a\u200c\u206f\u206a\u202d\u200f\u200d\u200d\u206c\u206c\u206d\u200e\u202d\u206d\u202e();
			\u202d\u206a\u202e\u206d\u206a\u202a\u206c\u202c\u200c\u206d\u200d\u206a\u200d\u206f\u202d\u202e\u206d\u200e\u200c\u202c\u206c\u200c\u202a\u200f\u202a\u206c\u200b\u200c\u202c\u206b\u206b\u202e\u206f\u202d\u206a\u202b\u206b\u202c\u200c\u202d\u202e = new \u202e\u200f\u202b\u206a\u206a\u200d\u206e\u206d\u200e\u202e\u200e\u200f\u202b\u202b\u202b\u206a\u200f\u202d\u202b\u206e\u206b\u202d\u202c\u206c\u206f\u202e\u206e\u202a\u206d\u202e\u206e\u202c\u206b\u202a\u200b\u202c\u202e\u200f\u200f\u202c\u202e();
			\u200d\u206b\u202b\u200d\u200f\u206b\u206a\u206d\u206d\u206a\u202c\u206d\u206c\u206b\u200d\u206f\u206e\u206a\u206a\u202c\u206c\u202a\u206a\u202c\u202a\u200e\u202b\u202e\u200d\u206f\u206d\u202e\u206b\u202b\u202e\u202c\u206e\u202d\u202c\u206d\u202e = new \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e(4);
			base..ctor();
			int num3 = default(int);
			while (true)
			{
				int num = -7913822;
				while (true)
				{
					uint num2;
					switch ((num2 = (uint)num ^ 0xECEFB647u) % 8)
					{
					case 7u:
						break;
					default:
						return;
					case 2u:
						num3++;
						num = ((int)num2 * -904574984) ^ -1090782324;
						continue;
					case 3u:
					{
						int num4;
						if ((long)num3 >= 4L)
						{
							num = -610719649;
							num4 = num;
						}
						else
						{
							num = -1955960181;
							num4 = num;
						}
						continue;
					}
					case 5u:
						\u206a\u202c\u202c\u206d\u202e\u206e\u206f\u206f\u200d\u206a\u202a\u202e\u202e\u200d\u202b\u202a\u206a\u202d\u200e\u206f\u200f\u206a\u200f\u206c\u206d\u202e\u202c\u200b\u206a\u200d\u200d\u206c\u206f\u202a\u206a\u200d\u200f\u200e\u202c\u202b\u202e = uint.MaxValue;
						num = (int)(num2 * 585295164) ^ -1760374819;
						continue;
					case 1u:
						num = (int)(num2 * 488117056) ^ -2046035140;
						continue;
					case 4u:
						\u202e\u200b\u200f\u202b\u206d\u206d\u202c\u206f\u200d\u200d\u206c\u200e\u206b\u200e\u206c\u202d\u206b\u206f\u200d\u200f\u202e\u206e\u202c\u202d\u200f\u200e\u206c\u206d\u206b\u206d\u200f\u206e\u206f\u200d\u202a\u200f\u200f\u206d\u200b\u200f\u202e[num3] = new \u200c\u206a\u200c\u202a\u200c\u200f\u200f\u206c\u206e\u206c\u202c\u200f\u206c\u206e\u206a\u200b\u202b\u202c\u202e\u202b\u202b\u200d\u206e\u202d\u206e\u206c\u200e\u200f\u206c\u200d\u202e\u206a\u202c\u202a\u202e\u206e\u206e\u206d\u206d\u202b\u202e(6);
						num = -2111567803;
						continue;
					case 6u:
						num3 = 0;
						num = ((int)num2 * -1859595997) ^ 0x5780C6D4;
						continue;
					case 0u:
						return;
					}
					break;
				}
			}
		}

		internal void \u206c\u206d\u206d\u206a\u202a\u200e\u206f\u200f\u202b\u202a\u206a\u206a\u202a\u202a\u200f\u206d\u200b\u206c\u200b\u206f\u202b\u200b\u200f\u206c\u202b\u200e\u206e\u206f\u200b\u200b\u200e\u202d\u200e\u202a\u202c\u206f\u206b\u202e\u202d\u200f\u202e(uint dictionarySize)
		{
			if (\u206a\u202c\u202c\u206d\u202e\u206e\u206f\u206f\u200d\u206a\u202a\u202e\u202e\u200d\u202b\u202a\u206a\u202d\u200e\u206f\u200f\u206a\u200f\u206c\u206d\u202e\u202c\u200b\u206a\u200d\u200d\u206c\u206f\u202a\u206a\u200d\u200f\u200e\u202c\u202b\u202e == dictionarySize)
			{
				return;
			}
			uint windowSize = default(uint);
			while (true)
			{
				int num = 1754984212;
				while (true)
				{
					uint num2;
					switch ((num2 = (uint)num ^ 0x56303172u) % 5)
					{
					case 2u:
						break;
					default:
						return;
					case 1u:
						\u206a\u202c\u202c\u206d\u202e\u206e\u206f\u206f\u200d\u206a\u202a\u202e\u202e\u200d\u202b\u202a\u206a\u202d\u200e\u206f\u200f\u206a\u200f\u206c\u206d\u202e\u202c\u200b\u206a\u200d\u200d\u206c\u206f\u202a\u206a\u200d\u200f\u200e\u202c\u202b\u202e = dictionarySize;
						num = ((int)num2 * -1680978840) ^ -1532679109;
						continue;
					case 3u:
						\u206b\u206b\u206d\u202e\u202d\u202e\u206b\u202b\u206c\u200e\u200b\u206d\u200b\u202a\u206b\u200d\u200b\u206e\u200f\u202c\u200c\u206c\u200e\u206d\u206e\u200c\u200b\u202e\u200b\u200d\u200c\u202b\u202b\u202d\u206e\u202e\u200e\u200c\u200d\u206f\u202e = Math.Max(\u206a\u202c\u202c\u206d\u202e\u206e\u206f\u206f\u200d\u206a\u202a\u202e\u202e\u200d\u202b\u202a\u206a\u202d\u200e\u206f\u200f\u206a\u200f\u206c\u206d\u202e\u202c\u200b\u206a\u200d\u200d\u206c\u206f\u202a\u206a\u200d\u200f\u200e\u202c\u202b\u202e, 1u);
						windowSize = Math.Max(\u206b\u206b\u206d\u202e\u202d\u202e\u206b\u202b\u206c\u200e\u200b\u206d\u200b\u202a\u206b\u200d\u200b\u206e\u200f\u202c\u200c\u206c\u200e\u206d\u206e\u200c\u200b\u202e\u200b\u200d\u200c\u202b\u202b\u202d\u206e\u202e\u200e\u200c\u200d\u206f\u202e, 4096u);
						num = (int)((num2 * 720835232) ^ 0x38F17EEC);
						continue;
					case 0u:
						\u202c\u206f\u206d\u202c\u202e\u200f\u202e\u206f\u202a\u206a\u206d\u206f\u200b\u200c\u200e\u202d\u200c\u202e\u200b\u200f\u206d\u202c\u202e\u206a\u202a\u206a\u202c\u206d\u206f\u202a\u206a\u206f\u202e\u200d\u206c\u206a\u202e\u200f\u202a\u206d\u202e.\u206f\u202c\u206e\u200e\u206b\u202a\u202d\u206c\u206d\u202c\u206d\u206d\u200b\u206e\u200f\u200d\u206a\u202b\u206c\u200e\u202c\u200f\u206c\u202d\u200c\u202c\u202c\u206f\u202c\u200d\u200f\u206f\u206d\u206a\u200c\u200c\u202d\u202b\u200c\u206a\u202e(windowSize);
						num = ((int)num2 * -344860447) ^ -328425823;
						continue;
					case 4u:
						return;
					}
					break;
				}
			}
		}

		internal void \u200e\u202d\u200f\u202c\u202c\u200d\u206a\u206a\u202e\u202e\u202e\u206f\u206f\u200c\u202b\u200f\u200c\u202b\u200e\u206e\u200c\u200c\u202b\u202e\u200f\u202e\u200f\u202c\u206b\u200c\u202e\u202e\u206d\u202d\u206d\u206f\u202d\u202a\u206c\u202e\u202e(int lp, int lc)
		{
			int num = 1;
			int num2 = num;
			while (true)
			{
				switch (num2)
				{
				default:
					return;
				case 1:
					\u206d\u206f\u202a\u206b\u200c\u206e\u200c\u206d\u202a\u206b\u200b\u202e\u206e\u206f\u200d\u206d\u202c\u206a\u206a\u200b\u202a\u202e\u206c\u202e\u202c\u206c\u200b\u200d\u202d\u200d\u202a\u206c\u202c\u200b\u200c\u206e\u206c\u200e\u206d\u200f\u202e.\u206a\u206f\u200c\u200e\u200f\u200c\u202d\u202e\u202e\u200c\u202d\u206f\u202a\u200c\u200b\u206c\u206c\u206b\u202b\u202a\u206d\u206b\u206f\u200b\u202d\u206c\u202b\u200f\u206d\u200c\u200c\u206f\u206f\u200b\u202a\u202e\u202b\u202a\u200d\u206b\u202e(lp, lc);
					num2 = 0;
					if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_05aa44ac360f4543942d6d4665b21d8f != 0)
					{
						num2 = 0;
					}
					break;
				case 0:
					return;
				}
			}
		}

		internal void \u202d\u202b\u200d\u202d\u202b\u202a\u206a\u206a\u200b\u202d\u202e\u206e\u202c\u202a\u200d\u202c\u206e\u200f\u206f\u202b\u200b\u202d\u200d\u200f\u206e\u206b\u202e\u200f\u206f\u200b\u206b\u200e\u202c\u200e\u202b\u200b\u206e\u202e\u206d\u206f\u202e(int pb)
		{
			int num = 6;
			int num2 = num;
			uint num3 = default(uint);
			uint num4 = default(uint);
			while (true)
			{
				int num5;
				switch (num2)
				{
				default:
					return;
				case 4:
					\u202d\u206a\u202e\u206d\u206a\u202a\u206c\u202c\u200c\u206d\u200d\u206a\u200d\u206f\u202d\u202e\u206d\u200e\u200c\u202c\u206c\u200c\u202a\u200f\u202a\u206c\u200b\u200c\u202c\u206b\u206b\u202e\u206f\u202d\u206a\u202b\u206b\u202c\u200c\u202d\u202e.\u202a\u206d\u200c\u206d\u206b\u200c\u200d\u202d\u200d\u200d\u202b\u200e\u200b\u206b\u206d\u206c\u206e\u202d\u200c\u202c\u200c\u202c\u200b\u206b\u200b\u206f\u206e\u200f\u206c\u200d\u202a\u200b\u206c\u200b\u202e\u202b\u206c\u206b\u202e\u202b\u202e(num3);
					num2 = 2;
					break;
				case 3:
					goto IL_005e;
				case 1:
					num5 = (int)(num4 * 138762949) ^ -1055751968;
					goto IL_00e3;
				case 2:
					\u202b\u206a\u200e\u202c\u206e\u200b\u200d\u206a\u206c\u206d\u200c\u206f\u202c\u202e\u202a\u202c\u206e\u206e\u206f\u200c\u202c\u202d\u200c\u200e\u206d\u202a\u206d\u206e\u200c\u206d\u206c\u206e\u202c\u202b\u200c\u206f\u206c\u200c\u200d\u202e = num3 - 1;
					num2 = 0;
					if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_a8c1fe04323a4399bcb12c498794d37e == 0)
					{
						num2 = 0;
					}
					break;
				case 0:
					return;
				case 6:
					num3 = (uint)(1 << pb);
					num2 = 5;
					break;
				case 5:
					goto IL_00de;
					IL_00e3:
					switch ((num4 = (uint)num5 ^ 0xE445B224u) % 3)
					{
					case 1u:
						break;
					case 2u:
						goto IL_005e;
					case 0u:
						goto IL_00de;
					default:
						goto IL_00ff;
					}
					goto case 4;
					IL_00ff:
					num2 = 4;
					break;
					IL_00de:
					num5 = -609599758;
					goto IL_00e3;
					IL_005e:
					\u200f\u206c\u202c\u200c\u202a\u206a\u202e\u200c\u202e\u202e\u206f\u206e\u206e\u206b\u206a\u202b\u200f\u202c\u200e\u200b\u200b\u200c\u202e\u202b\u202e\u206c\u206a\u206d\u206d\u202d\u206d\u200f\u206c\u206c\u200e\u200b\u206b\u200c\u200c\u200e\u202e.\u202a\u206d\u200c\u206d\u206b\u200c\u200d\u202d\u200d\u200d\u202b\u200e\u200b\u206b\u206d\u206c\u206e\u202d\u200c\u202c\u200c\u202c\u200b\u206b\u200b\u206f\u206e\u200f\u206c\u200d\u202a\u200b\u206c\u200b\u202e\u202b\u206c\u206b\u202e\u202b\u202e(num3);
					num2 = 1;
					if (<Module>{3df04056-351e-45b9-85a9-90dfc111f8c4}.m_0e9764acac0f48648ed50cef1c5b453e.m_0f61d379587f4b35bd57d0804be9cf98 == 0)
					{
						num2 = 0;
					}
					break;
				}
			}
		}

		internal void \u202e\u200c\u206d\u206a\u202c\u202e\u200b\u206e\u206b\u202e\u200b\u206b\u206a\u206a\u202c\u200b\u200c\u202d\u206d\u202e\u206d\u200f\u206a\u206b\u206f\u200c\u206a\u202d\u200d\u206d\u202c\u202b\u200d\u206d\u206a\u200c\u202b\u206b\u206d\u206e\u202e(Stream inStream, Stream outStream)
		{
			\u202b\u200f\u200b\u200d\u202a\u202a\u200d\u200e\u200b\u200d\u206a\u200e\u206b\u200b\u200b\u200b\u200b\u200b\u200b\u200e\u202e\u200e\u202b\u200e\u200f\u200c\u206f\u202e\u202d\u202e\u206e\u202d\u206f\u202d\u202e\u206c\u206c\u200d\u206b\u200f\u202e.\u200f\u206a\u206b\u206d\u200f\u202c\u200e\u200b\u202d\u206b\u202e\u202e\u206a\u206b\u200b\u200d\u202a\u202d\u206b\u200c\u200e\u200c\u202d\u202b\u200b\u202b\u202c\u200b\u206e\u206e\u200c\u200c\u206d\u206d\u206a\u200e\u200b\u202c\u202b\u202e(inStream);
			\u202c\u206f\u206d\u202c\u202e\u200f\u202e\u206f\u202a\u206a\u206d\u206f\u200b\u200c\u200e\u202d\u200c\u202e\u200b\u200f\u206d\u202c\u202e\u206a\u202a\u206a\u202c\u206d\u206f\u202a\u206a\u206f\u202e\u200d\u206c\u206a\u202e\u200f\u202a\u206d\u202e.\u200e\u200e\u202e\u202a\u200e\u202a\u200e\u206c\u202b\u206e\u202d\u202a\u200e\u206f\u206a\u202a\u202c\u200b\u202a\u200c\u202c\u202a\u200e\u202c\u200b\u200c\u202a\u202c\u202e\u200d\u206c\u200e\u206e\u200b\u202e\u200c\u202a\u206b\u200c\u206c\u202e(outStream, \u200c\u202d\u202c\u206d\u202d\u202e\u206c\u200c\u200d\u200f\u202c\u206e\u200d\u202c\u200e\u202d\u200b\u206d\u206e\u202b\u206a\u206c\u206e\u200c\u202d\u202d\u206f\u206d\u202b\u206f\u202d\u206f\u206e\u200f\u200e\u202e\u200d\u200e\u200b\u206a\u202e);
			uint num6 = default(uint);
			uint num3 = default(uint);
			uint num4 = default(uint);
			while (true)
			{
				int num = 822527250;
				while (true)
				{
					uint num2;
					switch ((num2 = (uint)num ^ 0x741A5B3u) % 23)
					{
					case 3u:
						break;
					case 8u:
						\u206e\u202b\u206e\u200c\u206b\u200f\u202c\u200c\u200d\u200b\u206f\u200f\u206a\u200e\u200c\u202c\u200e\u206f\u206c\u202a\u202d\u202e\u206b\u206d\u206f\u206b\u206f\u206c\u202c\u202a\u206a\u206d\u202c\u200c\u206f\u202d\u200b\u200e\u200c\u202b\u202e[num6].\u200b\u206e\u206e\u206f\u200b\u202b\u202b\u206f\u200b\u202e\u206f\u202e\u200d\u200c\u202d\u206a\u202d\u206a\u206c\u206b\u206c\u202e\u202c\u202c\u200d\u202c\u206f\u202b\u206d\u200d\u202b\u206f\u202d\u202a\u200c\u200b\u200d\u200f\u200e\u200d\u202e();
						num = ((int)num2 * -78605464) ^ -503162069;
						continue;
					case 5u:
						num6 = (num3 << 4) + num4;
						num = 277048380;
						continue;
					case 14u:
						num3++;
						num = (int)(num2 * 371860118) ^ -355420555;
						continue;
					case 7u:
						num = (int)((num2 * 1279726334) ^ 0x50A7F18);
						continue;
					case 12u:
						\u206b\u200d\u202a\u206b\u206f\u206b\u206f\u206e\u206f\u206f\u202a\u206c\u202d\u202b\u202e\u200d\u206b\u202d\u206b\u200e\u200c\u200e\u202e\u200f\u206d\u206d\u206d\u202a\u202b\u202a\u206e\u202b\u200e\u206c\u200e\u202b\u200f\u200c\u206c\u206e\u202e[num3].\u200b\u206e\u206e\u206f\u200b\u202b\u202b\u206f\u200b\u202e\u206f\u202e\u200d\u200c\u202d\u206a\u202d\u206a\u206c\u206b\u206c\u202e\u202c\u202c\u200d\u202c\u206f\u202b\u206d\u200d\u202b\u206f\u202d\u202a\u200c\u200b\u200d\u200f\u200e\u200d\u202e();
						num = 191143390;
						continue;
					case 1u:
						\u206c\u206d\u206a\u202e\u202a\u200f\u200e\u206e\u206e\u200f\u200d\u202a\u202c\u202b\u206f\u206a\u200f\u200d\u202b\u206f\u200f\u200f\u202a\u202c\u202e\u206b\u206c\u206f\u200c\u202e\u206d\u200e\u206c\u206d\u200b\u200e\u200c\u200e\u200f\u206d\u202e[num6].\u200b\u206e\u206e\u206f\u200b\u202b\u202b\u206f\u200b\u202e\u206f\u202e\u200d\u200c\u202d\u206a\u202d\u206a\u206c\u206b\u206c\u202e\u202c\u202c\u200d\u202c\u206f\u202b\u206d\u200d\u202b\u206f\u202d\u202a\u200c\u200b\u200d\u200f\u200e\u200d\u202e();
						num4++;
						num = (int)(num2 * 664189888) ^ -1422391168;
						continue;
					case 17u:
						\u206d\u206f\u202a\u206b\u200c\u206e\u200c\u206d\u202a\u206b\u200b\u202e\u206e\u206f\u200d\u206d\u202c\u206a\u206a\u200b\u202a\u202e\u206c\u202e\u202c\u206c\u200b\u200d\u202d\u200d\u202a\u206c\u202c\u200b\u200c\u206e\u206c\u200e\u206d\u200f\u202e.\u202e\u206f\u200b\u200e\u200e\u202e\u202d\u200d\u202d\u200e\u206d\u202d\u202b\u2

BepInEx/plugins/Fang86-MoreSlots/moreslots.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
using ValheimInventorySlots;
using backpacks;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("backpacks")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("backpacks")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("04e60408-c37c-4b84-b8cd-3f6257152cb4")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.0", FrameworkDisplayName = ".NET Framework 4")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ValheimInventorySlots
{
	[BepInPlugin("8F0F9F2B-E481-4BEC-B641-01228D7508F9", "MoreSlotsPatcher", "1.1.0")]
	public class FixGuiFrame : BaseUnityPlugin
	{
		public const string FixGuiGuid = "8F0F9F2B-E481-4BEC-B641-01228D7508F9";

		public const string FixGuiName = "MoreSlotsPatcher";

		private GameObject inventoryScreenObjectRoot;

		private Transform inventoryScreenObject;

		private Transform containerScreenObject;

		private float bgYOffset = 0f;

		private float containerYOffset = 0f;

		private Coroutine screenSearch;

		public static int ExtraRows { get; set; }

		private void OnEnable()
		{
			screenSearch = ((MonoBehaviour)this).StartCoroutine(screenSearchCoroutine());
		}

		private void OnDisable()
		{
			((MonoBehaviour)this).StopCoroutine(screenSearch);
		}

		public IEnumerator screenSearchCoroutine()
		{
			while (((Behaviour)this).enabled)
			{
				if ((Object)(object)inventoryScreenObjectRoot == (Object)null || (Object)(object)inventoryScreenObject == (Object)null || (Object)(object)containerScreenObject == (Object)null)
				{
					bgYOffset = 0f;
					containerYOffset = 0f;
					inventoryScreenObjectRoot = (from obj in Resources.FindObjectsOfTypeAll<GameObject>()
						where ((Object)obj).name == "Inventory_screen"
						where obj.transform.position.x != 0f
						select obj).SingleOrDefault();
					if ((Object)(object)inventoryScreenObjectRoot != (Object)null)
					{
						yield return (object)new WaitForSecondsRealtime(1f);
						inventoryScreenObject = inventoryScreenObjectRoot.transform.Find("root/Player/Bkg");
						containerScreenObject = inventoryScreenObjectRoot.transform.Find("root/Container");
					}
					yield return (object)new WaitForSecondsRealtime(5f);
				}
				else
				{
					((Component)inventoryScreenObject).transform.localScale = new Vector3(1f, (float)ExtraRows * 0.25f + 1f, 1f);
					if (bgYOffset == 0f)
					{
						float oldOffset = ((Component)inventoryScreenObject).transform.localPosition.y;
						bgYOffset = ((Component)inventoryScreenObject).transform.localPosition.y * ((float)ExtraRows * 0.25f + 1f);
						float offsetDiff = oldOffset - bgYOffset;
						containerYOffset = containerScreenObject.localPosition.y - offsetDiff;
						Vector3 localBgPosition = ((Component)inventoryScreenObject).transform.localPosition;
						localBgPosition.y = bgYOffset;
						Vector3 localContainerPosition = ((Component)containerScreenObject).transform.localPosition;
						localContainerPosition.y = containerYOffset;
						((Component)inventoryScreenObject).transform.localPosition = localBgPosition;
						((Component)containerScreenObject).transform.localPosition = localBgPosition;
						float sleepSeconds = 30f;
						yield return (object)new WaitForSecondsRealtime(sleepSeconds);
					}
				}
				yield return 0;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "CreateTombStone")]
	public class TombstonePatcher
	{
		private static void Prefix(Player __instance)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: 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)
			if (Backpacks.GKInstalled)
			{
				return;
			}
			GameObject val = Object.Instantiate<GameObject>(__instance.m_tombstone, ((Character)__instance).GetCenterPoint() + Vector3.up * 2.5f, ((Component)__instance).transform.rotation);
			Transform transform = val.gameObject.transform;
			transform.localScale -= new Vector3(0.5f, 0.5f, 0.5f);
			Container component = val.GetComponent<Container>();
			((Humanoid)__instance).UnequipAllItems();
			Func<ItemData, bool> predicate = (ItemData item) => item.m_gridPos.y >= 4 && !item.m_shared.m_questItem && !item.m_equiped;
			ItemData[] array = ((Humanoid)__instance).GetInventory().GetAllItems().Where(predicate)
				.ToArray();
			foreach (ItemData val2 in array)
			{
				if (val2.m_gridPos.y >= 4)
				{
					component.GetInventory().AddItem(val2);
					((Humanoid)__instance).GetInventory().RemoveItem(val2);
				}
			}
		}
	}
}
namespace backpacks
{
	[BepInPlugin("valheim.mod.moreslots", "More Slots", "1.1.6")]
	public class Backpacks : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(Player), "Awake")]
		public static class GridExtension
		{
			private static void Prefix(ref Player __instance)
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Expected O, but got Unknown
				int value = rows.Value;
				int num = 8;
				Traverse.Create((object)__instance).Field("m_inventory").SetValue((object)new Inventory("Inventory", (Sprite)null, num, value));
			}
		}

		private const string MID = "valheim.mod.moreslots";

		private const string NAME = "More Slots";

		private const string VERSION = "1.1.6";

		private const string author = "Fang86";

		public static bool GKInstalled;

		private static Assembly assem = typeof(Backpacks).Assembly;

		public static string fpath = assem.Location;

		public static string path = fpath.Remove(fpath.Length - 13);

		private static ConfigFile configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, "moreslots.cfg"), true);

		private static ConfigEntry<int> rows = configFile.Bind<int>("General", "rows", 6, "Number of rows in the player's inventory grid");

		private void Awake()
		{
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			FixGuiFrame.ExtraRows = rows.Value - 4;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"More Slots mod - Created by Fang86");
			if (File.Exists(path + "Gravekeeper.dll"))
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Gravekeeper found");
				GKInstalled = true;
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Gravekeeper not found");
				GKInstalled = false;
			}
		}
	}
}

BepInEx/plugins/gittywithexcitement-Build_Camera/Build Camera.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Valheim Build Camera")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Valheim Build Camera")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("28173031-3a88-4e18-835e-9cbd815f0588")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Valheim_Build_Camera;

[BepInPlugin("org.gittywithexcitement.plugins.valheim.buildCamera", "Build Camera", "1.6.1")]
[BepInProcess("valheim.exe")]
[HarmonyPatch]
public class Valheim_Build_Camera : BaseUnityPlugin
{
	private struct BuildCameraView
	{
		public float yaw;

		public float pitch;
	}

	private struct NearbyCraftingStation
	{
		public Vector3 position;

		public float distance;

		public float rangeBuild;
	}

	private const string MID = "org.gittywithexcitement.plugins.valheim.buildCamera";

	private const string VERSION = "1.6.1";

	private const string PluginName = "Build Camera";

	private static ConfigFile configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, "Build Camera.cfg"), true);

	private static ConfigEntry<float> distanceCanBuildFromAvatar = configFile.Bind<float>("General", "Distance_Can_Build_From_Avatar", 100f, "Distance from your avatar that you can build or repair. (Valheim default is 8)");

	private static ConfigEntry<float> distanceCanBuildFromWorkbench = configFile.Bind<float>("General", "Distance_Can_Build_From_Workbench", 100f, "Distance from nearest workbench/stonecutter/etc. that you can build or repair. (Valheim default is 20)");

	private static ConfigEntry<float> cameraRangeMultiplier = configFile.Bind<float>("General", "Camera_Range_Multiplier", 1f, "Changes maximum range camera can move away from the build station. 1 means the build station's range, 2 means twice the build station range, etc.");

	private static ConfigEntry<float> cameraMoveSpeedMultiplier = configFile.Bind<float>("General", "Camera_Move_Speed_Multiplier", 3f, "Multiplies the speed at which the build camera pans (i.e. moves around).");

	private static ConfigEntry<bool> moveWithRespectToWorld = configFile.Bind<bool>("General", "Move_With_Respect_To_World", false, "When true, camera panning input (e.g. pressing WASD) moves the camera with respect to the world coordinates. This means that turning the camera has no effect on the direction of movement. For example, pressing W will always move the camera toward the world's 'North', as opposed to the direction the camera is currently facing.");

	private static ConfigEntry<KeyboardShortcut> toggleBuildMode = configFile.Bind<KeyboardShortcut>("Hotkeys", "Toggle_build_mode", new KeyboardShortcut((KeyCode)98, Array.Empty<KeyCode>()), "See https://docs.unity3d.com/ScriptReference/KeyCode.html for the names of all key codes. To add one or more modifier keys, separate them with +, like so: Toggle_build_mode = B + LeftControl");

	private static ConfigEntry<bool> verboseLogging = configFile.Bind<bool>("General", "Verbose_Logging", false, "When true, increases verbosity of logging. Enable this if you're wondering why you're unable to enable the Build Camera.");

	private static Dictionary<Player, bool> inBuildMode = new Dictionary<Player, bool>();

	private static ManualLogSource log;

	private static BuildCameraView buildCameraViewDirection = new BuildCameraView
	{
		pitch = 0f,
		yaw = 0f
	};

	private static readonly string[] toolNames = new string[6] { "$item_hammer", "$item_cultivator", "$item_hoe", "$PlumgaPlantItShovel", "$PlumgaClutterTool", "$ImprovedHammer" };

	private void Awake()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		new Harmony("org.gittywithexcitement.plugins.valheim.buildCamera").PatchAll();
		log = Logger.CreateLogSource("Build Camera");
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(Player), "Awake")]
	public static void Player_Awake(ref float ___m_maxPlaceDistance)
	{
		if (___m_maxPlaceDistance < distanceCanBuildFromAvatar.Value)
		{
			log.LogDebug((object)$"in Player_Awake, changing maxPlaceDistance from {___m_maxPlaceDistance} to {distanceCanBuildFromAvatar.Value}");
			___m_maxPlaceDistance = distanceCanBuildFromAvatar.Value;
		}
		else
		{
			log.LogDebug((object)"Not changing distanceCanBuildFromAvatar (AKA maxPlaceDistance) as it seems another mod has already changed it.");
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(CraftingStation), "Start")]
	public static void CraftingStation_Start(ref CraftingStation __instance, ref float ___m_rangeBuild)
	{
		if (___m_rangeBuild < distanceCanBuildFromWorkbench.Value)
		{
			log.LogDebug((object)$"in CraftingStation_Start, changing rangeBuild from {___m_rangeBuild} to {distanceCanBuildFromWorkbench.Value}");
			___m_rangeBuild = distanceCanBuildFromWorkbench.Value;
		}
		else
		{
			log.LogDebug((object)"Not changing distanceCanBuildFromWorkbench (AKA rangeBuild) as it seems another mod has already changed it.");
		}
	}

	private static void LogWhenVerbose(string s)
	{
		if (verboseLogging.Value)
		{
			((Character)Player.m_localPlayer).Message((MessageType)1, s, 0, (Sprite)null);
			log.LogInfo((object)s);
		}
	}

	private static bool InBuildMode()
	{
		if (Object.op_Implicit((Object)(object)Player.m_localPlayer))
		{
			return inBuildMode[Player.m_localPlayer];
		}
		return false;
	}

	private static void DisableBuildMode()
	{
		inBuildMode[Player.m_localPlayer] = false;
	}

	private static void EnableBuildMode()
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		inBuildMode[Player.m_localPlayer] = true;
		Quaternion rotation = ((Component)((Character)Player.m_localPlayer).m_eye).transform.rotation;
		buildCameraViewDirection.pitch = ((Quaternion)(ref rotation)).eulerAngles.x;
		buildCameraViewDirection.yaw = ((Quaternion)(ref rotation)).eulerAngles.y;
		((Character)Player.m_localPlayer).Message((MessageType)1, "Entering Build Mode.", 0, (Sprite)null);
	}

	private static bool IsLocalPlayer(in Player player)
	{
		if (Object.op_Implicit((Object)(object)Player.m_localPlayer))
		{
			return (Object)(object)player == (Object)(object)Player.m_localPlayer;
		}
		return false;
	}

	private static bool IsTool(in ItemData itemData)
	{
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Invalid comparison between Unknown and I4
		if (toolNames.Contains(itemData?.m_shared.m_name))
		{
			ItemData obj = itemData;
			if (obj == null)
			{
				return false;
			}
			return (int)obj.m_shared.m_itemType == 19;
		}
		return false;
	}

	private static bool ToolIsEquipped(in Player player)
	{
		return IsTool(in ((Humanoid)player).m_rightItem);
	}

	private static bool ShouldDeactivateBuildMode(in Player player)
	{
		return !ToolIsEquipped(in player);
	}

	[HarmonyPatch(typeof(Player), "SetLocalPlayer")]
	[HarmonyPostfix]
	private static void InitializeNotInBuildMode()
	{
		DisableBuildMode();
	}

	[HarmonyPatch(typeof(Player), "Update")]
	[HarmonyPrefix]
	private static void Update_Prefix_Player(ref Player __instance, ref bool __runOriginal)
	{
		if (IsLocalPlayer(in __instance) && InBuildMode())
		{
			if (ShouldDeactivateBuildMode(in __instance))
			{
				DisableBuildMode();
				__runOriginal = true;
				return;
			}
			__runOriginal = false;
			if (((Character)__instance).TakeInput())
			{
				if (Input.GetKeyDown((KeyCode)49))
				{
					__instance.UseHotbarItem(1);
				}
				if (Input.GetKeyDown((KeyCode)50))
				{
					__instance.UseHotbarItem(2);
				}
				if (Input.GetKeyDown((KeyCode)51))
				{
					__instance.UseHotbarItem(3);
				}
				if (Input.GetKeyDown((KeyCode)52))
				{
					__instance.UseHotbarItem(4);
				}
				if (Input.GetKeyDown((KeyCode)53))
				{
					__instance.UseHotbarItem(5);
				}
				if (Input.GetKeyDown((KeyCode)54))
				{
					__instance.UseHotbarItem(6);
				}
				if (Input.GetKeyDown((KeyCode)55))
				{
					__instance.UseHotbarItem(7);
				}
				if (Input.GetKeyDown((KeyCode)56))
				{
					__instance.UseHotbarItem(8);
				}
				if ((ZInput.GetButtonDown("Hide") || ZInput.GetButtonDown("JoyHide")) && (((Humanoid)__instance).GetRightItem() != null || ((Humanoid)__instance).GetLeftItem() != null) && !((Character)__instance).InAttack())
				{
					((Humanoid)__instance).HideHandItems();
				}
				__instance.UpdatePlacement(true, Time.deltaTime);
			}
		}
		else
		{
			__runOriginal = true;
		}
	}

	[HarmonyPatch(typeof(Player), "Update")]
	[HarmonyPostfix]
	private static void Update_Postfix_Player(ref Player __instance)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_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)
		KeyboardShortcut value;
		if (IsLocalPlayer(in __instance))
		{
			value = toggleBuildMode.Value;
			if (((KeyboardShortcut)(ref value)).IsDown() && ((Character)__instance).TakeInput())
			{
				if (!InBuildMode() && ToolIsEquipped(in __instance) && BuildStationInRange(in __instance))
				{
					EnableBuildMode();
					return;
				}
				if (InBuildMode())
				{
					DisableBuildMode();
					return;
				}
			}
		}
		if (!IsLocalPlayer(in __instance))
		{
			return;
		}
		value = toggleBuildMode.Value;
		if (((KeyboardShortcut)(ref value)).IsDown())
		{
			if (!((Character)__instance).TakeInput())
			{
				LogWhenVerbose("Build Mode not enabled because chat, console, menu, inventory, map, or similar is open.");
			}
			else if (!ToolIsEquipped(in __instance))
			{
				LogWhenVerbose("Build Mode not enabled because hammer is not equipped.");
			}
			else if (!BuildStationInRange(in __instance))
			{
				LogWhenVerbose("Build Mode not enabled because no build station (e.g. workbench) is in range.");
			}
		}
	}

	[HarmonyPatch(typeof(PlayerController), "TakeInput")]
	[HarmonyPrefix]
	private static void TakeInput_PlayerController(ref bool __result, ref bool __runOriginal)
	{
		if (InBuildMode())
		{
			__result = false;
			__runOriginal = false;
		}
		else
		{
			__runOriginal = true;
		}
	}

	private static NearbyCraftingStation? GetNearestBuildStation(in Vector3 playerOrCamera)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		if (CraftingStation.m_allStations.Count == 0)
		{
			return null;
		}
		List<NearbyCraftingStation> list = new List<NearbyCraftingStation>();
		foreach (CraftingStation allStation in CraftingStation.m_allStations)
		{
			list.Add(new NearbyCraftingStation
			{
				position = ((Component)allStation).transform.position,
				distance = Vector3.Distance(((Component)allStation).transform.position, playerOrCamera),
				rangeBuild = allStation.m_rangeBuild
			});
		}
		return list.OrderBy((NearbyCraftingStation x) => x.distance).First();
	}

	private static bool BuildStationInRange(in Player player)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		Vector3 playerOrCamera = ((Component)player).transform.position;
		NearbyCraftingStation? nearestBuildStation = GetNearestBuildStation(in playerOrCamera);
		if (nearestBuildStation.HasValue)
		{
			NearbyCraftingStation valueOrDefault = nearestBuildStation.GetValueOrDefault();
			return valueOrDefault.distance <= valueOrDefault.rangeBuild;
		}
		return false;
	}

	private static void StayNearWorkbench(ref GameCamera __instance)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		Vector3 playerOrCamera = ((Component)__instance).transform.position;
		NearbyCraftingStation? nearestBuildStation = GetNearestBuildStation(in playerOrCamera);
		if (nearestBuildStation.HasValue)
		{
			NearbyCraftingStation valueOrDefault = nearestBuildStation.GetValueOrDefault();
			if (valueOrDefault.distance > valueOrDefault.rangeBuild * cameraRangeMultiplier.Value)
			{
				float num = valueOrDefault.distance - valueOrDefault.rangeBuild * cameraRangeMultiplier.Value;
				Vector3 val = valueOrDefault.position - ((Component)__instance).transform.position;
				Vector3 val2 = num * ((Vector3)(ref val)).normalized;
				((Component)__instance).transform.position = ((Component)__instance).transform.position + val2;
			}
		}
		else
		{
			DisableBuildMode();
		}
	}

	private static void StayAboveGround(ref GameCamera __instance)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		float num = default(float);
		if (ZoneSystem.instance.GetGroundHeight(((Component)__instance).transform.position, ref num) && ((Component)__instance).transform.position.y < num)
		{
			Vector3 position = ((Component)__instance).transform.position;
			position.y = num;
			((Component)__instance).transform.position = position;
		}
	}

	private static Quaternion UpdateBuildCameraViewDirection(float dt)
	{
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		buildCameraViewDirection.yaw += PlayerController.m_mouseSens * Input.GetAxis("Mouse X") + ZInput.GetJoyRightStickX() * 110f * dt;
		float num = ((!PlayerController.m_invertMouse) ? 1 : (-1));
		float num2 = buildCameraViewDirection.pitch - num * (PlayerController.m_mouseSens * Input.GetAxis("Mouse Y") - ZInput.GetJoyRightStickY() * 110f * dt);
		buildCameraViewDirection.pitch = Mathf.Clamp(num2, -89f, 89f);
		return Quaternion.Euler(0f, buildCameraViewDirection.yaw, 0f) * Quaternion.Euler(buildCameraViewDirection.pitch, 0f, 0f);
	}

	private static Vector3 UntransformedMovementVector(float dt)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = Vector3.zero;
		if (ZInput.GetButton("Left"))
		{
			val -= Vector3.right;
		}
		if (ZInput.GetButton("Right"))
		{
			val += Vector3.right;
		}
		if (ZInput.GetButton("Forward"))
		{
			val += Vector3.forward;
		}
		if (ZInput.GetButton("Backward"))
		{
			val -= Vector3.forward;
		}
		if (ZInput.GetButton("Jump") || ZInput.GetButton("JoyJump"))
		{
			val += Vector3.up;
		}
		if (ZInput.GetButton("Crouch") || ZInput.GetButton("JoyCrouch"))
		{
			val -= Vector3.up;
		}
		((Vector3)(ref val)).Normalize();
		val += Vector3.right * ZInput.GetJoyLeftStickX(false);
		val += -Vector3.forward * ZInput.GetJoyLeftStickY(true);
		float num = (ZInput.GetButton("Run") ? ((Character)Player.m_localPlayer).m_runSpeed : ((Character)Player.m_localPlayer).m_walkSpeed);
		return val * (dt * num * cameraMoveSpeedMultiplier.Value);
	}

	private static void UpdateBuildCamera(float dt, ref GameCamera __instance)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		if (!Console.IsVisible() && ((Character)Player.m_localPlayer).TakeInput() && !Hud.IsPieceSelectionVisible())
		{
			Vector3 val = UntransformedMovementVector(dt);
			Vector3 val2 = (moveWithRespectToWorld.Value ? val : ((Component)__instance).transform.TransformVector(val));
			Transform transform = ((Component)__instance).transform;
			transform.position += val2;
			StayNearWorkbench(ref __instance);
			StayAboveGround(ref __instance);
			((Component)__instance).transform.rotation = UpdateBuildCameraViewDirection(dt);
		}
	}

	[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
	[HarmonyPrefix]
	private static void UpdateCamera(float dt, ref GameCamera __instance, ref bool __runOriginal)
	{
		if (InBuildMode())
		{
			UpdateBuildCamera(dt, ref __instance);
			__runOriginal = false;
		}
		else
		{
			__runOriginal = true;
		}
	}
}

BepInEx/plugins/GoldenJude-Blacksmiths_tools/BlacksmithTools.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("BlacksmithTools")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("2.0.3.0")]
[assembly: AssemblyInformationalVersion("2.0.3")]
[assembly: AssemblyProduct("BlacksmithTools")]
[assembly: AssemblyTitle("BlacksmithTools")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.3.0")]
[module: UnverifiableCode]
namespace BlacksmithTools;

internal class BodyPartController : MonoBehaviour
{
	public List<PlayerModel> originalModels = new List<PlayerModel>();

	public VisEquipment viseq;

	public void FullUpdate()
	{
		UpdateBodyModel();
	}

	public void UpdateBodyModel()
	{
		if (BodypartSystem.bodypartSettingsAsBones.Keys.Count != BodypartSystem.bodypartSettings.Keys.Count)
		{
			BodypartSystem.PartCfgToBoneindexes();
			BodypartSystem.CleanupCfgs();
		}
		List<int> list = new List<int>();
		int[] equippedHashes = Util.GetEquippedHashes(viseq);
		foreach (int num in equippedHashes)
		{
			foreach (string key in BodypartSystem.bodypartSettingsAsBones.Keys)
			{
				if (StringExtensionMethods.GetStableHashCode(key) == num || StringExtensionMethods.GetStableHashCode(Util.CorrectRRRArmorPrefabName(key)) == num)
				{
					list.AddRange(BodypartSystem.bodypartSettingsAsBones[key].ToArray());
				}
			}
		}
		Util.LogMessage("Hiding " + list.Count + " bones", (LogLevel)8);
		if (list.Count == 0)
		{
			viseq.m_models[viseq.GetModelIndex()].m_mesh = originalModels[viseq.GetModelIndex()].m_mesh;
			return;
		}
		Mesh mesh = originalModels[viseq.GetModelIndex()].m_mesh;
		Mesh val = Amputate(Object.Instantiate<Mesh>(mesh), list.ToArray());
		((Object)val).name = ((Object)mesh).name;
		viseq.m_models[viseq.GetModelIndex()].m_mesh = val;
	}

	private Mesh Amputate(Mesh body, int[] bonesToHide)
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		BoneWeight[] boneWeights = body.boneWeights;
		for (int i = 0; i < body.subMeshCount; i++)
		{
			List<int> list = new List<int>(body.GetTriangles(i));
			int num = 0;
			while (num < list.Count)
			{
				bool flag = false;
				int num2 = 0;
				for (int j = 0; j < 2; j++)
				{
					if (flag)
					{
						break;
					}
					BoneWeight boneWeight = boneWeights[list[num + j]];
					float num3 = Mathf.Max(new float[4]
					{
						((BoneWeight)(ref boneWeight)).weight0,
						((BoneWeight)(ref boneWeight)).weight1,
						((BoneWeight)(ref boneWeight)).weight2,
						((BoneWeight)(ref boneWeight)).weight3
					});
					for (int k = 0; k < 4; k++)
					{
						int boneIndex = GetBoneIndex(boneWeight, k);
						foreach (int num4 in bonesToHide)
						{
							if (flag)
							{
								break;
							}
							if (boneIndex == num4)
							{
								float boneWeight2 = GetBoneWeight(boneWeight, k);
								if (boneWeight2 / num3 > 0.9f && ++num2 == 1)
								{
									flag = true;
									break;
								}
							}
						}
					}
				}
				if (flag)
				{
					list.RemoveAt(num);
					list.RemoveAt(num);
					list.RemoveAt(num);
				}
				else
				{
					num += 3;
				}
			}
			body.SetTriangles(list.ToArray(), i);
		}
		return body;
	}

	private int GetBoneIndex(BoneWeight boneWeight, int bone)
	{
		return bone switch
		{
			0 => ((BoneWeight)(ref boneWeight)).boneIndex0, 
			1 => ((BoneWeight)(ref boneWeight)).boneIndex1, 
			2 => ((BoneWeight)(ref boneWeight)).boneIndex2, 
			3 => ((BoneWeight)(ref boneWeight)).boneIndex3, 
			_ => -1, 
		};
	}

	private float GetBoneWeight(BoneWeight boneWeight, int bone)
	{
		return bone switch
		{
			0 => ((BoneWeight)(ref boneWeight)).weight0, 
			1 => ((BoneWeight)(ref boneWeight)).weight1, 
			2 => ((BoneWeight)(ref boneWeight)).weight2, 
			3 => ((BoneWeight)(ref boneWeight)).weight3, 
			_ => 0f, 
		};
	}

	public void Setup(VisEquipment _viseq)
	{
		viseq = _viseq;
		SaveOriginalModels();
		UpdateBodyModel();
		Util.LogMessage("bodypart controller attached to " + ((Object)viseq).name, (LogLevel)8);
	}

	private void SaveOriginalModels()
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Expected O, but got Unknown
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Expected O, but got Unknown
		for (int i = 0; i < viseq.m_models.Length; i++)
		{
			PlayerModel val = viseq.m_models[i];
			if ((Object)(object)val.m_baseMaterial == (Object)null)
			{
				Util.LogMessage("mat null", (LogLevel)8);
			}
			Material val2 = new Material(val.m_baseMaterial);
			((Object)val2).name = ((Object)val.m_baseMaterial).name;
			if ((Object)(object)val.m_mesh == (Object)null)
			{
				Util.LogMessage("mesh null", (LogLevel)8);
			}
			Mesh val3 = Object.Instantiate<Mesh>(val.m_mesh);
			((Object)val3).name = ((Object)val.m_mesh).name;
			originalModels.Add(new PlayerModel
			{
				m_baseMaterial = val2,
				m_mesh = val3
			});
		}
	}
}
[HarmonyPatch]
public static class BodypartSystem
{
	public enum bodyPart
	{
		Head,
		Torso,
		ArmUpperLeft,
		ArmLowerLeft,
		HandLeft,
		ArmUpperRight,
		ArmLowerRight,
		HandRight,
		LegUpperLeft,
		LegLowerLeft,
		FootLeft,
		LegUpperRight,
		LegLowerRight,
		FootRight,
		All,
		Beard,
		Hair
	}

	public static Dictionary<string, List<bodyPart>> bodypartSettings = new Dictionary<string, List<bodyPart>>();

	public static Dictionary<string, List<int>> bodypartSettingsAsBones = new Dictionary<string, List<int>>();

	[HarmonyPatch(typeof(VisEquipment), "Awake")]
	[HarmonyPostfix]
	private static void VisEqAwakePatch(VisEquipment __instance)
	{
		if (Main.bodyHidingEnabled.Value && __instance.m_isPlayer)
		{
			SkinnedMeshRenderer bodyModel = __instance.m_bodyModel;
			if (!((Object)(object)((bodyModel != null) ? bodyModel.sharedMesh : null) == (Object)null) && __instance.m_bodyModel.sharedMesh.isReadable)
			{
				BodyPartController bodyPartController = ((Component)__instance).gameObject.AddComponent<BodyPartController>();
				bodyPartController.Setup(__instance);
			}
		}
	}

	public static void BindConfigs()
	{
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Expected O, but got Unknown
		string[] files = Directory.GetFiles(Paths.ConfigPath);
		string[] array = files;
		foreach (string text in array)
		{
			string fileName = Path.GetFileName(text);
			if (!fileName.StartsWith("bsmith."))
			{
				continue;
			}
			string text2 = fileName.Remove(0, 7);
			text2 = text2.Remove(text2.Length - 4, 4);
			Util.LogMessage("Loaded configuration file for " + text2, (LogLevel)8);
			if (bodypartSettingsAsBones.ContainsKey(text2))
			{
				return;
			}
			bodypartSettingsAsBones.Add(text2, new List<int>());
			ConfigFile val = new ConfigFile(text, true);
			ConfigEntry<string> val2 = val.Bind<string>("Body Parts", "List", "", "List of body parts to hide, delimited by a semilocor. List of valid values on mod page");
			string[] array2 = val2.Value.Split(new char[1] { ';' });
			for (int j = 0; j < array2.Length; j++)
			{
				bodypartSettingsAsBones[text2].AddRange(Util.BodyPartToBoneIndexes(array2[j]));
			}
			ConfigEntry<string> val3 = val.Bind<string>("Body Parts", "Bone List", "", "List of bone indexes, body model geometry weighted to these bones will be hidden, delimited by a semilocor. List of valid values on mod page");
			string[] array3 = val3.Value.Split(new char[1] { ';' });
			for (int k = 0; k < array3.Length; k++)
			{
				if (int.TryParse(array3[k], out var result))
				{
					bodypartSettingsAsBones[text2].Add(result);
				}
			}
			Util.LogMessage(bodypartSettingsAsBones[text2].Count + " bones for " + text2, (LogLevel)8);
		}
		PartCfgToBoneindexes();
		CleanupCfgs();
	}

	public static void PartCfgToBoneindexes()
	{
		foreach (string key in bodypartSettings.Keys)
		{
			if (!bodypartSettingsAsBones.ContainsKey(key))
			{
				bodypartSettingsAsBones.Add(key, new List<int>());
			}
			bodypartSettingsAsBones[key].AddRange(Util.BodyPartToBoneIndexes(bodypartSettings[key].ToArray()));
		}
	}

	public static void CleanupCfgs()
	{
		foreach (KeyValuePair<string, List<bodyPart>> bodypartSetting in bodypartSettings)
		{
			bodypartSettingsAsBones[bodypartSetting.Key] = new List<int>(bodypartSettingsAsBones[bodypartSetting.Key].Distinct().ToArray());
		}
	}

	private static void EquipmentChanged(VisEquipment viseq)
	{
		if (Main.bodyHidingEnabled.Value)
		{
			((Component)viseq).GetComponent<BodyPartController>()?.FullUpdate();
			Util.LogMessage("Equipment changed ", (LogLevel)8);
		}
	}

	[HarmonyPatch(typeof(VisEquipment), "SetRightHandEquipped")]
	[HarmonyPostfix]
	private static void SetRightHandPatch(VisEquipment __instance, bool __result)
	{
		if (__result)
		{
			EquipmentChanged(__instance);
		}
	}

	[HarmonyPatch(typeof(VisEquipment), "SetLeftHandEquipped")]
	[HarmonyPostfix]
	private static void SetLeftHandPatch(VisEquipment __instance, bool __result)
	{
		if (__result)
		{
			EquipmentChanged(__instance);
		}
	}

	[HarmonyPatch(typeof(VisEquipment), "SetChestEquipped")]
	[HarmonyPostfix]
	private static void SetChestPatch(VisEquipment __instance, bool __result, int hash)
	{
		if (__result)
		{
			EquipmentChanged(__instance);
		}
	}

	[HarmonyPatch(typeof(VisEquipment), "SetLegEquipped")]
	[HarmonyPostfix]
	private static void SetLegPatch(VisEquipment __instance, bool __result, int hash)
	{
		if (__result)
		{
			EquipmentChanged(__instance);
		}
	}

	[HarmonyPatch(typeof(VisEquipment), "SetHelmetEquipped")]
	[HarmonyPostfix]
	private static void SetHelmetPatch(VisEquipment __instance, bool __result)
	{
		if (__result)
		{
			EquipmentChanged(__instance);
		}
	}

	[HarmonyPatch(typeof(VisEquipment), "SetShoulderEquipped")]
	[HarmonyPostfix]
	private static void SetShoulderPtach(VisEquipment __instance, bool __result)
	{
		if (__result)
		{
			EquipmentChanged(__instance);
		}
	}

	[HarmonyPatch(typeof(VisEquipment), "SetUtilityEquipped")]
	[HarmonyPostfix]
	private static void SetUtilityPatch(VisEquipment __instance, bool __result)
	{
		if (__result)
		{
			EquipmentChanged(__instance);
		}
	}
}
[HarmonyPatch]
public static class BoneReorder
{
	[HarmonyPatch(typeof(VisEquipment), "AttachItem")]
	[HarmonyPostfix]
	private static void AttachItemPatch(VisEquipment __instance, GameObject __result, int itemHash)
	{
		if (Main.reorderEnabled.Value && !((Object)(object)__result == (Object)null) && ((Object)__result).name.StartsWith("attach_skin") && (Object)(object)ObjectDB.instance.GetItemPrefab(itemHash) != (Object)null)
		{
			SetSMRBones(__instance, __result, itemHash);
		}
	}

	[HarmonyPatch(typeof(VisEquipment), "AttachArmor")]
	[HarmonyPostfix]
	private static void AttachArmorPatch(VisEquipment __instance, List<GameObject> __result, int itemHash)
	{
		if (!Main.reorderEnabled.Value)
		{
			return;
		}
		foreach (GameObject item in __result)
		{
			if (((Object)item).name.StartsWith("attach_skin"))
			{
				SetSMRBones(__instance, item, itemHash);
			}
		}
	}

	public static void SetSMRBones(VisEquipment ve, GameObject instance, int hash)
	{
		Util.LogMessage("Reordering bones", (LogLevel)8);
		try
		{
			SkinnedMeshRenderer componentInChildren = instance.GetComponentInChildren<SkinnedMeshRenderer>();
			SkinnedMeshRenderer[] componentsInChildren = instance.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			SkinnedMeshRenderer[] array = componentsInChildren;
			foreach (SkinnedMeshRenderer smr in array)
			{
				SetBones(smr, GetBoneNames(componentInChildren), ve.m_bodyModel.rootBone);
			}
		}
		catch (Exception ex)
		{
			Util.LogMessage(ex.Message, (LogLevel)2);
		}
	}

	public static string[] GetBoneNames(SkinnedMeshRenderer smr)
	{
		List<string> list = new List<string>();
		Transform[] bones = smr.bones;
		foreach (Transform val in bones)
		{
			list.Add(((Object)val).name);
		}
		return list.ToArray();
	}

	public static void SetBones(SkinnedMeshRenderer smr, string[] boneNames, Transform skeletonRoot)
	{
		Transform[] array = (Transform[])(object)new Transform[smr.bones.Length];
		for (int i = 0; i < array.Length; i++)
		{
			array[i] = Util.FindInChildren(skeletonRoot, boneNames[i]);
		}
		smr.bones = array;
		smr.rootBone = skeletonRoot;
	}
}
[BepInPlugin("GoldenJude_BlacksmithTools", "BlacksmithTools", "2.0.1")]
public class Main : BaseUnityPlugin
{
	public const string MODNAME = "BlacksmithTools";

	public const string AUTHOR = "GoldenJude";

	public const string GUID = "GoldenJude_BlacksmithTools";

	public const string VERSION = "2.0.1";

	public static ManualLogSource log;

	public static Harmony harmony;

	public static Assembly assembly;

	public static string modFolder;

	public static ConfigFile configFile;

	public static ConfigEntry<bool> reorderEnabled;

	public static ConfigEntry<bool> bodyHidingEnabled;

	public static ConfigEntry<bool> loggingEnabled;

	public Main()
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Expected O, but got Unknown
		log = ((BaseUnityPlugin)this).Logger;
		harmony = new Harmony("GoldenJude_BlacksmithTools");
		assembly = Assembly.GetExecutingAssembly();
		modFolder = Path.GetDirectoryName(assembly.Location);
	}

	public void Start()
	{
		harmony.PatchAll(assembly);
	}

	public void Awake()
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Expected O, but got Unknown
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Expected O, but got Unknown
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Expected O, but got Unknown
		configFile = ((BaseUnityPlugin)this).Config;
		reorderEnabled = configFile.Bind<bool>("bone reorder", "enabled", true, new ConfigDescription("", (AcceptableValueBase)null, Array.Empty<object>()));
		bodyHidingEnabled = configFile.Bind<bool>("bodypart hiding", "enabled", true, new ConfigDescription("", (AcceptableValueBase)null, Array.Empty<object>()));
		loggingEnabled = configFile.Bind<bool>("logging", "enabled", false, new ConfigDescription("", (AcceptableValueBase)null, Array.Empty<object>()));
		if (bodyHidingEnabled.Value)
		{
			BodypartSystem.BindConfigs();
		}
	}
}
public static class Util
{
	public static Transform FindInChildrenWc(Transform trans, string name)
	{
		if (((Object)trans).name.ToLower().Contains(name.ToLower()))
		{
			return trans;
		}
		for (int i = 0; i < trans.childCount; i++)
		{
			Transform val = FindInChildrenWc(trans.GetChild(i), name);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
		}
		return null;
	}

	public static Transform FindInChildren(Transform trans, string name)
	{
		if (((Object)trans).name == name)
		{
			return trans;
		}
		for (int i = 0; i < trans.childCount; i++)
		{
			Transform val = FindInChildren(trans.GetChild(i), name);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
		}
		return null;
	}

	public static List<BodypartSystem.bodyPart> StringToParts(string partstring)
	{
		List<BodypartSystem.bodyPart> list = new List<BodypartSystem.bodyPart>();
		string[] array = partstring.Split(new char[1] { ';' });
		foreach (string value in array)
		{
			if (Enum.TryParse<BodypartSystem.bodyPart>(value, out var result) && !list.Contains(result))
			{
				list.Add(result);
			}
		}
		return list;
	}

	public static string CorrectRRRArmorPrefabName(string name)
	{
		string[] array = name.Split(new char[1] { '@' });
		if (array.Length > 1)
		{
			return array[1];
		}
		return name;
	}

	public static string[] GetEquippedItemNames(VisEquipment ve, ObjectDB db)
	{
		if ((Object)(object)ve == (Object)null || (Object)(object)db == (Object)null)
		{
			return new string[0];
		}
		List<string> list = new List<string>();
		int[] equippedHashes = GetEquippedHashes(ve);
		foreach (int num in equippedHashes)
		{
			GameObject itemPrefab = db.GetItemPrefab(num);
			if (!((Object)(object)itemPrefab == (Object)null))
			{
				list.Add(((Object)itemPrefab).name);
			}
		}
		return list.ToArray();
	}

	public static int[] GetEquippedHashes(VisEquipment ve)
	{
		if ((Object)(object)ve == (Object)null)
		{
			return new int[0];
		}
		List<int> list = new List<int>();
		if (ve.m_currentLeftItemHash != 0)
		{
			list.Add(ve.m_currentLeftItemHash);
		}
		if (ve.m_currentRightItemHash != 0)
		{
			list.Add(ve.m_currentRightItemHash);
		}
		if (ve.m_currentChestItemHash != 0)
		{
			list.Add(ve.m_currentChestItemHash);
		}
		if (ve.m_currentLegItemHash != 0)
		{
			list.Add(ve.m_currentLegItemHash);
		}
		if (ve.m_currentHelmetItemHash != 0)
		{
			list.Add(ve.m_currentHelmetItemHash);
		}
		if (ve.m_currentShoulderItemHash != 0)
		{
			list.Add(ve.m_currentShoulderItemHash);
		}
		if (ve.m_currentBeardItemHash != 0)
		{
			list.Add(ve.m_currentBeardItemHash);
		}
		if (ve.m_currentHairItemHash != 0)
		{
			list.Add(ve.m_currentHairItemHash);
		}
		if (ve.m_currentUtilityItemHash != 0)
		{
			list.Add(ve.m_currentUtilityItemHash);
		}
		if (ve.m_currentLeftBackItemHash != 0)
		{
			list.Add(ve.m_currentLeftBackItemHash);
		}
		if (ve.m_currentRightBackItemHash != 0)
		{
			list.Add(ve.m_currentRightBackItemHash);
		}
		return list.ToArray();
	}

	public static void LogMessage(string message, LogLevel level = 8)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Invalid comparison between Unknown and I4
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Invalid comparison between Unknown and I4
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Invalid comparison between Unknown and I4
		if (Main.loggingEnabled.Value)
		{
			if ((int)level == 8)
			{
				Main.log.LogMessage((object)message);
			}
			if ((int)level == 4)
			{
				Main.log.LogWarning((object)message);
			}
			if ((int)level == 2)
			{
				Main.log.LogError((object)message);
			}
		}
	}

	public static int[] BodyPartToBoneIndexes(string part)
	{
		if (Enum.TryParse<BodypartSystem.bodyPart>(part, out var result))
		{
			return BodyPartToBoneIndexes(result);
		}
		return new int[1] { -100 };
	}

	public static int[] BodyPartToBoneIndexes(BodypartSystem.bodyPart[] part)
	{
		List<int> list = new List<int>();
		for (int i = 0; i < part.Length; i++)
		{
			list.AddRange(BodyPartToBoneIndexes(part[i]));
		}
		return list.ToArray();
	}

	public static int[] BodyPartToBoneIndexes(BodypartSystem.bodyPart part)
	{
		return part switch
		{
			BodypartSystem.bodyPart.All => new int[1] { -1 }, 
			BodypartSystem.bodyPart.Head => new int[3] { 4, 5, 6 }, 
			BodypartSystem.bodyPart.Torso => new int[6] { 0, 1, 2, 3, 7, 26 }, 
			BodypartSystem.bodyPart.ArmUpperLeft => new int[1] { 8 }, 
			BodypartSystem.bodyPart.ArmLowerLeft => new int[1] { 9 }, 
			BodypartSystem.bodyPart.HandLeft => new int[17]
			{
				10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
				20, 21, 22, 23, 24, 25, 26
			}, 
			BodypartSystem.bodyPart.ArmUpperRight => new int[1] { 27 }, 
			BodypartSystem.bodyPart.ArmLowerRight => new int[1] { 28 }, 
			BodypartSystem.bodyPart.HandRight => new int[16]
			{
				29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
				39, 40, 41, 42, 43, 44
			}, 
			BodypartSystem.bodyPart.LegUpperLeft => new int[1] { 45 }, 
			BodypartSystem.bodyPart.LegLowerLeft => new int[1] { 46 }, 
			BodypartSystem.bodyPart.FootLeft => new int[2] { 47, 48 }, 
			BodypartSystem.bodyPart.LegUpperRight => new int[1] { 49 }, 
			BodypartSystem.bodyPart.LegLowerRight => new int[1] { 50 }, 
			BodypartSystem.bodyPart.FootRight => new int[2] { 51, 52 }, 
			_ => new int[1] { -100 }, 
		};
	}
}

BepInEx/plugins/GoldenJude-Judes_Equipment/JudesEquipment.dll

Decompiled 8 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using JudesEquipment.ArmorSets;
using JudesEquipment.Configuration;
using Microsoft.CodeAnalysis;
using ServerSync;
using UnityEngine;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("JudesEquipment")]
[assembly: AssemblyDescription("")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("JudesEquipment")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f33c90df-d8e2-403e-b94c-001a58ff0821")]
[assembly: AssemblyFileVersion("2.2.3")]
[assembly: AssemblyCompany("")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.2.3.0")]
[module: UnverifiableCode]
namespace JudesEquipment
{
	public static class Sync
	{
		public static ConfigSync configSync = new ConfigSync("GoldenJude_JudesEquipment")
		{
			DisplayName = "Jude's Equipment",
			CurrentVersion = "2.2.3",
			MinimumRequiredVersion = "2.2.3"
		};

		public static ConfigEntry<T> SyncConfig<T>(ConfigEntry<T> entry)
		{
			SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(entry);
			syncedConfigEntry.SynchronizedConfig = true;
			return entry;
		}
	}
	[HarmonyPatch]
	internal static class GenderSwitchPatch
	{
		[HarmonyPatch(typeof(VisEquipment), "AttachArmor")]
		[HarmonyPostfix]
		public static void PostFix(VisEquipment __instance, ref List<GameObject> __result)
		{
			SetEquipmentGender(ref __result, __instance);
		}

		public static void SetEquipmentGender(ref List<GameObject> equip, VisEquipment viseq)
		{
			foreach (GameObject item in equip)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				for (int i = 0; i < item.transform.childCount; i++)
				{
					Transform child = item.transform.GetChild(i);
					if (!((Object)(object)child == (Object)null))
					{
						if (((Object)((Component)child).gameObject).name == "female" && viseq.GetModelIndex() == 0)
						{
							((Component)child).gameObject.SetActive(false);
						}
						if (((Object)((Component)child).gameObject).name == "male" && viseq.GetModelIndex() == 1)
						{
							((Component)child).gameObject.SetActive(false);
						}
					}
				}
			}
		}
	}
	public static class ItemManager
	{
		public static Transform cloneContainer;

		public static List<PrefabConfig> prefabs = new List<PrefabConfig>();

		public static List<StatusEffect> customSEs = new List<StatusEffect>();

		public static List<BlacksmithsToolsConfig> bsmithCfgs = new List<BlacksmithsToolsConfig>();

		public static Dictionary<string, Dictionary<string, string>> colorConfig = new Dictionary<string, Dictionary<string, string>>
		{
			{
				"ArmorBarbarianBronzeHelmetJD",
				new Dictionary<string, string>
				{
					{ "Color 1", "#FF892A" },
					{ "Color 2", "#FFFFFF" }
				}
			},
			{
				"ArmorBarbarianBronzeChestJD",
				new Dictionary<string, string>
				{
					{ "Color 1", "#FF892A" },
					{ "Color 2", "#FFFFFF" }
				}
			},
			{
				"ArmorBarbarianBronzeLegsJD",
				new Dictionary<string, string>
				{
					{ "Color 1", "#FF892A" },
					{ "Color 2", "#FFFFFF" }
				}
			},
			{
				"ArmorWarriorHelmet",
				new Dictionary<string, string> { { "Color 1", "#FF892A" } }
			},
			{
				"ArmorWarriorChest",
				new Dictionary<string, string> { { "Color 1", "#FF892A" } }
			},
			{
				"ArmorPlateIronHelmetJD",
				new Dictionary<string, string> { { "Color 1", "#FFFFFF" } }
			},
			{
				"ArmorPlateIronChestJD",
				new Dictionary<string, string> { { "Color 1", "#FFFFFF" } }
			},
			{
				"ArmorPlateIronLegsJD",
				new Dictionary<string, string> { { "Color 1", "#FFFFFF" } }
			},
			{
				"ArmorDragonslayerHelmet",
				new Dictionary<string, string> { { "Color 1", "#373737" } }
			},
			{
				"ArmorDragonslayerChest",
				new Dictionary<string, string> { { "Color 1", "#373737" } }
			},
			{
				"ArmorDragonslayerLegs",
				new Dictionary<string, string> { { "Color 1", "#373737" } }
			},
			{
				"ArmorWandererChest",
				new Dictionary<string, string> { { "Color 1", "#FFFFFF" } }
			},
			{
				"ArmorWandererLegs",
				new Dictionary<string, string> { { "Color 1", "#FFFFFF" } }
			},
			{
				"ArmorBlackmetalgarbHelmet",
				new Dictionary<string, string> { { "Color 1", "#264C35" } }
			},
			{
				"ArmorBlackmetalgarbChest",
				new Dictionary<string, string> { { "Color 1", "#264C35" } }
			},
			{
				"ArmorBlackmetalgarbLegs",
				new Dictionary<string, string> { { "Color 1", "#264C35" } }
			},
			{
				"ArmorSerpentHelmet",
				new Dictionary<string, string>
				{
					{ "Color 1", "#264C35" },
					{ "Color 2", "#FFFFFF" }
				}
			},
			{
				"ArmorSerpentChest",
				new Dictionary<string, string>
				{
					{ "Color 1", "#264C35" },
					{ "Color 2", "#FFFFFF" }
				}
			},
			{
				"ArmorSerpentLegs",
				new Dictionary<string, string>
				{
					{ "Color 1", "#264C35" },
					{ "Color 2", "#FFFFFF" }
				}
			},
			{
				"ArmorMistlandsHelmet",
				new Dictionary<string, string>
				{
					{ "Color 1", "#545454" },
					{ "Emission color", "#BF3000" }
				}
			},
			{
				"ArmorMistlandsChest",
				new Dictionary<string, string>
				{
					{ "Color 1", "#545454" },
					{ "Emission color", "#BF3000" }
				}
			},
			{
				"ArmorMistlandsLegs",
				new Dictionary<string, string>
				{
					{ "Color 1", "#545454" },
					{ "Emission color", "#BF3000" }
				}
			}
		};

		public static readonly List<string> allPrefabs = new List<string>
		{
			"ArmorNobleHelmet", "ArmorNobleChest", "ArmorNobleLegs", "ArmorNobleCape", "ArmorBarbarianBronzeHelmetJD", "ArmorBarbarianBronzeChestJD", "ArmorBarbarianBronzeLegsJD", "ArmorBarbarianCapeJD", "ArmorWarriorHelmet", "ArmorWarriorChest",
			"ArmorWarriorLegs", "ArmorPlateIronHelmetJD", "ArmorPlateIronChestJD", "ArmorPlateIronLegsJD", "ArmorPlateCape", "ArmorDragonslayerHelmet", "ArmorDragonslayerChest", "ArmorDragonslayerLegs", "ArmorWandererHelmet", "ArmorWandererChest",
			"ArmorWandererLegs", "ArmorWandererCape", "ArmorBlackmetalgarbHelmet", "ArmorBlackmetalgarbChest", "ArmorBlackmetalgarbLegs", "ArmorSerpentHelmet", "ArmorSerpentChest", "ArmorSerpentLegs", "ArmorSerpentCape", "ArmorMistlandsHelmet",
			"ArmorMistlandsChest", "ArmorMistlandsLegs", "BackpackSimple", "BackpackHeavy"
		};

		public static Transform GetCloneHolder()
		{
			if ((Object)(object)cloneContainer == (Object)null)
			{
				cloneContainer = GameObject.CreatePrimitive((PrimitiveType)3).transform;
				Object.DontDestroyOnLoad((Object)(object)cloneContainer);
				((Component)cloneContainer).gameObject.SetActive(false);
				return cloneContainer;
			}
			return cloneContainer;
		}

		public static void AddItemsToDBs(ObjectDB odb)
		{
			LoadPrefabsFromBundle();
			foreach (PrefabConfig prefab in prefabs)
			{
				if ((Object)(object)prefab.GetPrefab() == (Object)null)
				{
					continue;
				}
				if (!odb.m_itemByHash.ContainsKey(StringExtensionMethods.GetStableHashCode(((Object)prefab.GetPrefab()).name)))
				{
					odb.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(((Object)prefab.GetPrefab()).name), prefab.GetPrefab());
				}
				if (!odb.m_items.Contains(prefab.GetPrefab()))
				{
					odb.m_items.Add(prefab.GetPrefab());
				}
				if ((Object)(object)ZNetScene.instance != (Object)null)
				{
					if (!ZNetScene.instance.m_prefabs.Contains(prefab.GetPrefab()))
					{
						ZNetScene.instance.m_prefabs.Add(prefab.GetPrefab());
					}
					if (!ZNetScene.instance.m_namedPrefabs.ContainsKey(StringExtensionMethods.GetStableHashCode(((Object)prefab.GetPrefab()).name)))
					{
						ZNetScene.instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)prefab.GetPrefab()).name), prefab.GetPrefab());
					}
				}
			}
			customSEs.ForEach(delegate(StatusEffect se)
			{
				if (!odb.m_StatusEffects.Contains(se))
				{
					odb.m_StatusEffects.Add(se);
				}
			});
		}

		public static void InsertBsmithToolsCfgs()
		{
			if (!Main.bsmithAvailable)
			{
				return;
			}
			Type type = Type.GetType("BlacksmithTools.BodypartSystem,BlacksmithTools");
			FieldInfo field = type.GetField("bodypartSettingsAsBones");
			Dictionary<string, List<int>> dictionary = (Dictionary<string, List<int>>)field.GetValue(field);
			foreach (BlacksmithsToolsConfig bsmithCfg in bsmithCfgs)
			{
				if (dictionary.ContainsKey(bsmithCfg.itemName))
				{
					dictionary[bsmithCfg.itemName] = new List<int>(bsmithCfg.bonesToHide);
				}
				else
				{
					dictionary.Add(bsmithCfg.itemName, new List<int>(bsmithCfg.bonesToHide));
				}
			}
		}

		private static void LoadPrefabsFromBundle()
		{
			AssetBundle bundle = Util.LoadBundle("judeequipment");
			prefabs.Clear();
			allPrefabs.ForEach(delegate(string _prefab)
			{
				prefabs.Add(new PrefabConfig
				{
					prefab = bundle.LoadAsset<GameObject>(_prefab)
				});
			});
			bundle.Unload(false);
		}
	}
	public static class LocalizationManager
	{
		public static Localization localizationInstance;

		public static readonly List<string> languages = new List<string>
		{
			"English", "Swedish", "French", "Italian", "German", "Spanish", "Russian", "Romanian", "Bulgarian", "Macedonian",
			"Finnish", "Danish", "Norwegian", "Icelandic", "Turkish", "Lithuanian", "Czech", "Hungarian", "Slovak", "Polish",
			"Dutch", "Portuguese_European", "Portuguese_Brazilian", "Chinese", "Japanese", "Korean", "Hindi", "Thai", "Abenaki", "Croatian",
			"Georgian", "Greek", "Serbian", "Ukrainian"
		};

		public static void LoadLocalization()
		{
			List<string> list = Directory.GetFiles(Paths.ConfigPath, "GoldenJude_JudesEquipment_Localization.yml", SearchOption.AllDirectories).ToList();
			if (list.Count == 0)
			{
				File.WriteAllText(Path.Combine(Paths.ConfigPath, "GoldenJude_JudesEquipment_Localization.yml"), new SerializerBuilder().Build().Serialize(Main.localization));
				return;
			}
			try
			{
				IDeserializer deserializer = new DeserializerBuilder().Build();
				Dictionary<string, Dictionary<string, string>> dictionary = new Dictionary<string, Dictionary<string, string>>();
				dictionary = deserializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(File.ReadAllText(list[0]));
				Main.localization.Clear();
				Main.localization = dictionary;
				Main.syncedLocalization.Value = new SerializerBuilder().Build().Serialize(dictionary);
			}
			catch (Exception ex)
			{
				Main.log.LogWarning((object)"An error occured when loading localization");
				Main.log.LogWarning((object)ex.Message);
				Main.log.LogWarning((object)ex.StackTrace);
			}
		}

		public static void InsertLocalization()
		{
			if (localizationInstance == null)
			{
				return;
			}
			string key = localizationInstance.GetSelectedLanguage();
			if (!Main.localization.ContainsKey(key))
			{
				key = "English";
			}
			if (!Main.localization.ContainsKey(key))
			{
				return;
			}
			foreach (KeyValuePair<string, string> item in Main.localization[key])
			{
				localizationInstance.m_translations.Remove(item.Key);
				localizationInstance.m_translations.Add(item.Key, item.Value);
			}
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("GoldenJude_JudesEquipment", "JudesEquipment", "2.2.3")]
	public class Main : BaseUnityPlugin
	{
		public const string MODNAME = "JudesEquipment";

		public const string AUTHOR = "GoldenJude";

		public const string GUID = "GoldenJude_JudesEquipment";

		public const string VERSION = "2.2.3";

		public static ManualLogSource log;

		internal readonly Harmony harmony;

		public static Assembly assembly;

		public const string bundleName = "judeequipment";

		public const string itemConfigName = "GoldenJude_JudesEquipment_ItemConfig.yml";

		public const string localizationconfigName = "GoldenJude_JudesEquipment_Localization.yml";

		public const string colorConfigName = "GoldenJude_JudesEquipment_Colors.yml";

		public static CustomSyncedValue<string> syncedModConfig = new CustomSyncedValue<string>(Sync.configSync, Path.GetFileNameWithoutExtension("GoldenJude_JudesEquipment_ItemConfig.yml"));

		public static CustomSyncedValue<string> syncedLocalization = new CustomSyncedValue<string>(Sync.configSync, Path.GetFileNameWithoutExtension("GoldenJude_JudesEquipment_Localization.yml"));

		public static SyncedConfigEntry<int> lockingConfig;

		public static ConfigEntry<bool> neutralMetals;

		public static ConfigEntry<bool> smoothTextures;

		public static Shader creatureShader;

		public static bool bsmithAvailable = false;

		public static bool hugosCollidersAvaiable = false;

		public static ItemConfig modConfig = new ItemConfig();

		public static Dictionary<string, Dictionary<string, string>> localization = new Dictionary<string, Dictionary<string, string>> { 
		{
			"English",
			new Dictionary<string, string>()
		} };

		public static FileSystemWatcher fsw = new FileSystemWatcher
		{
			Path = Paths.ConfigPath,
			IncludeSubdirectories = true,
			EnableRaisingEvents = true
		};

		public Main()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			log = ((BaseUnityPlugin)this).Logger;
			harmony = new Harmony("GoldenJude_JudesEquipment");
			assembly = Assembly.GetExecutingAssembly();
		}

		public void Start()
		{
			harmony.PatchAll(assembly);
			bsmithAvailable = Util.IsModAvailable("BlacksmithTools", "2.0.0");
			hugosCollidersAvaiable = Util.IsModAvailable("More Player Cloth Colliders", "3.0.0");
			lockingConfig = Sync.configSync.AddLockingConfigEntry<int>(((BaseUnityPlugin)this).Config.Bind<int>("Sync", "Sync configs", 1, "1 = enabled, 0 = disabled"));
			neutralMetals = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "Neutral metals", false, "Makes all metals a neutral grey");
			smoothTextures = ((BaseUnityPlugin)this).Config.Bind<bool>("Appearance", "Smooth textures", false, "Removes pixelization filter on all textures, overrides color config");
			CreateDefaultLocalization();
			LocalizationManager.LoadLocalization();
			LoadColorConfig();
			syncedModConfig.ValueChanged += delegate
			{
				modConfig = new DeserializerBuilder().Build().Deserialize<ItemConfig>(syncedModConfig.Value);
				modConfig.ApplyArmorConfigs();
				modConfig.ApplyRecipeConfigs();
				modConfig.ApplySetEffects();
			};
			syncedLocalization.ValueChanged += delegate
			{
				localization = new DeserializerBuilder().Build().Deserialize<Dictionary<string, Dictionary<string, string>>>(syncedLocalization.Value);
				LocalizationManager.InsertLocalization();
			};
			fsw.Changed += delegate(object sender, FileSystemEventArgs e)
			{
				if (Sync.configSync.IsSourceOfTruth)
				{
					if (Path.GetFileName(e.FullPath) == "GoldenJude_JudesEquipment_ItemConfig.yml")
					{
						LoadModConfig();
					}
					if (Path.GetFileName(e.FullPath) == "GoldenJude_JudesEquipment_Localization.yml")
					{
						LocalizationManager.LoadLocalization();
					}
				}
			};
		}

		public static void LoadColorConfig()
		{
			List<string> list = Directory.GetFiles(Paths.ConfigPath, "GoldenJude_JudesEquipment_Colors.yml", SearchOption.AllDirectories).ToList();
			if (list.Count == 0)
			{
				File.WriteAllText(Path.Combine(Paths.ConfigPath, "GoldenJude_JudesEquipment_Colors.yml"), new SerializerBuilder().Build().Serialize(ItemManager.colorConfig));
				return;
			}
			Dictionary<string, Dictionary<string, string>> dictionary = new Dictionary<string, Dictionary<string, string>>();
			try
			{
				dictionary = new DeserializerBuilder().Build().Deserialize<Dictionary<string, Dictionary<string, string>>>(File.ReadAllText(list[0]));
				ItemManager.colorConfig = dictionary;
			}
			catch (Exception ex)
			{
				log.LogWarning((object)"An error occured when loading GoldenJude_JudesEquipment_Colors.yml, will use default values");
				log.LogWarning((object)ex.Message);
				log.LogWarning((object)ex.StackTrace);
			}
		}

		public static void LoadModConfig()
		{
			List<string> list = Directory.GetFiles(Paths.ConfigPath, "GoldenJude_JudesEquipment_ItemConfig.yml", SearchOption.AllDirectories).ToList();
			if (list.Count == 0)
			{
				File.WriteAllText(Path.Combine(Paths.ConfigPath, "GoldenJude_JudesEquipment_ItemConfig.yml"), new SerializerBuilder().Build().Serialize(modConfig));
				return;
			}
			ItemConfig graph = new ItemConfig();
			try
			{
				graph = new DeserializerBuilder().Build().Deserialize<ItemConfig>(File.ReadAllText(list[0]));
			}
			catch (Exception ex)
			{
				log.LogWarning((object)"An error occured when loading GoldenJude_JudesEquipment_ItemConfig.yml, will use default values");
				log.LogWarning((object)ex.Message);
				log.LogWarning((object)ex.StackTrace);
			}
			syncedModConfig.Value = new SerializerBuilder().Build().Serialize(graph);
			try
			{
				if (!ConfigHasAllArmors(File.ReadAllText(list[0])))
				{
					File.WriteAllText(Path.Combine(Paths.ConfigPath, "GoldenJude_JudesEquipment_ItemConfig.yml"), new SerializerBuilder().Build().Serialize(modConfig));
				}
			}
			catch (Exception ex2)
			{
				log.LogWarning((object)("failed to validate if item config fil contains all sets, error: " + Environment.NewLine + ex2.Message));
			}
		}

		private static bool ConfigHasAllArmors(string configJson)
		{
			List<FieldInfo> source = typeof(ItemConfig).GetFields().ToList();
			List<FieldInfo> list = source.Where((FieldInfo field) => field.CustomAttributes.First((CustomAttributeData att) => att.AttributeType == typeof(YamlMemberAttribute)) != null).ToList();
			foreach (FieldInfo item in list)
			{
				CustomAttributeData customAttributeData = item.CustomAttributes.First((CustomAttributeData att) => att.AttributeType == typeof(YamlMemberAttribute));
				string value = (string)customAttributeData.NamedArguments.First((CustomAttributeNamedArgument na) => na.MemberName == "Alias").TypedValue.Value;
				if (!configJson.Contains(value))
				{
					return false;
				}
			}
			return true;
		}

		private void CreateDefaultLocalization()
		{
			localization["English"].Add("ArmorNobleHelmet", "Fur hat");
			localization["English"].Add("ArmorNobleHelmet_description", "Fashionable hat with fur lining");
			localization["English"].Add("ArmorNobleChest", "Noble's banner garb");
			localization["English"].Add("ArmorNobleChest_description", "A garb stitched together from banners torn from your burial chamber, a good alternative to roaming Valheim bare");
			localization["English"].Add("ArmorNobleLegs", "Noble's pants");
			localization["English"].Add("ArmorNobleLegs_description", "Worn, loose pants from a past life where one could afford to feast more often");
			localization["English"].Add("ArmorNobleCape", "Vegvisir cape");
			localization["English"].Add("ArmorNobleCape_description", "Cape fashioned from a vegvisir banner");
			localization["English"].Add("ArmorBarbarianBronzeHelmetJD", "Barbarian's helmet");
			localization["English"].Add("ArmorBarbarianBronzeHelmetJD_description", "Helmet made from a bronze alloy");
			localization["English"].Add("ArmorBarbarianBronzeChestJD", "Barbarian's armor");
			localization["English"].Add("ArmorBarbarianBronzeChestJD_description", "A bronze disc attached to leather straps, a true barbarian hurls himself into battle despite the lack of protection");
			localization["English"].Add("ArmorBarbarianBronzeLegsJD", "Barbarian's boots");
			localization["English"].Add("ArmorBarbarianBronzeLegsJD_description", "Thick hide wrapped around one's waist, fastened with a fashionable bronze belt");
			localization["English"].Add("ArmorBarbarianCapeJD", "Barbarian's fur cape");
			localization["English"].Add("ArmorBarbarianCapeJD_description", "Thick, short cape made from fur. Covers ones back when his drunk raidmates can't.");
			localization["English"].Add("ArmorWarriorHelmet", "Warrior's helmet");
			localization["English"].Add("ArmorWarriorHelmet_description", "Chainmail wrapping around the neck provides good protection");
			localization["English"].Add("ArmorWarriorChest", "Warrior's hauberk");
			localization["English"].Add("ArmorWarriorChest_description", "Long vest made from linked chains");
			localization["English"].Add("ArmorWarriorLegs", "Warrior's boots");
			localization["English"].Add("ArmorWarriorLegs_description", "Multi-layered pants keep it's wearer warm and protected");
			localization["English"].Add("ArmorPlateIronHelmetJD", "Sturdy helmet");
			localization["English"].Add("ArmorPlateIronHelmetJD_description", "A sturdy helmet with a leather neckguard");
			localization["English"].Add("ArmorPlateIronChestJD", "Plate mail");
			localization["English"].Add("ArmorPlateIronChestJD_description", "Thick plates of metal riveted to a leather harness");
			localization["English"].Add("ArmorPlateIronLegsJD", "Plate greaves");
			localization["English"].Add("ArmorPlateIronLegsJD_description", "Reliable greaves and kneeguards");
			localization["English"].Add("ArmorPlateCape", "Boar cape");
			localization["English"].Add("ArmorPlateCape_description", "Reinforced boar hide worn around one's shoulders like a trophy");
			localization["English"].Add("ArmorDragonslayerHelmet", "Horned helm");
			localization["English"].Add("ArmorDragonslayerHelmet_description", "Dragon's tremble in fear when they see the blackened helmet adorned with the horns of their kin");
			localization["English"].Add("ArmorDragonslayerChest", "Dragonslayer's armor");
			localization["English"].Add("ArmorDragonslayerChest_description", "Obsidian layer over silver plates makes for reliable protection");
			localization["English"].Add("ArmorDragonslayerLegs", "Spiked greaves");
			localization["English"].Add("ArmorDragonslayerLegs_description", "Unlucky is he who finds himself in the way of these");
			localization["English"].Add("ArmorWandererHelmet", "Straw hat");
			localization["English"].Add("ArmorWandererHelmet_description", "A reinforced straw hat");
			localization["English"].Add("ArmorWandererChest", "Coat of plates");
			localization["English"].Add("ArmorWandererChest_description", "Small metal plates attached to a leather jerkin, easy to maintain during travels");
			localization["English"].Add("ArmorWandererLegs", "Wanderer's pants");
			localization["English"].Add("ArmorWandererLegs_description", "Durable pants with makeshift protection around the shins");
			localization["English"].Add("ArmorWandererCape", "Straw cape");
			localization["English"].Add("ArmorWandererCape_description", "Cheap to make cape made from straw collected in the plains, protects against the elements but is quick to catch fire");
			localization["English"].Add("ArmorBlackmetalgarbHelmet", "Nomadic helmet");
			localization["English"].Add("ArmorBlackmetalgarbHelmet_description", "Blackmetal helmet with colorful padding fit for a nomad");
			localization["English"].Add("ArmorBlackmetalgarbChest", "Nomadic garb");
			localization["English"].Add("ArmorBlackmetalgarbChest_description", "A nomadic garb adorned with protective elements made from blackmetal, found commonly in the nomad's homeland, the plains");
			localization["English"].Add("ArmorBlackmetalgarbLegs", "Nomadic boots");
			localization["English"].Add("ArmorBlackmetalgarbLegs_description", "Thick leather boots with blackmetal toe guard, helpful when one happens to get stomped on by a Lox");
			localization["English"].Add("ArmorSerpentHelmet", "Finned helm");
			localization["English"].Add("ArmorSerpentHelmet_description", "A thick blackmetal casque adorned by the fins of a mighty serpent. The style is popular with raiding knights of the South.");
			localization["English"].Add("ArmorSerpentChest", "Serpent armor");
			localization["English"].Add("ArmorSerpentChest_description", "Plates of blackmetal overtop a surcoat of sea serpent scales. The perfect garb for spreading Odin's good word.");
			localization["English"].Add("ArmorSerpentLegs", "Serpent Cuisses");
			localization["English"].Add("ArmorSerpentLegs_description", "Blackmetal cuisses, greaves and sabatons. Excellent protection with a slightly fishy smell.");
			localization["English"].Add("ArmorSerpentCape", "Serpent knight's cape");
			localization["English"].Add("ArmorSerpentCape_description", "Heavy dark cape of the Serpent order.");
			localization["English"].Add("ArmorMistlandsHelmet", "Scorched sallet");
			localization["English"].Add("ArmorMistlandsHelmet_description", "Helmet made from a rare material only found within the ashlands");
			localization["English"].Add("ArmorMistlandsChest", "Scorched armor");
			localization["English"].Add("ArmorMistlandsChest_description", "Thick, multi layered gambeson provides protection from the searing heat of flametal, which in turn protects from blows");
			localization["English"].Add("ArmorMistlandsLegs", "Scorched greaves");
			localization["English"].Add("ArmorMistlandsLegs_description", "One need not fear the cold while wearing these");
			localization["English"].Add("BackpackSimple", "Simple backpack");
			localization["English"].Add("BackpackSimple_description", "Leather container attached to a wooden frame");
			localization["English"].Add("BackpackHeavy", "Heavy backpack");
			localization["English"].Add("BackpackHeavy_description", "Large chest hauled on ones shoulders with a canvas bag for additional storage");
		}

		public static void CreateBlacksmithsTooslConfigs()
		{
			if (bsmithAvailable)
			{
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorNobleChest",
					bonesToHide = Util.TorsoUpperLowerArms
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorNobleLegs",
					bonesToHide = Util.CompleteLegs
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorBlackmetalgarbChest",
					bonesToHide = Util.TorsoUpperArms
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorBlackmetalgarbLegs",
					bonesToHide = Util.CompleteLegs
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorBarbarianBronzeLegsJD",
					bonesToHide = Util.CompleteLegs
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorWarriorLegs",
					bonesToHide = Util.CompleteLegs
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorWandererChest",
					bonesToHide = Util.TorsoUpperArms
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorWandererLegs",
					bonesToHide = Util.CompleteLegs
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorDragonslayerChest",
					bonesToHide = Util.TorsoUpperArms
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorDragonslayerLegs",
					bonesToHide = Util.CompleteLegs
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorMistlandsChest",
					bonesToHide = Util.TorsoUpperLowerArms
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorMistlandsLegs",
					bonesToHide = Util.CompleteLegs
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorSerpentChest",
					bonesToHide = Util.TorsoUpperLowerArms
				});
				ItemManager.bsmithCfgs.Add(new BlacksmithsToolsConfig
				{
					itemName = "ArmorSerpentLegs",
					bonesToHide = Util.CompleteLegs
				});
			}
		}
	}
	[HarmonyPatch]
	internal static class Patches
	{
		public static IEnumerator DelayedRecipeInsertion()
		{
			yield return null;
			Main.modConfig.ApplyRecipeConfigs();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
		private static void CopyOtherDb_patch(ObjectDB __instance, ObjectDB other)
		{
			List<GameObject> items = __instance.m_items;
			object creatureShader;
			if (items == null)
			{
				creatureShader = null;
			}
			else
			{
				GameObject? obj = items.Find((GameObject _item) => ((Object)_item).name == "ArmorIronChest");
				if (obj == null)
				{
					creatureShader = null;
				}
				else
				{
					SkinnedMeshRenderer componentInChildren = obj.GetComponentInChildren<SkinnedMeshRenderer>(true);
					if (componentInChildren == null)
					{
						creatureShader = null;
					}
					else
					{
						Material material = ((Renderer)componentInChildren).material;
						creatureShader = ((material != null) ? material.shader : null);
					}
				}
			}
			Main.creatureShader = (Shader)creatureShader;
			ItemManager.AddItemsToDBs(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		private static void DbAwake_patch(ObjectDB __instance)
		{
			List<GameObject> items = __instance.m_items;
			object creatureShader;
			if (items == null)
			{
				creatureShader = null;
			}
			else
			{
				GameObject? obj = items.Find((GameObject _item) => ((Object)_item).name == "ArmorIronChest");
				if (obj == null)
				{
					creatureShader = null;
				}
				else
				{
					SkinnedMeshRenderer componentInChildren = obj.GetComponentInChildren<SkinnedMeshRenderer>(true);
					if (componentInChildren == null)
					{
						creatureShader = null;
					}
					else
					{
						Material material = ((Renderer)componentInChildren).material;
						creatureShader = ((material != null) ? material.shader : null);
					}
				}
			}
			Main.creatureShader = (Shader)creatureShader;
			if (Main.bsmithAvailable)
			{
				Main.CreateBlacksmithsTooslConfigs();
				ItemManager.InsertBsmithToolsCfgs();
			}
			ItemManager.AddItemsToDBs(__instance);
			Main.LoadModConfig();
			LocalizationManager.LoadLocalization();
			LocalizationManager.InsertLocalization();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FejdStartup), "Start")]
		private static void FejdSetupGui_patch()
		{
			LocalizationManager.localizationInstance = Localization.instance;
		}

		[HarmonyPatch(typeof(Humanoid), "HaveSetEffect")]
		[HarmonyPostfix]
		private static void shitpatch(ItemData item, Humanoid __instance, ref bool __result)
		{
			if (!__result && item != null && !((Object)(object)item.m_dropPrefab == (Object)null) && ItemManager.allPrefabs.Contains(((Object)item.m_dropPrefab).name))
			{
				__result = item != null && !((Object)(object)item.m_shared.m_setStatusEffect == (Object)null) && item.m_shared.m_setName.Length != 0 && item.m_shared.m_setSize > 0 && __instance.GetSetCount(item.m_shared.m_setName) >= item.m_shared.m_setSize;
			}
		}
	}
	public static class Util
	{
		public static readonly int[] Torso = new int[6] { 0, 1, 2, 3, 7, 26 };

		public static readonly int[] ArmUpperLeft = new int[1] { 8 };

		public static readonly int[] ArmLowerLeft = new int[1] { 9 };

		public static readonly int[] HandLeft = new int[17]
		{
			10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
			20, 21, 22, 23, 24, 25, 26
		};

		public static readonly int[] ArmUpperRight = new int[1] { 27 };

		public static readonly int[] ArmLowerRight = new int[1] { 28 };

		public static readonly int[] HandRight = new int[16]
		{
			29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
			39, 40, 41, 42, 43, 44
		};

		public static readonly int[] LegUpperLeft = new int[1] { 45 };

		public static readonly int[] LegLowerLeft = new int[1] { 46 };

		public static readonly int[] FootLeft = new int[2] { 47, 48 };

		public static readonly int[] LegUpperRight = new int[1] { 49 };

		public static readonly int[] LegLowerRight = new int[1] { 50 };

		public static readonly int[] FootRight = new int[2] { 51, 52 };

		public static readonly int[] TorsoUpperArms = Torso.Concat(ArmUpperLeft).Concat(ArmUpperRight).ToArray();

		public static readonly int[] TorsoUpperLowerArms = Torso.Concat(ArmUpperLeft).Concat(ArmLowerLeft).Concat(ArmUpperRight)
			.Concat(ArmLowerRight)
			.ToArray();

		public static readonly int[] CompleteLegs = LegUpperLeft.Concat(LegLowerLeft).Concat(FootLeft).Concat(LegUpperRight)
			.Concat(LegLowerRight)
			.Concat(FootRight)
			.ToArray();

		public static AssetBundle LoadBundle(string bundleName)
		{
			return AssetBundle.LoadFromStream(Main.assembly.GetManifestResourceStream(Main.assembly.GetName().Name + ".Resources." + bundleName));
		}

		public static bool IsModAvailable(string modName, string minVersion, bool printAllMods = false)
		{
			PluginInfo? obj = Chainloader.PluginInfos.Values.ToList().Find((PluginInfo _modName) => _modName.Metadata.Name == modName);
			return ((obj != null) ? obj.Metadata.Version : null) >= new System.Version(minVersion);
		}

		public static List<DamageModPair> ParseDmgModPairs(string def)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (string.IsNullOrEmpty(def))
				{
					return new List<DamageModPair>();
				}
				def = def.Trim();
				List<DamageModPair> list = new List<DamageModPair>();
				string[] array = def.Split(new char[1] { ';' });
				string[] array2 = array;
				foreach (string text in array2)
				{
					string[] array3 = text.Split(new char[1] { ':' });
					DamageType type = (DamageType)Enum.Parse(typeof(DamageType), array3[0].ToString().Trim());
					DamageModifier modifier = (DamageModifier)Enum.Parse(typeof(DamageModifier), array3[1].ToString().Trim());
					list.Add(new DamageModPair
					{
						m_type = type,
						m_modifier = modifier
					});
				}
				return list;
			}
			catch (Exception ex)
			{
				Main.log.LogError((object)"An error occured when parsing damge modifiers");
				Main.log.LogError((object)ex.Message);
				return new List<DamageModPair>();
			}
		}
	}
}
namespace JudesEquipment.Properties
{
	[CompilerGenerated]
	[DebuggerNonUserCode]
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					ResourceManager resourceManager = new ResourceManager("JudesEquipment.Properties.Resources", typeof(Resources).Assembly);
					resourceMan = resourceManager;
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal static byte[] judeequipment
		{
			get
			{
				object @object = ResourceManager.GetObject("judeequipment", resourceCulture);
				return (byte[])@object;
			}
		}

		internal Resources()
		{
		}
	}
}
namespace JudesEquipment.Configuration
{
	public class ArmorSetConfig
	{
		[YamlMember(Alias = "set effect")]
		public SetEffect setEffect = new SetEffect();

		public Dictionary<string, ArmorConfig> items = new Dictionary<string, ArmorConfig>();

		public void ApplyArmorConfigs()
		{
			items.Values.ToList().ForEach(delegate(ArmorConfig piece)
			{
				piece.ApplyConfig();
			});
		}

		public void ApplyRecipeConfigs()
		{
			items.Values.ToList().ForEach(delegate(ArmorConfig piece)
			{
				piece.recipe.ApplyConfig(piece.prefabName);
			});
		}

		public void ApplySetConfig(string effectName)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			SE_Stats effect = (SE_Stats)ItemManager.customSEs.Find((StatusEffect se) => ((Object)se).name == effectName);
			if ((Object)(object)effect == (Object)null)
			{
				effect = ScriptableObject.CreateInstance<SE_Stats>();
				((Object)effect).name = effectName;
				((StatusEffect)effect).m_icon = ObjectDB.instance.m_items.Find((GameObject iconSource) => ((Object)iconSource).name == items.Values.ToList()[0].prefabName).GetComponent<ItemDrop>().m_itemData.m_shared.m_icons[0];
				ObjectDB.instance.m_StatusEffects.Add((StatusEffect)(object)effect);
				ItemManager.customSEs.Add((StatusEffect)(object)effect);
			}
			effect.m_healthRegenMultiplier = (float)setEffect.healthRegenModifier / 100f + 1f;
			effect.m_staminaRegenMultiplier = (float)setEffect.staminaReregenModifier / 100f + 1f;
			effect.m_addMaxCarryWeight = setEffect.carryWeightModifier;
			effect.m_mods = ArmorConfig.ParseModPairs(setEffect.damageModifiers);
			effect.m_skillLevel = (SkillType)Enum.Parse(typeof(SkillType), setEffect.skillModifier.skill);
			effect.m_skillLevelModifier = setEffect.skillModifier.modifier;
			effect.m_runStaminaDrainModifier = (float)setEffect.runStaminaDrainModifier / 100f;
			effect.m_jumpStaminaUseModifier = (float)setEffect.jumpStaminaDrainModifier / 100f;
			items.Values.ToList().ForEach(delegate(ArmorConfig piece)
			{
				if (piece.countsTowardsSetBonus)
				{
					GameObject prefab = ItemManager.prefabs.Find((PrefabConfig armor) => ((Object)armor.GetPrefab()).name == piece.prefabName).GetPrefab();
					ItemDrop val = ((prefab != null) ? prefab.GetComponent<ItemDrop>() : null);
					val.m_itemData.m_shared.m_setStatusEffect = (StatusEffect)(object)effect;
					val.m_itemData.m_shared.m_setName = effectName;
					val.m_itemData.m_shared.m_setSize = GetSetSize();
				}
			});
		}

		public int GetSetSize()
		{
			int num = 0;
			foreach (ArmorConfig value in items.Values)
			{
				if (value.countsTowardsSetBonus)
				{
					num++;
				}
			}
			return num;
		}
	}
	public class ItemConfig
	{
		[YamlMember(Alias = "noble's armor")]
		public Noble noble = new Noble();

		[YamlMember(Alias = "barbarian's armor")]
		public Barbarian barbarian = new Barbarian();

		[YamlMember(Alias = "warrior's armor")]
		public Warrior warrior = new Warrior();

		[YamlMember(Alias = "plate armor")]
		public Plate plate = new Plate();

		[YamlMember(Alias = "dragonslayer's armor")]
		public Dragonslayer dragonslayer = new Dragonslayer();

		[YamlMember(Alias = "wanderer's armor")]
		public Wanderer wanderer = new Wanderer();

		[YamlMember(Alias = "nomad's armor")]
		public Nomad nomad = new Nomad();

		[YamlMember(Alias = "serpent armor")]
		public Serpent serpent = new Serpent();

		[YamlMember(Alias = "scorched armor")]
		public Scorched scorched = new Scorched();

		[YamlMember(Alias = "simple backpack")]
		public SimpleBackpack simpleBackpack = new SimpleBackpack();

		[YamlMember(Alias = "heavy backpack")]
		public HeavyBackpack heavyBackpack = new HeavyBackpack();

		[YamlIgnore]
		private List<ArmorSetConfig> Sets => new List<ArmorSetConfig>
		{
			noble, barbarian, warrior, plate, dragonslayer, wanderer, nomad, serpent, scorched, simpleBackpack,
			heavyBackpack
		};

		public void ApplyArmorConfigs()
		{
			Sets.ForEach(delegate(ArmorSetConfig set)
			{
				set.ApplyArmorConfigs();
			});
		}

		public void ApplyRecipeConfigs()
		{
			Sets.ForEach(delegate(ArmorSetConfig set)
			{
				set.ApplyRecipeConfigs();
			});
		}

		public void ApplySetEffects()
		{
			Sets.ForEach(delegate(ArmorSetConfig set)
			{
				set.ApplySetConfig(set.items.Values.First().prefabName);
			});
		}
	}
	public class PrefabConfig
	{
		public GameObject prefab;

		public bool replaceMat = true;

		public GameObject GetPrefab()
		{
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Invalid comparison between Unknown and I4
			if ((Object)(object)prefab == (Object)null)
			{
				Main.log.LogWarning((object)"prefab null");
				return null;
			}
			prefab.layer = 12;
			ItemDrop component = prefab.GetComponent<ItemDrop>();
			SharedData shared = component.m_itemData.m_shared;
			prefab.layer = 12;
			string name = "$" + ((Object)prefab).name;
			string description = "$" + ((Object)prefab).name + "_description";
			shared.m_name = name;
			shared.m_description = description;
			if (replaceMat)
			{
				ReplaceMaterials();
			}
			if (!Main.hugosCollidersAvaiable && (int)component.m_itemData.m_shared.m_itemType != 17)
			{
				prefab.GetComponentsInChildren<Cloth>(true).ToList().ForEach(delegate(Cloth cloth)
				{
					Object.Destroy((Object)(object)cloth);
				});
			}
			return prefab;
		}

		public void ReplaceMaterials()
		{
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Expected O, but got Unknown
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)prefab == (Object)null || (Object)(object)Main.creatureShader == (Object)null)
			{
				return;
			}
			List<Renderer> list = new List<Renderer>();
			list.AddRange((IEnumerable<Renderer>)(object)prefab.GetComponentsInChildren<MeshRenderer>(true));
			list.AddRange((IEnumerable<Renderer>)(object)prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true));
			foreach (Renderer item in list)
			{
				List<Material> list2 = new List<Material>();
				int num = 0;
				Material[] materials = item.materials;
				foreach (Material mat in materials)
				{
					string[] source = new string[4] { "_MainTex", "_BumpMap", "_MetallicGlossMap", "_EmissionMap" };
					string[] array = new string[1] { "_BumpMap" };
					Material replacerMat = new Material(Main.creatureShader);
					replacerMat.SetFloat("_Cull", 0f);
					replacerMat.SetFloat("_AddRain", 1f);
					replacerMat.SetFloat("_Glossiness", 0f);
					int num2 = (((Object)(object)mat.GetTexture("_MetallicGlossMap") != (Object)null) ? 1 : 0);
					replacerMat.SetFloat("_Metallic", (float)num2);
					replacerMat.SetFloat("_MetalGloss", mat.GetFloat("_GlossMapScale"));
					replacerMat.SetFloat("_TwoSidedNormals", 1f);
					Color val = mat.GetColor("_Color");
					Color val2 = mat.GetColor("_EmissionColor");
					if (Main.neutralMetals.Value)
					{
						val = Color.grey;
						val2 = Color.black;
					}
					else if (ItemManager.colorConfig.ContainsKey(((Object)prefab).name))
					{
						string key = "Color " + (num + 1);
						if (ItemManager.colorConfig[((Object)prefab).name].ContainsKey(key))
						{
							ColorUtility.TryParseHtmlString(ItemManager.colorConfig[((Object)prefab).name][key], ref val);
						}
						if (ItemManager.colorConfig[((Object)prefab).name].ContainsKey("Emission color"))
						{
							ColorUtility.TryParseHtmlString(ItemManager.colorConfig[((Object)prefab).name]["Emission color"], ref val2);
						}
					}
					replacerMat.SetColor("_Color", Color.white);
					replacerMat.SetColor("_MetalColor", val);
					replacerMat.SetColor("_EmissionColor", val2);
					replacerMat.EnableKeyword("_ADDRAIN_ON");
					replacerMat.EnableKeyword("_TWOSIDEDNORMALS_ON");
					source.ToList().ForEach(delegate(string tex)
					{
						Texture texture = mat.GetTexture(tex);
						if ((Object)(object)texture != (Object)null && Main.smoothTextures.Value)
						{
							texture.filterMode = (FilterMode)1;
						}
						replacerMat.SetTexture(tex, texture);
					});
					list2.Add(replacerMat);
					num++;
				}
				item.materials = list2.ToArray();
			}
			replaceMat = false;
		}
	}
	public class RecipeConfig
	{
		public class RequirementConfig
		{
			[YamlMember(Alias = "item")]
			public string item;

			[YamlMember(Alias = "amount")]
			public int amount = 0;

			[YamlMember(Alias = "amount per level")]
			public int amountPerLevel = 0;

			public Requirement GetRequirement()
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Expected O, but got Unknown
				Requirement val = new Requirement();
				GameObject? obj = ObjectDB.instance.m_items.Find((GameObject _item) => ((Object)_item).name == item);
				val.m_resItem = ((obj != null) ? obj.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val.m_resItem == (Object)null)
				{
					return null;
				}
				val.m_amount = amount;
				val.m_amountPerLevel = amountPerLevel;
				val.m_recover = true;
				return val;
			}
		}

		[YamlMember(Alias = "enabled")]
		public bool enabled = true;

		[YamlIgnore]
		public int amount = 1;

		[YamlMember(Alias = "station")]
		public string station = string.Empty;

		[YamlMember(Alias = "minimum station level")]
		public int minimumStationLevel = 1;

		[YamlMember(Alias = "requirements")]
		public List<RequirementConfig> requirements = new List<RequirementConfig>();

		public void ApplyConfig(string prefabName)
		{
			bool flag = false;
			string recipeName = prefabName + "_recipe";
			if ((Object)(object)ObjectDB.instance == (Object)null || (Object)(object)ZNetScene.instance == (Object)null || !enabled)
			{
				return;
			}
			Recipe val = ObjectDB.instance.m_recipes?.Find((Recipe _recipe) => ((Object)_recipe).name == recipeName);
			if ((Object)(object)val == (Object)null)
			{
				flag = true;
			}
			PrefabConfig? prefabConfig = ItemManager.prefabs.Find((PrefabConfig _prefab) => ((Object)_prefab.GetPrefab()).name == prefabName);
			object obj;
			if (prefabConfig == null)
			{
				obj = null;
			}
			else
			{
				GameObject prefab = prefabConfig.GetPrefab();
				obj = ((prefab != null) ? prefab.GetComponent<ItemDrop>() : null);
			}
			ItemDrop val2 = (ItemDrop)obj;
			if ((Object)(object)val2 == (Object)null)
			{
				return;
			}
			if (flag)
			{
				val = ScriptableObject.CreateInstance<Recipe>();
				((Object)val).name = recipeName;
				ObjectDB.instance.m_recipes.Add(val);
			}
			val.m_enabled = enabled;
			val.m_item = val2;
			val.m_amount = amount;
			Recipe obj2 = val;
			GameObject prefab2 = ZNetScene.instance.GetPrefab(station);
			obj2.m_craftingStation = ((prefab2 != null) ? prefab2.GetComponent<CraftingStation>() : null);
			val.m_repairStation = val.m_craftingStation;
			val.m_minStationLevel = minimumStationLevel;
			List<Requirement> resolvedRequirements = new List<Requirement>();
			requirements.ForEach(delegate(RequirementConfig reqCfg)
			{
				Requirement requirement = reqCfg.GetRequirement();
				if (requirement != null)
				{
					resolvedRequirements.Add(requirement);
				}
			});
			val.m_resources = resolvedRequirements.ToArray();
		}
	}
	public class SetEffect
	{
		[YamlMember(Alias = "health regen modifier")]
		public int healthRegenModifier = 0;

		[YamlMember(Alias = "stamina regen modifier")]
		public int staminaReregenModifier = 0;

		[YamlMember(Alias = "run stamina drain modifier")]
		public int runStaminaDrainModifier = 0;

		[YamlMember(Alias = "jump stamina drain modifier")]
		public int jumpStaminaDrainModifier = 0;

		[YamlMember(Alias = "carry weight modifier")]
		public int carryWeightModifier = 0;

		[YamlMember(Alias = "skill modifier")]
		public SkillModifier skillModifier = new SkillModifier();

		[YamlMember(Alias = "damage modifiers")]
		public Dictionary<string, string> damageModifiers;

		public SetEffect()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			DamageType val = (DamageType)1;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)2;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)4;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)8;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)32;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)64;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)128;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)256;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)512;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			damageModifiers = dictionary;
			base..ctor();
		}
	}
	public class SkillModifier
	{
		public string skill = "None";

		public int modifier = 0;
	}
	public class ArmorConfig
	{
		[YamlMember(Alias = "item prefab name")]
		public string prefabName = string.Empty;

		[YamlMember(Alias = "required for set bonus")]
		public bool countsTowardsSetBonus = true;

		public int armor = 0;

		[YamlMember(Alias = "armor per level")]
		public int armorPerLevel = 2;

		[YamlMember(Alias = "enable durability")]
		public bool enableDurability = true;

		public int baseDurability = 1000;

		[YamlMember(Alias = "durability per level")]
		public int durabilityPerLevel = 200;

		public bool repairable = true;

		[YamlMember(Alias = "destroy when broken")]
		public bool destroyBroken = false;

		public int weight = 0;

		public bool teleportable = true;

		[YamlMember(Alias = "maximum upgrade level")]
		public int maxUpgradeLevel = 4;

		[YamlMember(Alias = "movement speed modifier")]
		public int movementSpeedModifier = 0;

		[YamlMember(Alias = "damage modifiers")]
		public Dictionary<string, string> damageModifiers;

		[YamlMember(Alias = "recipe")]
		public RecipeConfig recipe;

		public void ApplyConfig()
		{
			PrefabConfig? prefabConfig = ItemManager.prefabs.Find((PrefabConfig prefab) => ((Object)prefab.GetPrefab()).name == prefabName);
			object obj;
			if (prefabConfig == null)
			{
				obj = null;
			}
			else
			{
				GameObject prefab2 = prefabConfig.GetPrefab();
				obj = ((prefab2 != null) ? prefab2.GetComponent<ItemDrop>().m_itemData.m_shared : null);
			}
			SharedData val = (SharedData)obj;
			if (val != null)
			{
				val.m_weight = weight;
				val.m_armor = armor;
				val.m_armorPerLevel = armorPerLevel;
				val.m_damageModifiers = ParseModPairs(damageModifiers);
				val.m_maxDurability = baseDurability;
				val.m_durabilityPerLevel = durabilityPerLevel;
				val.m_destroyBroken = destroyBroken;
				val.m_canBeReparied = repairable;
				val.m_movementModifier = (float)movementSpeedModifier / 100f;
				val.m_equipDuration = 1f;
				val.m_maxQuality = maxUpgradeLevel;
				val.m_useDurability = enableDurability;
			}
		}

		public static List<DamageModPair> ParseModPairs(Dictionary<string, string> mods)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			List<DamageModPair> list = new List<DamageModPair>();
			foreach (KeyValuePair<string, string> mod in mods)
			{
				if (!(mod.Value.ToLower() == "none"))
				{
					DamageType type = (DamageType)Enum.Parse(typeof(DamageType), mod.Key);
					DamageModifier modifier = (DamageModifier)Enum.Parse(typeof(DamageModifier), mod.Value);
					list.Add(new DamageModPair
					{
						m_type = type,
						m_modifier = modifier
					});
				}
			}
			return list;
		}

		public ArmorConfig()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			DamageType val = (DamageType)1;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)2;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)4;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)8;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)32;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)64;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)128;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)256;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			val = (DamageType)512;
			dictionary.Add(((object)(DamageType)(ref val)).ToString(), "none");
			damageModifiers = dictionary;
			recipe = new RecipeConfig();
			base..ctor();
		}
	}
	public class BlacksmithsToolsConfig
	{
		public string itemName;

		public int[] bonesToHide;
	}
}
namespace JudesEquipment.ArmorSets
{
	public class Barbarian : ArmorSetConfig
	{
		public Barbarian()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			SetEffect obj = new SetEffect
			{
				staminaReregenModifier = 25
			};
			SkillModifier skillModifier = new SkillModifier();
			SkillType val = (SkillType)7;
			skillModifier.skill = ((object)(SkillType)(ref val)).ToString();
			skillModifier.modifier = 25;
			obj.skillModifier = skillModifier;
			setEffect = obj;
			int armor = 4;
			int weight = 10;
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "ArmorBarbarianBronzeHelmetJD",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Bronze",
							amount = 5,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 2,
							amountPerLevel = 0
						}
					}
				}
			};
			ArmorConfig value2 = new ArmorConfig
			{
				prefabName = "ArmorBarbarianBronzeChestJD",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Bronze",
							amount = 5,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 2,
							amountPerLevel = 0
						}
					}
				}
			};
			ArmorConfig value3 = new ArmorConfig
			{
				prefabName = "ArmorBarbarianBronzeLegsJD",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Bronze",
							amount = 5,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 2,
							amountPerLevel = 0
						}
					}
				}
			};
			ArmorConfig value4 = new ArmorConfig
			{
				prefabName = "ArmorBarbarianCapeJD",
				armor = 4,
				weight = 6,
				movementSpeedModifier = -3,
				countsTowardsSetBonus = false,
				recipe = new RecipeConfig
				{
					station = "piece_workbench",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 8,
							amountPerLevel = 4
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Bronze",
							amount = 1,
							amountPerLevel = 1
						},
						new RecipeConfig.RequirementConfig
						{
							item = "BoneFragments",
							amount = 5,
							amountPerLevel = 3
						}
					}
				}
			};
			items.Add("helmet", value);
			items.Add("chest", value2);
			items.Add("legs", value3);
			items.Add("cape", value4);
		}
	}
	public class Dragonslayer : ArmorSetConfig
	{
		public Dragonslayer()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			SetEffect obj = new SetEffect
			{
				jumpStaminaDrainModifier = -25
			};
			SkillModifier skillModifier = new SkillModifier();
			SkillType val = (SkillType)100;
			skillModifier.skill = ((object)(SkillType)(ref val)).ToString();
			skillModifier.modifier = 30;
			obj.skillModifier = skillModifier;
			setEffect = obj;
			Dictionary<string, string> damageModifiers = setEffect.damageModifiers;
			DamageType val2 = (DamageType)64;
			string? key = ((object)(DamageType)(ref val2)).ToString();
			DamageModifier val3 = (DamageModifier)1;
			damageModifiers[key] = ((object)(DamageModifier)(ref val3)).ToString();
			int armor = 24;
			int weight = 20;
			int movementSpeedModifier = -5;
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "ArmorDragonslayerHelmet",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Silver",
							amount = 20,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "WolfPelt",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Obsidian",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "TrophyHatchling",
							amount = 2,
							amountPerLevel = 0
						}
					}
				}
			};
			ArmorConfig value2 = new ArmorConfig
			{
				prefabName = "ArmorDragonslayerChest",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Silver",
							amount = 20,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "WolfPelt",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Obsidian",
							amount = 10,
							amountPerLevel = 3
						}
					}
				}
			};
			ArmorConfig value3 = new ArmorConfig
			{
				prefabName = "ArmorDragonslayerLegs",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Silver",
							amount = 20,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "WolfPelt",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Obsidian",
							amount = 10,
							amountPerLevel = 3
						}
					}
				}
			};
			items.Add("helmet", value);
			items.Add("chest", value2);
			items.Add("legs", value3);
		}
	}
	public class HeavyBackpack : ArmorSetConfig
	{
		public HeavyBackpack()
		{
			setEffect = new SetEffect
			{
				carryWeightModifier = 200
			};
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "BackpackHeavy",
				armor = 0,
				weight = 30,
				movementSpeedModifier = -5,
				baseDurability = 100,
				durabilityPerLevel = 100,
				recipe = new RecipeConfig
				{
					station = "piece_workbench",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Wood",
							amount = 20,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 5,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "IronNails",
							amount = 10,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Iron",
							amount = 2,
							amountPerLevel = 1
						}
					}
				}
			};
			items.Add("backpack", value);
		}
	}
	public class Noble : ArmorSetConfig
	{
		public Noble()
		{
			setEffect = new SetEffect
			{
				staminaReregenModifier = 5,
				healthRegenModifier = 5,
				runStaminaDrainModifier = -5
			};
			int armor = 1;
			int weight = 5;
			string station = "piece_workbench";
			string item = "LeatherScraps";
			int amount = 5;
			int amountPerLevel = 1;
			string item2 = "DeerHide";
			int amount2 = 2;
			int amountPerLevel2 = 1;
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "ArmorNobleHelmet",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = station,
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = item,
							amount = amount,
							amountPerLevel = amountPerLevel
						},
						new RecipeConfig.RequirementConfig
						{
							item = item2,
							amount = amount2,
							amountPerLevel = amountPerLevel2
						}
					}
				}
			};
			ArmorConfig value2 = new ArmorConfig
			{
				prefabName = "ArmorNobleChest",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = station,
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = item,
							amount = amount,
							amountPerLevel = amountPerLevel
						},
						new RecipeConfig.RequirementConfig
						{
							item = item2,
							amount = amount2,
							amountPerLevel = amountPerLevel2
						}
					}
				}
			};
			ArmorConfig value3 = new ArmorConfig
			{
				prefabName = "ArmorNobleLegs",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = station,
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = item,
							amount = amount,
							amountPerLevel = amountPerLevel
						},
						new RecipeConfig.RequirementConfig
						{
							item = item2,
							amount = amount2,
							amountPerLevel = amountPerLevel2
						}
					}
				}
			};
			ArmorConfig value4 = new ArmorConfig
			{
				prefabName = "ArmorNobleCape",
				armor = 1,
				weight = 1,
				countsTowardsSetBonus = false,
				recipe = new RecipeConfig
				{
					station = station,
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = item,
							amount = amount,
							amountPerLevel = amountPerLevel
						}
					}
				}
			};
			items.Add("helmet", value);
			items.Add("chest", value2);
			items.Add("legs", value3);
			items.Add("cape", value4);
		}
	}
	public class Nomad : ArmorSetConfig
	{
		public Nomad()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			SetEffect obj = new SetEffect
			{
				runStaminaDrainModifier = -15
			};
			SkillModifier skillModifier = new SkillModifier();
			SkillType val = (SkillType)102;
			skillModifier.skill = ((object)(SkillType)(ref val)).ToString();
			skillModifier.modifier = 25;
			obj.skillModifier = skillModifier;
			setEffect = obj;
			Dictionary<string, string> damageModifiers = setEffect.damageModifiers;
			DamageType val2 = (DamageType)64;
			string key = ((object)(DamageType)(ref val2)).ToString().ToString();
			DamageModifier val3 = (DamageModifier)1;
			damageModifiers[key] = ((object)(DamageModifier)(ref val3)).ToString();
			int armor = 20;
			int weight = 10;
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "ArmorBlackmetalgarbHelmet",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "BlackMetal",
							amount = 15,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LoxPelt",
							amount = 10,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 20,
							amountPerLevel = 5
						}
					}
				}
			};
			ArmorConfig value2 = new ArmorConfig
			{
				prefabName = "ArmorBlackmetalgarbChest",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "BlackMetal",
							amount = 15,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LoxPelt",
							amount = 10,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 20,
							amountPerLevel = 5
						}
					}
				}
			};
			ArmorConfig value3 = new ArmorConfig
			{
				prefabName = "ArmorBlackmetalgarbLegs",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "BlackMetal",
							amount = 15,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LoxPelt",
							amount = 10,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 20,
							amountPerLevel = 5
						}
					}
				}
			};
			items.Add("helmet", value);
			items.Add("chest", value2);
			items.Add("legs", value3);
		}
	}
	public class Plate : ArmorSetConfig
	{
		public Plate()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			SetEffect obj = new SetEffect
			{
				healthRegenModifier = 10
			};
			SkillModifier skillModifier = new SkillModifier();
			SkillType val = (SkillType)6;
			skillModifier.skill = ((object)(SkillType)(ref val)).ToString();
			skillModifier.modifier = 20;
			obj.skillModifier = skillModifier;
			setEffect = obj;
			int armor = 18;
			int weight = 20;
			int movementSpeedModifier = -5;
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "ArmorPlateIronHelmetJD",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Iron",
							amount = 20,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 5,
							amountPerLevel = 1
						}
					}
				}
			};
			ArmorConfig value2 = new ArmorConfig
			{
				prefabName = "ArmorPlateIronChestJD",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Iron",
							amount = 25,
							amountPerLevel = 8
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 5,
							amountPerLevel = 1
						}
					}
				}
			};
			ArmorConfig value3 = new ArmorConfig
			{
				prefabName = "ArmorPlateIronLegsJD",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Iron",
							amount = 25,
							amountPerLevel = 8
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 5,
							amountPerLevel = 1
						}
					}
				}
			};
			ArmorConfig value4 = new ArmorConfig
			{
				prefabName = "ArmorPlateCape",
				armor = 4,
				weight = 8,
				movementSpeedModifier = -3,
				countsTowardsSetBonus = false,
				recipe = new RecipeConfig
				{
					station = "piece_workbench",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "TrophyBoar",
							amount = 3,
							amountPerLevel = 1
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Iron",
							amount = 2,
							amountPerLevel = 1
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LeatherScraps",
							amount = 10,
							amountPerLevel = 5
						}
					}
				}
			};
			items.Add("helmet", value);
			items.Add("chest", value2);
			items.Add("legs", value3);
			items.Add("cape", value4);
		}
	}
	public class Scorched : ArmorSetConfig
	{
		public Scorched()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			SetEffect obj = new SetEffect
			{
				healthRegenModifier = 10
			};
			SkillModifier skillModifier = new SkillModifier();
			SkillType val = (SkillType)1;
			skillModifier.skill = ((object)(SkillType)(ref val)).ToString();
			skillModifier.modifier = 15;
			obj.skillModifier = skillModifier;
			setEffect = obj;
			Dictionary<string, string> damageModifiers = setEffect.damageModifiers;
			DamageType val2 = (DamageType)32;
			string? key = ((object)(DamageType)(ref val2)).ToString();
			DamageModifier val3 = (DamageModifier)1;
			damageModifiers[key] = ((object)(DamageModifier)(ref val3)).ToString();
			Dictionary<string, string> damageModifiers2 = setEffect.damageModifiers;
			val2 = (DamageType)64;
			string? key2 = ((object)(DamageType)(ref val2)).ToString();
			val3 = (DamageModifier)1;
			damageModifiers2[key2] = ((object)(DamageModifier)(ref val3)).ToString();
			int armor = 34;
			int weight = 20;
			int movementSpeedModifier = -5;
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "ArmorMistlandsHelmet",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Flametal",
							amount = 20,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LoxPelt",
							amount = 10,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 10,
							amountPerLevel = 3
						}
					}
				}
			};
			ArmorConfig value2 = new ArmorConfig
			{
				prefabName = "ArmorMistlandsChest",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Flametal",
							amount = 20,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LoxPelt",
							amount = 10,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 10,
							amountPerLevel = 3
						}
					}
				}
			};
			ArmorConfig value3 = new ArmorConfig
			{
				prefabName = "ArmorMistlandsLegs",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Flametal",
							amount = 20,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LoxPelt",
							amount = 10,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 10,
							amountPerLevel = 3
						}
					}
				}
			};
			items.Add("helmet", value);
			items.Add("chest", value2);
			items.Add("legs", value3);
		}
	}
	public class Serpent : ArmorSetConfig
	{
		public Serpent()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: Unknown result type (might be due to invalid IL or missing references)
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			SetEffect obj = new SetEffect
			{
				staminaReregenModifier = 15,
				healthRegenModifier = 15
			};
			SkillModifier skillModifier = new SkillModifier();
			SkillType val = (SkillType)103;
			skillModifier.skill = ((object)(SkillType)(ref val)).ToString();
			skillModifier.modifier = 30;
			obj.skillModifier = skillModifier;
			setEffect = obj;
			int armor = 30;
			int weight = 20;
			int movementSpeedModifier = -5;
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "ArmorSerpentHelmet",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "BlackMetal",
							amount = 15,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Silver",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LoxPelt",
							amount = 10,
							amountPerLevel = 2
						},
						new RecipeConfig.RequirementConfig
						{
							item = "TrophySerpent",
							amount = 2,
							amountPerLevel = 0
						}
					}
				}
			};
			ArmorConfig value2 = new ArmorConfig
			{
				prefabName = "ArmorSerpentChest",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "BlackMetal",
							amount = 15,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Silver",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LoxPelt",
							amount = 5,
							amountPerLevel = 2
						},
						new RecipeConfig.RequirementConfig
						{
							item = "SerpentScale",
							amount = 5,
							amountPerLevel = 2
						}
					}
				}
			};
			ArmorConfig value3 = new ArmorConfig
			{
				prefabName = "ArmorSerpentLegs",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "BlackMetal",
							amount = 15,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Silver",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LoxPelt",
							amount = 5,
							amountPerLevel = 2
						},
						new RecipeConfig.RequirementConfig
						{
							item = "SerpentScale",
							amount = 5,
							amountPerLevel = 2
						}
					}
				}
			};
			ArmorConfig armorConfig = new ArmorConfig
			{
				prefabName = "ArmorSerpentCape",
				armor = 3,
				weight = 6,
				recipe = new RecipeConfig
				{
					station = "piece_workbench",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Silver",
							amount = 5,
							amountPerLevel = 1
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 20,
							amountPerLevel = 5
						}
					}
				}
			};
			Dictionary<string, string> damageModifiers = armorConfig.damageModifiers;
			DamageType val2 = (DamageType)64;
			string? key = ((object)(DamageType)(ref val2)).ToString();
			DamageModifier val3 = (DamageModifier)1;
			damageModifiers[key] = ((object)(DamageModifier)(ref val3)).ToString();
			items.Add("helmet", value);
			items.Add("chest", value2);
			items.Add("legs", value3);
			items.Add("cape", armorConfig);
		}
	}
	public class SimpleBackpack : ArmorSetConfig
	{
		public SimpleBackpack()
		{
			setEffect = new SetEffect
			{
				carryWeightModifier = 100
			};
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "BackpackSimple",
				armor = 0,
				weight = 15,
				movementSpeedModifier = -5,
				baseDurability = 10,
				durabilityPerLevel = 10,
				recipe = new RecipeConfig
				{
					station = "piece_workbench",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Wood",
							amount = 20,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 5,
							amountPerLevel = 2
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LeatherScraps",
							amount = 10,
							amountPerLevel = 5
						}
					}
				}
			};
			items.Add("backpack", value);
		}
	}
	public class Wanderer : ArmorSetConfig
	{
		public Wanderer()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			SetEffect obj = new SetEffect
			{
				staminaReregenModifier = 15,
				carryWeightModifier = 50
			};
			SkillModifier skillModifier = new SkillModifier();
			SkillType val = (SkillType)1;
			skillModifier.skill = ((object)(SkillType)(ref val)).ToString();
			skillModifier.modifier = 15;
			obj.skillModifier = skillModifier;
			setEffect = obj;
			int armor = 22;
			int weight = 10;
			int movementSpeedModifier = -3;
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "ArmorWandererHelmet",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Flax",
							amount = 15,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Iron",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 10,
							amountPerLevel = 3
						}
					}
				}
			};
			ArmorConfig value2 = new ArmorConfig
			{
				prefabName = "ArmorWandererChest",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Iron",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 20,
							amountPerLevel = 10
						}
					}
				}
			};
			ArmorConfig value3 = new ArmorConfig
			{
				prefabName = "ArmorWandererLegs",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Iron",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 20,
							amountPerLevel = 10
						}
					}
				}
			};
			ArmorConfig value4 = new ArmorConfig
			{
				prefabName = "ArmorWandererCape",
				armor = 2,
				weight = 5,
				countsTowardsSetBonus = false,
				recipe = new RecipeConfig
				{
					station = "piece_workbench",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Flax",
							amount = 15,
							amountPerLevel = 5
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Iron",
							amount = 10,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "LinenThread",
							amount = 10,
							amountPerLevel = 3
						}
					}
				}
			};
			items.Add("helmet", value);
			items.Add("chest", value2);
			items.Add("legs", value3);
			items.Add("cape", value4);
		}
	}
	public class Warrior : ArmorSetConfig
	{
		public Warrior()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			SetEffect obj = new SetEffect
			{
				healthRegenModifier = 10
			};
			SkillModifier skillModifier = new SkillModifier();
			SkillType val = (SkillType)4;
			skillModifier.skill = ((object)(SkillType)(ref val)).ToString();
			skillModifier.modifier = 15;
			obj.skillModifier = skillModifier;
			setEffect = obj;
			Dictionary<string, string> damageModifiers = setEffect.damageModifiers;
			DamageType val2 = (DamageType)2;
			string? key = ((object)(DamageType)(ref val2)).ToString();
			DamageModifier val3 = (DamageModifier)1;
			damageModifiers[key] = ((object)(DamageModifier)(ref val3)).ToString();
			int armor = 6;
			int weight = 15;
			int movementSpeedModifier = -5;
			ArmorConfig value = new ArmorConfig
			{
				prefabName = "ArmorWarriorHelmet",
				armor = armor,
				weight = weight,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Bronze",
							amount = 5,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 3,
							amountPerLevel = 1
						}
					}
				}
			};
			ArmorConfig value2 = new ArmorConfig
			{
				prefabName = "ArmorWarriorChest",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Bronze",
							amount = 5,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 3,
							amountPerLevel = 1
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Stone",
							amount = 20,
							amountPerLevel = 0
						},
						new RecipeConfig.RequirementConfig
						{
							item = "Raspberry",
							amount = 20,
							amountPerLevel = 0
						}
					}
				}
			};
			ArmorConfig value3 = new ArmorConfig
			{
				prefabName = "ArmorWarriorLegs",
				armor = armor,
				weight = weight,
				movementSpeedModifier = movementSpeedModifier,
				recipe = new RecipeConfig
				{
					station = "forge",
					requirements = new List<RecipeConfig.RequirementConfig>
					{
						new RecipeConfig.RequirementConfig
						{
							item = "Bronze",
							amount = 5,
							amountPerLevel = 3
						},
						new RecipeConfig.RequirementConfig
						{
							item = "DeerHide",
							amount = 3,
							amountPerLevel = 1
						}
					}
				}
			};
			items.Add("helmet", value);
			items.Add("chest", value2);
			items.Add("legs", value3);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[<d9681e9e-c3e5-4638-a0e6-5bf62a83c66a>Embedded]
	[CompilerGenerated]
	internal sealed class <d9681e9e-c3e5-4638-a0e6-5bf62a83c66a>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<d9681e9e-c3e5-4638-a0e6-5bf62a83c66a>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <89380e5c-033f-40c6-a7dd-9f097d380e02>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <89380e5c-033f-40c6-a7dd-9f097d380e02>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <89380e5c-033f-40c6-a7dd-9f097d380e02>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[<d9681e9e-c3e5-4638-a0e6-5bf62a83c66a>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(0)]
	[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
	internal abstract class OwnConfigEntryBase
	{
		[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(2)]
		public object LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(0)]
	[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
	[PublicAPI]
	internal class SyncedConfigEntry<[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(2)] T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(0)]
	[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(2)]
	internal abstract class CustomSyncedValueBase
	{
		public object LocalBaseValue;

		[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(1)]
		public readonly string Identifier;

		[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(1)]
		public readonly Type Type;

		private object boxedValue;

		protected bool localIsOwner;

		public object BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action ValueChanged;

		[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(0)]
	[PublicAPI]
	[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
	internal sealed class CustomSyncedValue<[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(2)] T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(0)]
	[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(0)]
		private static class SnatchCurrentlyHandlingRPC
		{
			[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(2)]
			public static ZRpc currentRpc;

			[HarmonyPrefix]
			[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					configSync2.IsSourceOfTruth = __instance.IsDedicated() || __instance.IsServer();
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_ConfigSync);
					if (isServer)
					{
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(0)]
		private static class RegisterClientRPCPatch
		{
			[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(1)]
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_InitialConfigSync);
				}
			}
		}

		[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(0)]
		private class ParsedConfigs
		{
			[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>();

			[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		[<661fe1ae-3aac-4fb9-ba05-97e7283a6ffa>NullableContext(0)]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
				}
				ProcessingServerUpdate = false;
			}
		}

		[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(0)]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			[<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(0)]
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix([<89380e5c-033f-40c6-a7dd-9f097d380e02>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNet

BepInEx/plugins/ishid4-BetterArchery/BetterArchery.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Auga;
using BepInEx;
using BepInEx.Configuration;
using Common;
using HarmonyLib;
using JetBrains.Annotations;
using LitJson;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: Guid("04f6ef99-721d-41d7-86e2-59ced874c902")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyProduct("BetterArchery")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("BetterArchery")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
namespace Common
{
	[Serializable]
	public class RecipeRequirementConfig
	{
		public string item = "";

		public int amount = 1;
	}
	[Serializable]
	public class RecipeConfig
	{
		public string name = "";

		public string item = "";

		public int amount = 1;

		public string craftingStation = "";

		public int minStationLevel = 1;

		public bool enabled = true;

		public string repairStation = "";

		public List<RecipeRequirementConfig> resources = new List<RecipeRequirementConfig>();
	}
	[Serializable]
	public class RecipesConfig
	{
		public List<RecipeConfig> recipes = new List<RecipeConfig>();
	}
	internal class CustomSlotItem : MonoBehaviour
	{
		public string m_slotName;
	}
	public static class CustomSlotCreator
	{
		public static readonly Dictionary<Humanoid, Dictionary<string, ItemData>> customSlotItemData = new Dictionary<Humanoid, Dictionary<string, ItemData>>();

		public static string GetCustomSlotName(ItemData item)
		{
			return item.m_dropPrefab.GetComponent<CustomSlotItem>().m_slotName;
		}

		public static bool IsCustomSlotItem(ItemData item)
		{
			return item != null && Object.op_Implicit((Object)(object)item.m_dropPrefab) && Object.op_Implicit((Object)(object)item.m_dropPrefab.GetComponent<CustomSlotItem>());
		}

		public static ItemData GetPrefabItemData(Humanoid humanoid, string slotName)
		{
			if (!DoesSlotExist(humanoid, slotName))
			{
				return null;
			}
			return customSlotItemData[humanoid][slotName].m_dropPrefab.GetComponent<ItemDrop>().m_itemData;
		}

		public static ItemData GetSlotItem(Humanoid humanoid, string slotName)
		{
			if (DoesSlotExist(humanoid, slotName))
			{
				return customSlotItemData[humanoid][slotName];
			}
			return null;
		}

		public static void SetSlotItem(Humanoid humanoid, string slotName, ItemData item)
		{
			customSlotItemData[humanoid][slotName] = item;
		}

		public static bool DoesSlotExist(Humanoid humanoid, string slotName)
		{
			return customSlotItemData[humanoid] != null && customSlotItemData[humanoid].ContainsKey(slotName);
		}

		public static bool IsSlotOccupied(Humanoid humanoid, string slotName)
		{
			return customSlotItemData[humanoid] != null && customSlotItemData[humanoid].ContainsKey(slotName) && customSlotItemData[humanoid][slotName] != null;
		}

		public static void ApplyCustomSlotItem(GameObject prefab, string slotName)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)prefab.GetComponent<CustomSlotItem>()))
			{
				prefab.AddComponent<CustomSlotItem>();
			}
			prefab.GetComponent<CustomSlotItem>().m_slotName = slotName;
			prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_itemType = (ItemType)0;
			Debug.Log((object)("[CustomSlotCreator] Created " + slotName + " slot for " + ((Object)prefab).name + "."));
		}
	}
	public static class PrefabCreator
	{
		public static Dictionary<string, CraftingStation> CraftingStations;

		public static T RequireComponent<T>(GameObject go) where T : Component
		{
			T val = go.GetComponent<T>();
			if ((Object)(object)val == (Object)null)
			{
				val = go.AddComponent<T>();
			}
			return val;
		}

		public static void Reset()
		{
			CraftingStations = null;
		}

		private static void InitCraftingStations()
		{
			if (CraftingStations != null)
			{
				return;
			}
			CraftingStations = new Dictionary<string, CraftingStation>();
			foreach (Recipe recipe in ObjectDB.instance.m_recipes)
			{
				if ((Object)(object)recipe.m_craftingStation != (Object)null && !CraftingStations.ContainsKey(((Object)recipe.m_craftingStation).name))
				{
					CraftingStations.Add(((Object)recipe.m_craftingStation).name, recipe.m_craftingStation);
				}
			}
		}

		public static Recipe CreateRecipe(string name, string itemId, RecipeConfig recipeConfig)
		{
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Expected O, but got Unknown
			InitCraftingStations();
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(itemId);
			if ((Object)(object)itemPrefab == (Object)null)
			{
				Debug.LogWarning((object)("[PrefabCreator] Could not find item prefab (" + itemId + ")"));
				return null;
			}
			Recipe val = ScriptableObject.CreateInstance<Recipe>();
			((Object)val).name = name;
			val.m_amount = recipeConfig.amount;
			val.m_minStationLevel = recipeConfig.minStationLevel;
			val.m_item = itemPrefab.GetComponent<ItemDrop>();
			val.m_enabled = recipeConfig.enabled;
			if (!string.IsNullOrEmpty(recipeConfig.craftingStation))
			{
				if (!CraftingStations.ContainsKey(recipeConfig.craftingStation))
				{
					Debug.LogWarning((object)("[PrefabCreator] Could not find crafting station (" + itemId + "): " + recipeConfig.craftingStation));
					string text = string.Join(", ", CraftingStations.Keys);
					Debug.Log((object)("[PrefabCreator] Available Stations: " + text));
				}
				else
				{
					val.m_craftingStation = CraftingStations[recipeConfig.craftingStation];
				}
			}
			if (!string.IsNullOrEmpty(recipeConfig.repairStation))
			{
				if (!CraftingStations.ContainsKey(recipeConfig.repairStation))
				{
					Debug.LogWarning((object)("[PrefabCreator] Could not find repair station (" + itemId + "): " + recipeConfig.repairStation));
					string text2 = string.Join(", ", CraftingStations.Keys);
					Debug.Log((object)("[PrefabCreator] Available Stations: " + text2));
				}
				else
				{
					val.m_repairStation = CraftingStations[recipeConfig.repairStation];
				}
			}
			List<Requirement> list = new List<Requirement>();
			foreach (RecipeRequirementConfig resource in recipeConfig.resources)
			{
				GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab(resource.item);
				if ((Object)(object)itemPrefab2 == (Object)null)
				{
					Debug.LogError((object)("[PrefabCreator] Could not find requirement item (" + itemId + "): " + resource.item));
					continue;
				}
				list.Add(new Requirement
				{
					m_amount = resource.amount,
					m_resItem = itemPrefab2.GetComponent<ItemDrop>()
				});
			}
			val.m_resources = list.ToArray();
			return val;
		}

		public static Recipe AddNewRecipe(string name, string itemId, RecipeConfig recipeConfig)
		{
			Recipe val = CreateRecipe(name, itemId, recipeConfig);
			if ((Object)(object)val == (Object)null)
			{
				Debug.LogError((object)("[PrefabCreator] Failed to create recipe (" + name + ")"));
				return null;
			}
			return AddNewRecipe(val);
		}

		public static Recipe AddNewRecipe(Recipe recipe)
		{
			int num = ObjectDB.instance.m_recipes.RemoveAll((Recipe x) => ((Object)x).name == ((Object)recipe).name);
			if (num > 0)
			{
				Debug.Log((object)$"[PrefabCreator] Removed recipe ({((Object)recipe).name}): {num}");
			}
			ObjectDB.instance.m_recipes.Add(recipe);
			Debug.Log((object)("[PrefabCreator] Added recipe: " + ((Object)recipe).name));
			return recipe;
		}
	}
	public static class Utils
	{
		public static void PrintObject(object o)
		{
			if (o == null)
			{
				Debug.Log((object)"null");
			}
			else
			{
				Debug.Log((object)(o?.ToString() + ":\n" + GetObjectString(o, "  ")));
			}
		}

		public static string GetObjectString(object obj, string indent)
		{
			string text = "";
			Type type = obj.GetType();
			IEnumerable<FieldInfo> enumerable = from f in type.GetFields()
				where f.IsPublic
				select f;
			foreach (FieldInfo item in enumerable)
			{
				object value = item.GetValue(obj);
				string text2 = ((value == null) ? "null" : value.ToString());
				text = text + "\n" + indent + item.Name + ": " + text2;
			}
			return text;
		}

		public static Sprite LoadSpriteFromFile(string spritePath)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			spritePath = Path.Combine(Paths.PluginPath, spritePath);
			if (File.Exists(spritePath))
			{
				byte[] array = File.ReadAllBytes(spritePath);
				Texture2D val = new Texture2D(20, 20);
				if (ImageConversion.LoadImage(val, array))
				{
					return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), default(Vector2), 100f);
				}
			}
			return null;
		}

		public static Sprite LoadSpriteFromFile(string modFolder, string iconName)
		{
			string spritePath = Path.Combine(modFolder, iconName);
			return LoadSpriteFromFile(spritePath);
		}

		public static bool IsServer()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			return ZNet.instance.IsServer() || ZNet.instance.IsDedicated() || (int)SystemInfo.graphicsDeviceType == 4;
		}
	}
}
namespace BetterArchery
{
	public class Arrow
	{
		public float SpawnChance { get; set; }

		public string SpawnArrow { get; set; }
	}
	[BepInPlugin("ishid4.mods.betterarchery", "Better Archery", "1.9.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class BetterArchery : BaseUnityPlugin
	{
		public enum ZoomState
		{
			Fixed,
			ZoomingIn,
			ZoomingOut
		}

		public static bool zoomSFX;

		public static Dictionary<string, Dictionary<string, AudioClip>> customSFXDict = new Dictionary<string, Dictionary<string, AudioClip>>();

		public static bool speedReduction;

		public static bool isContainerOpen;

		public static float ZoomInTimer = 0f;

		public static float ZoomOutTimer;

		public static float ZoomOutDelayTimer = 0f;

		public static float __BaseFov;

		public static float __LastZoomFov;

		public static float __NewZoomFov = 0f;

		public static ZoomState __ZoomState;

		public const int QuiverUseSlotCount = 3;

		public static int QuiverRowIndex = 0;

		public static ConfigEntry<KeyboardShortcut> HoldingKeyCode;

		public static ConfigEntry<KeyboardShortcut>[] KeyCodes = new ConfigEntry<KeyboardShortcut>[3];

		public static ConfigEntry<float>[] ArrowRetrieveChance = new ConfigEntry<float>[11];

		public static ConfigEntry<string>[] ArrowRetrieveSpawnType = new ConfigEntry<string>[11];

		public static List<Arrow> ArrowRetrieves = new List<Arrow>();

		public static ConfigEntry<float> ArrowDisappearTime;

		public static ConfigEntry<bool> ArrowDisappearOnHit;

		public static ConfigEntry<bool> ArrowRetrieveOldVersion;

		public static ConfigEntry<Vector2> InventoryQuiverSlotLocation;

		public static ConfigEntry<Vector2> InventoryQuiverSlotLocationWithContainer;

		public static ConfigEntry<bool> QuiverHudEnabled;

		public static ConfigEntry<float> ArrowVelocity;

		public static ConfigEntry<float> ArrowGravity;

		public static ConfigEntry<float> ArrowAccuracy;

		public static ConfigEntry<Vector3> ArrowAimDir;

		public static ConfigEntry<bool> configQuiverEnabled;

		public static ConfigEntry<bool> configArrowImprovementsEnabled;

		public static ConfigEntry<bool> configRetrievableArrowsEnabled;

		public static ConfigEntry<bool> configBowZoomEnabled;

		public static ConfigEntry<KeyboardShortcut> BowDrawCancelKey;

		public static ConfigEntry<float> BowZoomFactor;

		public static ConfigEntry<bool> AutomaticBowZoom;

		public static ConfigEntry<KeyboardShortcut> BowZoomKey;

		public static ConfigEntry<float> BowZoomConstantTime;

		public static ConfigEntry<bool> BowZoomSFXEnabled;

		public static ConfigEntry<float> StayInZoomTime;

		public static ConfigEntry<bool> IsCrosshairVisible;

		public static ConfigEntry<bool> IsBowCrosshairVisible;

		public static ConfigEntry<bool> ShowSneakDamage;

		public static ConfigEntry<bool> BowDrawMovementSpeedReductionEnabled;

		public static ConfigEntry<int> _DebugLevel;

		public static RecipesConfig Recipes;

		public static ConfigEntry<bool> WoodenArrowEverywhereEnabled;

		public static readonly Dictionary<string, GameObject> Prefabs = new Dictionary<string, GameObject>();

		public static ConfigEntry<int> nexusID;

		public static AudioSource playerAudioSource;

		private Harmony _harmony;

		public static BetterArchery _instance;

		public static bool HasAuga { get; private set; }

		public static void Log(string str = "", int warningType = 2)
		{
			if (_DebugLevel.Value == 0)
			{
				return;
			}
			if (warningType == 0)
			{
				Debug.LogError((object)("[" + typeof(BetterArchery).Namespace + "]: " + str));
			}
			if (_DebugLevel.Value > 1)
			{
				if (warningType == 1)
				{
					Debug.LogWarning((object)("[" + typeof(BetterArchery).Namespace + "]: " + str));
				}
				if (_DebugLevel.Value > 2 && warningType == 2)
				{
					Debug.Log((object)("[" + typeof(BetterArchery).Namespace + "]: " + str));
				}
			}
		}

		private void Awake()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			_instance = this;
			configQuiverEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Quiver", "Enable Quiver", true, "Enable the quiver. Don't change this value while in the game. If you disable this while arrows are in the quiver, you will LOSE ALL OF THEM!");
			InventoryQuiverSlotLocation = ((BaseUnityPlugin)this).Config.Bind<Vector2>("Quiver", "Change location of inventory quiver slot", new Vector2(3f, -25f), "Change quiver slot inventory location. For 'More Slots' you can use this location, 'x:3.0, y:-167.0'.");
			InventoryQuiverSlotLocationWithContainer = ((BaseUnityPlugin)this).Config.Bind<Vector2>("Quiver", "Change location of inventory quiver slot when a chest opened", new Vector2(3f, -425f), "Change quiver slot inventory location when a chest opened.");
			QuiverHudEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Quiver", "Enable Quiver Hud", true, "Enable the quiver's hotbar on the screen/hud. This doesn't affect inventory.");
			HoldingKeyCode = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Quiver", "Quiver slot hotkey holding key", new KeyboardShortcut((KeyCode)308, Array.Empty<KeyCode>()), "Change holding key. For the inputs: https://docs.unity3d.com/ScriptReference/KeyCode.html");
			KeyCodes[0] = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Quiver", "Quiver slot hotkey 1", new KeyboardShortcut((KeyCode)49, Array.Empty<KeyCode>()), "Hotkey for Quiver Slot 1. For the inputs: https://docs.unity3d.com/ScriptReference/KeyCode.html");
			KeyCodes[1] = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Quiver", "Quiver slot hotkey 2", new KeyboardShortcut((KeyCode)50, Array.Empty<KeyCode>()), "Hotkey for Quiver Slot 2. For the inputs: https://docs.unity3d.com/ScriptReference/KeyCode.html");
			KeyCodes[2] = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Quiver", "Quiver slot hotkey 3", new KeyboardShortcut((KeyCode)51, Array.Empty<KeyCode>()), "Hotkey for Quiver Slot 3. For the inputs: https://docs.unity3d.com/ScriptReference/KeyCode.html");
			configArrowImprovementsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Arrow Improvements", "Enable Arrow Improvements", true, "Arrow improvements including aim problems fixes, gravity changes.");
			ArrowVelocity = ((BaseUnityPlugin)this).Config.Bind<float>("Arrow Improvements", "Set Arrow Velocity", 70f, "Change the arrow's velocity. Vanilla is '60'.");
			ArrowGravity = ((BaseUnityPlugin)this).Config.Bind<float>("Arrow Improvements", "Set Arrow Gravity", 15f, "Change the arrow's gravity. Vanilla is '5'.");
			ArrowAccuracy = ((BaseUnityPlugin)this).Config.Bind<float>("Arrow Improvements", "Set Arrow Accuracy", 0f, "Change the arrow's accuracy. Vanilla is '-1'.");
			ArrowAimDir = ((BaseUnityPlugin)this).Config.Bind<Vector3>("Arrow Improvements", "Set Aim Direction", new Vector3(0f, 0.05f, 0f), "Change the aim direction. Vanilla is 'x:0.0, y:0.0, z: 0.0'.");
			configBowZoomEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Bow Zoom", "Enable Bow Zoom", true, "Enable the zooming with bow.");
			AutomaticBowZoom = ((BaseUnityPlugin)this).Config.Bind<bool>("Bow Zoom", "Automatic Bow Zoom", false, "Zoom while drawing bow automatically.");
			BowZoomSFXEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Bow Zoom", "Enable Bow Zoom SFX", true, "Sound effects for zoom-in and zoom-out.");
			BowZoomFactor = ((BaseUnityPlugin)this).Config.Bind<float>("Bow Zoom", "Zoom Factor", 2f, "Max zoom.");
			BowZoomConstantTime = ((BaseUnityPlugin)this).Config.Bind<float>("Bow Zoom", "Bow Zoom Constant Time", -1f, "Change this value to '-1' if you don't want constant time while zooming. '1' is recommended.");
			BowZoomKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Bow Zoom", "Bow Zoom Hotkey", new KeyboardShortcut((KeyCode)324, Array.Empty<KeyCode>()), "Mouse0: Left Click, Mouse1: Right Click, Mouse2: Middle Click. For the other inputs: https://docs.unity3d.com/ScriptReference/KeyCode.html");
			BowDrawCancelKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Bow Zoom", "Bow Draw Cancel Hotkey", new KeyboardShortcut((KeyCode)101, Array.Empty<KeyCode>()), "Mouse0: Left Click, Mouse1: Right Click, Mouse2: Middle Click. For the other inputs: https://docs.unity3d.com/ScriptReference/KeyCode.html");
			StayInZoomTime = ((BaseUnityPlugin)this).Config.Bind<float>("Bow Zoom", "Stay In-Zoom Time", 2f, "Set the max time of staying on zoom while holding RMB after releasing an arrow.");
			IsCrosshairVisible = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Enable Crosshair", true, "You can hide your crosshair.");
			IsBowCrosshairVisible = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Enable Bow Crosshair", true, "You can hide your bow crosshair, circle one.");
			ShowSneakDamage = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Enable Sneak Damage Showing", true, "Show sneak damage at top left.");
			BowDrawMovementSpeedReductionEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Enable Bow Draw Movement Speed Reduction", true, "Set walk speed while drawing bow.");
			WoodenArrowEverywhereEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Other", "Enable Crafting Wooden Arrow Everywhere", true, "Enable to crafting wooden arrows without a crafting table.");
			configRetrievableArrowsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Retrievable Arrows", "Enable Retrievable Arrows", true, "Enable the retrievable arrows.");
			ArrowDisappearTime = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "Arrow Disappear Time", 60f, "Set arrow's disappear countdown time.");
			ArrowDisappearOnHit = ((BaseUnityPlugin)this).Config.Bind<bool>("Retrievable Arrows", "Arrow Disappear On Hit", false, "Make arrows disappear when they are not retrievable.");
			ArrowRetrieveOldVersion = ((BaseUnityPlugin)this).Config.Bind<bool>("Retrievable Arrows", "Enable Old Retrievable Version", false, "Instantly arrow drops to the ground on hit if retrievable. Enabling this will ignore 'Arrow Disappear On Hit' and 'Arrow Disappear Time' settings.");
			ArrowRetrieveChance[0] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Wooden Arrow", 0.2f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[1] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Flint Arrow", 0.3f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[2] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Bronze Arrow", 0.5f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[3] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Iron Arrow", 0.7f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[4] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Obsidian Arrow", 0.7f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[5] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Needle Arrow", 0.1f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[6] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Fire Arrow", 0f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[7] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Poison Arrow", 0.7f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[8] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Silver Arrow", 0.5f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[9] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Frost Arrow", 0.7f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveChance[10] = ((BaseUnityPlugin)this).Config.Bind<float>("Retrievable Arrows", "ArrowRetrieveChance for Carapace Arrow", 0.7f, "Example: 0.9 for 90% chance to retrieve.");
			ArrowRetrieveSpawnType[0] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Wooden Arrow", "ArrowWood", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[1] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Flint Arrow", "ArrowFlint", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[2] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Bronze Arrow", "ArrowBronze", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[3] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Iron Arrow", "ArrowIron", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[4] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Obsidian Arrow", "ArrowObsidian", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[5] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Needle Arrow", "ArrowNeedle", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[6] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Fire Arrow", "ArrowFire", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[7] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Poison Arrow", "ArrowObsidian", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[8] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Silver Arrow", "ArrowSilver", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[9] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Frost Arrow", "ArrowObsidian", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			ArrowRetrieveSpawnType[10] = ((BaseUnityPlugin)this).Config.Bind<string>("Retrievable Arrows", "ArrowRetrieveSpawnType for Carapace Arrow", "ArrowCarapace", "https://valheim.fandom.com/wiki/Category:Arrows use internal ids.");
			for (int i = 0; i < ArrowRetrieveSpawnType.Length; i++)
			{
				ArrowRetrieves.Add(new Arrow
				{
					SpawnChance = ArrowRetrieveChance[i].Value,
					SpawnArrow = ArrowRetrieveSpawnType[i].Value
				});
			}
			nexusID = ((BaseUnityPlugin)this).Config.Bind<int>("Other", "NexusID", 348, "Nexus mod ID for updates.");
			_DebugLevel = ((BaseUnityPlugin)this).Config.Bind<int>("Other", "Set Debug Log Level", 1, "0: Nothing, 1: Only Errors, 2: Errors and Warnings, 3: Everyting");
			Recipes = LoadJsonFile<RecipesConfig>("BetterArcheryRecipes.json");
			if (configQuiverEnabled.Value)
			{
				AssetBundle val = LoadAssetBundle("quiverassets");
				if (Recipes != null && (Object)(object)val != (Object)null)
				{
					foreach (RecipeConfig recipe in Recipes.recipes)
					{
						if (val.Contains(recipe.item))
						{
							GameObject value = val.LoadAsset<GameObject>(recipe.item);
							Prefabs.Add(recipe.item, value);
						}
					}
				}
				if (val != null)
				{
					val.Unload(false);
				}
			}
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			HasAuga = API.IsLoaded();
		}

		public void Start()
		{
			HasAuga = API.IsLoaded();
			if (HasAuga)
			{
				Log("Auga Loaded.");
			}
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchAll((string)null);
			}
			foreach (GameObject value in Prefabs.Values)
			{
				Object.Destroy((Object)(object)value);
			}
			Prefabs.Clear();
		}

		private void Update()
		{
			if (!configQuiverEnabled.Value)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && ((Character)localPlayer).TakeInput())
			{
				for (int i = 0; i < 3; i++)
				{
					CheckQuiverUseInput(localPlayer, i);
				}
			}
		}

		public static string GetBindingLabel(int index)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			index = Mathf.Clamp(index, 0, 2);
			KeyCode bindingKeycode = GetBindingKeycode(index);
			if (((object)(KeyCode)(ref bindingKeycode)).ToString().Contains("Alpha"))
			{
				return ((object)(KeyCode)(ref bindingKeycode)).ToString().Replace("Alpha", "");
			}
			return ((object)(KeyCode)(ref bindingKeycode)).ToString().ToUpperInvariant();
		}

		public static KeyCode GetBindingKeycode(int index)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			index = Mathf.Clamp(index, 0, 2);
			KeyboardShortcut value = KeyCodes[index].Value;
			return ((KeyboardShortcut)(ref value)).MainKey;
		}

		public static int GetBonusInventoryRowIndex()
		{
			if ((Object)(object)Player.m_localPlayer != (Object)null && QuiverRowIndex != 0)
			{
				return QuiverRowIndex;
			}
			return 0;
		}

		public static void CheckQuiverUseInput(Player player, int index)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			KeyCode bindingKeycode = GetBindingKeycode(index);
			KeyboardShortcut value = HoldingKeyCode.Value;
			bool flag;
			if (!string.IsNullOrEmpty(((KeyboardShortcut)(ref value)).Serialize()))
			{
				value = HoldingKeyCode.Value;
				if (((KeyboardShortcut)(ref value)).Serialize() != "None")
				{
					value = HoldingKeyCode.Value;
					flag = Input.GetKey(((KeyboardShortcut)(ref value)).MainKey) && Input.GetKeyDown(bindingKeycode);
					goto IL_0070;
				}
			}
			flag = Input.GetKeyDown(bindingKeycode);
			goto IL_0070;
			IL_0070:
			if (flag)
			{
				int bonusInventoryRowIndex = GetBonusInventoryRowIndex();
				ItemData itemAt = ((Humanoid)player).GetInventory().GetItemAt(index, bonusInventoryRowIndex);
				if (itemAt != null)
				{
					((Humanoid)player).UseItem((Inventory)null, itemAt, false);
				}
			}
		}

		public static bool IsQuiverSlot(Vector2i pos)
		{
			//IL_0001: 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)
			return IsQuiverSlot(pos.x, pos.y);
		}

		public static bool IsQuiverSlot(int x, int y)
		{
			int bonusInventoryRowIndex = GetBonusInventoryRowIndex();
			return y == bonusInventoryRowIndex && x >= 0 && x < 3;
		}

		public static Vector2i GetQuiverSlotPosition(int index)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			int bonusInventoryRowIndex = GetBonusInventoryRowIndex();
			return new Vector2i(index, bonusInventoryRowIndex);
		}

		public static bool IsQuiverEquipped()
		{
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			return CustomSlotCreator.IsSlotOccupied((Humanoid)(object)Player.m_localPlayer, "quiver");
		}

		private static T LoadJsonFile<T>(string filename) where T : class
		{
			string assetPath = GetAssetPath(filename);
			if (!string.IsNullOrEmpty(assetPath))
			{
				string json = File.ReadAllText(assetPath);
				return JsonMapper.ToObject<T>(json);
			}
			return null;
		}

		public static AssetBundle LoadAssetBundle(string filename)
		{
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			AssetBundle result = AssetBundle.LoadFromStream(callingAssembly.GetManifestResourceStream(callingAssembly.GetName().Name + "." + filename));
			Log("Loaded AssetBundle (" + filename + ").", 3);
			Log(callingAssembly.GetName().Name);
			return result;
		}

		public static string GetAssetPath(string assetName, bool isDirectory = false)
		{
			string text = Path.Combine(Paths.PluginPath, "BetterArchery", assetName);
			if (isDirectory)
			{
				if (!Directory.Exists(text))
				{
					Assembly assembly = typeof(BetterArchery).Assembly;
					text = Path.Combine(Path.GetDirectoryName(assembly.Location), assetName);
					if (!Directory.Exists(text))
					{
						Log("Could not find directory (" + assetName + ").", 1);
						return null;
					}
				}
				return text;
			}
			if (!File.Exists(text))
			{
				Assembly assembly2 = typeof(BetterArchery).Assembly;
				text = Path.Combine(Path.GetDirectoryName(assembly2.Location), assetName);
				if (!File.Exists(text))
				{
					Log("Could not find asset (" + assetName + ").", 1);
					return null;
				}
			}
			return text;
		}

		public static void TryCreateCustomSlot(ZNetScene zNetScene)
		{
			if (!((Object)(object)zNetScene == (Object)null) && configQuiverEnabled.Value)
			{
				GameObject prefab = zNetScene.GetPrefab("LeatherQuiver");
				CustomSlotCreator.ApplyCustomSlotItem(prefab, "quiver");
			}
		}

		public static void TryCreateCustomSFX()
		{
			if (!configBowZoomEnabled.Value || !BowZoomSFXEnabled.Value)
			{
				return;
			}
			string assetPath = GetAssetPath("SFX", isDirectory: true);
			if (string.IsNullOrEmpty(assetPath))
			{
				Log("SFX folder not found.");
				return;
			}
			Log("path: " + assetPath);
			string[] directories = Directory.GetDirectories(assetPath);
			foreach (string path in directories)
			{
				Log("Checking folder " + Path.GetFileName(path));
				customSFXDict[Path.GetFileName(path)] = new Dictionary<string, AudioClip>();
				string[] files = Directory.GetFiles(path);
				foreach (string path2 in files)
				{
					if (Path.GetExtension(path2).ToLower().Equals(".wav"))
					{
						Log("Checking file " + Path.GetFileName(path2));
						((MonoBehaviour)_instance).StartCoroutine(LoadSFXCoroutine(path2, customSFXDict[Path.GetFileName(path)]));
					}
				}
			}
		}

		public static void PlayCustomSFX(string name, bool checkIfPlaying = true)
		{
			if ((Object)(object)playerAudioSource == (Object)null || !BowZoomSFXEnabled.Value)
			{
				return;
			}
			ZSFX component = ((Component)playerAudioSource).GetComponent<ZSFX>();
			if (!(component.IsPlaying() && checkIfPlaying))
			{
				if (customSFXDict.ContainsKey(name))
				{
					component.m_audioClips = customSFXDict[name].Values.ToArray();
					component.Play();
				}
				else
				{
					Log("SFX not found.", 0);
				}
			}
		}

		public static IEnumerator LoadSFXCoroutine(string path, Dictionary<string, AudioClip> dict)
		{
			path = "file:///" + path;
			UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20);
			try
			{
				yield return www.SendWebRequest();
				if (www == null)
				{
					Log("ww error.", 0);
					yield break;
				}
				DownloadHandlerAudioClip dh = (DownloadHandlerAudioClip)www.downloadHandler;
				if (dh != null)
				{
					AudioClip ac = dh.audioClip;
					if ((Object)(object)ac != (Object)null)
					{
						((Object)ac).name = Path.GetFileNameWithoutExtension(path);
						if (!dict.ContainsKey(((Object)ac).name))
						{
							dict[((Object)ac).name] = ac;
						}
						Log("Added " + ((Object)ac).name + " SFX.");
						yield break;
					}
				}
				Log("Error while adding custom SFX.", 0);
			}
			finally
			{
				((IDisposable)www)?.Dispose();
			}
		}

		public static void TryRegisterPrefabs(ZNetScene zNetScene)
		{
			if ((Object)(object)zNetScene == (Object)null)
			{
				return;
			}
			foreach (GameObject value in Prefabs.Values)
			{
				if (!configQuiverEnabled.Value)
				{
					Log(((Object)value).name);
					if (((Object)value).name.Contains("Quiver"))
					{
						Debug.Log((object)("[PrefabCreator] " + ((Object)value).name + " prefab skipped."));
						continue;
					}
				}
				if (!zNetScene.m_prefabs.Contains(value))
				{
					zNetScene.m_prefabs.Add(value);
				}
			}
		}

		public static bool IsObjectDBReady()
		{
			return (Object)(object)ObjectDB.instance != (Object)null && ObjectDB.instance.m_items.Count != 0 && (Object)(object)ObjectDB.instance.GetItemPrefab("Amber") != (Object)null;
		}

		public static void TryRegisterItems()
		{
			if (!IsObjectDBReady())
			{
				return;
			}
			foreach (GameObject value in Prefabs.Values)
			{
				ItemDrop component = value.GetComponent<ItemDrop>();
				if ((Object)(object)component != (Object)null)
				{
					if (!configQuiverEnabled.Value && ((Object)component.m_itemData.m_dropPrefab).name.Contains("Quiver"))
					{
						Debug.Log((object)("[PrefabCreator] Skipped prefab: " + ((Object)component.m_itemData.m_dropPrefab).name));
					}
					else if ((Object)(object)ObjectDB.instance.GetItemPrefab(StringExtensionMethods.GetStableHashCode(((Object)value).name)) == (Object)null)
					{
						component.m_itemData.m_dropPrefab = value;
						ObjectDB.instance.m_items.Add(value);
					}
				}
			}
			ObjectDB.instance.UpdateItemHashes();
		}

		public static void TryRegisterRecipes()
		{
			if (!IsObjectDBReady())
			{
				return;
			}
			PrefabCreator.Reset();
			foreach (RecipeConfig recipe in Recipes.recipes)
			{
				if (!configQuiverEnabled.Value && recipe.item.Contains("Quiver"))
				{
					Debug.Log((object)("[PrefabCreator] Skipped recipe: " + recipe.name));
				}
				else if (!WoodenArrowEverywhereEnabled.Value && recipe.name == "Recipe_ArrowWoodAnywhere")
				{
					Debug.Log((object)("[PrefabCreator] Skipped recipe: " + recipe.name));
				}
				else
				{
					PrefabCreator.AddNewRecipe(recipe.name, recipe.item, recipe);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "InputText")]
	public static class InputText_Patch
	{
		public static bool Prefix(Terminal __instance)
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			string text = ((TMP_InputField)__instance.m_input).text.ToLower();
			if (text.Equals("ba reload"))
			{
				((BaseUnityPlugin)BetterArchery._instance).Config.Reload();
				__instance.AddString("Better Archery Reloaded.");
				return false;
			}
			if (text.Equals("ba drop"))
			{
				Inventory inventory = ((Humanoid)Player.m_localPlayer).m_inventory;
				for (int num = inventory.m_inventory.Count - 1; num >= 0; num--)
				{
					ItemData val = inventory.m_inventory[num];
					if (val.m_gridPos.y >= 5 && !BetterArchery.IsQuiverSlot(val.m_gridPos))
					{
						BetterArchery.Log($"Found {((Object)val.m_dropPrefab).name} x {val.m_stack} in invisible slots; attempting to drop.");
						((Humanoid)Player.m_localPlayer).DropItem(inventory, val, val.m_stack);
					}
				}
				return false;
			}
			if (text.Equals("ba god"))
			{
				Player.m_localPlayer.SetGodMode(!Player.m_localPlayer.m_godMode);
				Player.m_localPlayer.SetNoPlacementCost(!Player.m_localPlayer.m_noPlacementCost);
				Player.m_localPlayer.m_staminaRegenDelay = 0.05f;
				Player.m_localPlayer.m_staminaRegen = 999f;
				Player.m_localPlayer.m_runStaminaDrain = 0f;
				Player.m_localPlayer.SetMaxStamina(9999f, true);
				((Character)Player.m_localPlayer).AddStamina(999f);
				return false;
			}
			if (text.Equals("ba clear"))
			{
				((Humanoid)Player.m_localPlayer).GetInventory().RemoveAll();
				return false;
			}
			if (text.Equals("ba sfx"))
			{
				BetterArchery.PlayCustomSFX("exhale");
				return false;
			}
			if (text.Equals("ba kill"))
			{
				((Character)Player.m_localPlayer).SetHealth(0f);
				return false;
			}
			if (text.Equals("ba fill"))
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch]
	public class Patches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(ItemData), "IsEquipable")]
		private static void IsEquipablePostfix(ref bool __result, ref ItemData __instance)
		{
			__result = __result || CustomSlotCreator.IsCustomSlotItem(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Humanoid), "Awake")]
		private static void HumanoidEntryPostfix(ref Humanoid __instance)
		{
			CustomSlotCreator.customSlotItemData[__instance] = new Dictionary<string, ItemData>();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "Load")]
		private static void InventoryLoadPostfix(ref Player __instance)
		{
			foreach (ItemData equippedItem in ((Humanoid)__instance).m_inventory.GetEquippedItems())
			{
				if (CustomSlotCreator.IsCustomSlotItem(equippedItem))
				{
					string customSlotName = CustomSlotCreator.GetCustomSlotName(equippedItem);
					CustomSlotCreator.SetSlotItem((Humanoid)(object)__instance, customSlotName, equippedItem);
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "EquipItem")]
		[HarmonyPostfix]
		private static void EquipItemPostfix(ref bool __result, ref Humanoid __instance, ItemData item, bool triggerEquipEffects = true)
		{
			if (CustomSlotCreator.IsCustomSlotItem(item))
			{
				string customSlotName = CustomSlotCreator.GetCustomSlotName(item);
				if (CustomSlotCreator.IsSlotOccupied(__instance, customSlotName))
				{
					__instance.UnequipItem(CustomSlotCreator.GetSlotItem(__instance, customSlotName), triggerEquipEffects);
				}
				CustomSlotCreator.SetSlotItem(__instance, customSlotName, item);
				if (__instance.IsItemEquiped(item))
				{
					item.m_equipped = true;
				}
				__instance.SetupEquipment();
				if (triggerEquipEffects)
				{
					__instance.TriggerEquipEffect(item);
				}
				__result = true;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
		private static void UnequipItemPostfix(ref Humanoid __instance, ItemData item, bool triggerEquipEffects = true)
		{
			if (CustomSlotCreator.IsCustomSlotItem(item))
			{
				string customSlotName = CustomSlotCreator.GetCustomSlotName(item);
				if (item == CustomSlotCreator.GetSlotItem(__instance, customSlotName))
				{
					CustomSlotCreator.SetSlotItem(__instance, customSlotName, null);
				}
				__instance.UpdateEquipmentStatusEffects();
			}
		}

		[HarmonyPatch(typeof(Humanoid), "IsItemEquiped")]
		[HarmonyPostfix]
		private static void IsItemEquipedPostfix(ref bool __result, ref Humanoid __instance, ItemData item)
		{
			if (CustomSlotCreator.IsCustomSlotItem(item))
			{
				string customSlotName = CustomSlotCreator.GetCustomSlotName(item);
				bool flag = CustomSlotCreator.DoesSlotExist(__instance, customSlotName) && CustomSlotCreator.GetSlotItem(__instance, customSlotName) == item;
				__result |= flag;
			}
		}

		[HarmonyPatch(typeof(Humanoid), "GetEquipmentWeight")]
		[HarmonyPostfix]
		private static void GetEquipmentWeightPostfix(ref float __result, ref Humanoid __instance)
		{
			foreach (string key in CustomSlotCreator.customSlotItemData[__instance].Keys)
			{
				if (CustomSlotCreator.IsSlotOccupied(__instance, key))
				{
					__result += CustomSlotCreator.GetSlotItem(__instance, key).m_shared.m_weight;
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "UnequipAllItems")]
		[HarmonyPostfix]
		private static void UnequipAllItemsPostfix(ref Humanoid __instance)
		{
			foreach (string item in CustomSlotCreator.customSlotItemData[__instance].Keys.ToList())
			{
				if (CustomSlotCreator.IsSlotOccupied(__instance, item))
				{
					__instance.UnequipItem(CustomSlotCreator.GetSlotItem(__instance, item), false);
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "GetSetCount")]
		[HarmonyPostfix]
		private static void GetSetCountPostfix(ref int __result, ref Humanoid __instance, string setName)
		{
			foreach (string item in CustomSlotCreator.customSlotItemData[__instance].Keys.ToList())
			{
				if (CustomSlotCreator.IsSlotOccupied(__instance, item) && CustomSlotCreator.GetSlotItem(__instance, item).m_shared.m_setName == setName)
				{
					__result++;
				}
			}
		}

		public static HashSet<StatusEffect> GetStatusEffectsFromCustomSlotItems(Humanoid __instance)
		{
			HashSet<StatusEffect> hashSet = new HashSet<StatusEffect>();
			foreach (string key in CustomSlotCreator.customSlotItemData[__instance].Keys)
			{
				if (CustomSlotCreator.IsSlotOccupied(__instance, key))
				{
					if (Object.op_Implicit((Object)(object)CustomSlotCreator.GetSlotItem(__instance, key).m_shared.m_equipStatusEffect))
					{
						StatusEffect equipStatusEffect = CustomSlotCreator.GetSlotItem(__instance, key).m_shared.m_equipStatusEffect;
						hashSet.Add(equipStatusEffect);
					}
					if (__instance.HaveSetEffect(CustomSlotCreator.GetSlotItem(__instance, key)))
					{
						StatusEffect setStatusEffect = CustomSlotCreator.GetSlotItem(__instance, key).m_shared.m_setStatusEffect;
						hashSet.Add(setStatusEffect);
					}
				}
			}
			return hashSet;
		}
	}
	[HarmonyPatch(typeof(InventoryGrid), "OnLeftClick")]
	public static class InventoryGrid_OnLeftClick_Patch
	{
		public static bool Prefix(InventoryGrid __instance, UIInputHandler clickHandler)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (!BetterArchery.configQuiverEnabled.Value)
			{
				return true;
			}
			GameObject gameObject = ((Component)clickHandler).gameObject;
			Vector2i buttonPos = __instance.GetButtonPos(gameObject);
			ItemData itemAt = __instance.m_inventory.GetItemAt(buttonPos.x, buttonPos.y);
			if ((Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305)) && itemAt != null && itemAt.m_equipped && ((Object)itemAt.m_dropPrefab).name.Contains("Quiver"))
			{
				MessageHud.instance.ShowMessage((MessageType)2, "You can't drop the quiver while equipped.", 0, (Sprite)null);
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(InventoryGrid), "UpdateGui", new Type[]
	{
		typeof(Player),
		typeof(ItemData)
	})]
	public static class InventoryGrid_UpdateGui_Patch
	{
		public static Vector2 customLocation;

		private static void Postfix(InventoryGrid __instance, Player player, ItemData dragItem, List<Element> ___m_elements)
		{
			if (((Object)__instance).name != "PlayerGrid" || !BetterArchery.configQuiverEnabled.Value)
			{
				return;
			}
			if (__instance.GetInventory().GetHeight() > 5)
			{
				if (GetElement(___m_elements, 7, __instance.GetInventory().GetHeight() - 1).m_go.activeSelf)
				{
					for (int i = __instance.GetInventory().GetHeight() - 2; i < __instance.GetInventory().GetHeight(); i++)
					{
						for (int j = 0; j < 8; j++)
						{
							Element element = GetElement(___m_elements, j, i);
							element.m_go.SetActive(false);
						}
					}
				}
			}
			else if (GetElement(___m_elements, 7, __instance.GetInventory().GetHeight() - 1).m_go.activeSelf)
			{
				for (int k = __instance.GetInventory().GetHeight() - 1; k < __instance.GetInventory().GetHeight(); k++)
				{
					for (int l = 0; l < 8; l++)
					{
						Element element2 = GetElement(___m_elements, l, k);
						element2.m_go.SetActive(false);
					}
				}
			}
			if (BetterArchery.IsQuiverEquipped())
			{
				CreateQuiverSlots(__instance, ___m_elements);
			}
			else
			{
				RemoveQuiverSlots(__instance, ___m_elements);
			}
		}

		public static void CreateQuiverSlots(InventoryGrid __instance, List<Element> ___m_elements)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0412: Unknown result type (might be due to invalid IL or missing references)
			//IL_044a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_032c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			//IL_0373: Unknown result type (might be due to invalid IL or missing references)
			//IL_0378: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = (BetterArchery.isContainerOpen ? BetterArchery.InventoryQuiverSlotLocationWithContainer.Value : BetterArchery.InventoryQuiverSlotLocation.Value);
			Transform val2 = ((Component)__instance).transform.parent.Find("QuiverSlotBkg");
			if (Object.op_Implicit((Object)(object)val2) && customLocation == val)
			{
				return;
			}
			int bonusInventoryRowIndex = BetterArchery.GetBonusInventoryRowIndex();
			customLocation = (BetterArchery.isContainerOpen ? BetterArchery.InventoryQuiverSlotLocationWithContainer.Value : BetterArchery.InventoryQuiverSlotLocation.Value);
			KeyboardShortcut value;
			KeyCode mainKey;
			if (BetterArchery.HasAuga)
			{
				int num;
				Element element;
				Text component;
				Vector2 val3;
				Vector2 val4 = default(Vector2);
				Transform transform;
				for (int i = 0; i < 3; ((Graphic)component).rectTransform.anchoredPosition = new Vector2(1f, 14f), val3 = customLocation, ((Vector2)(ref val4))..ctor((float)num * __instance.m_elementSpace, 4f * (0f - __instance.m_elementSpace) + 30f), transform = element.m_go.transform, ((RectTransform)((transform is RectTransform) ? transform : null)).anchoredPosition = val3 + val4, i++)
				{
					num = i;
					element = GetElement(___m_elements, num, bonusInventoryRowIndex);
					element.m_go.SetActive(true);
					component = ((Component)element.m_go.transform.Find("binding")).GetComponent<Text>();
					((Behaviour)component).enabled = true;
					component.horizontalOverflow = (HorizontalWrapMode)1;
					component.fontSize = 11;
					value = BetterArchery.HoldingKeyCode.Value;
					if (!string.IsNullOrEmpty(((KeyboardShortcut)(ref value)).Serialize()))
					{
						value = BetterArchery.HoldingKeyCode.Value;
						if (!(((KeyboardShortcut)(ref value)).Serialize() == "None"))
						{
							value = BetterArchery.HoldingKeyCode.Value;
							mainKey = ((KeyboardShortcut)(ref value)).MainKey;
							component.text = ((object)(KeyCode)(ref mainKey)).ToString() + " + " + BetterArchery.GetBindingLabel(i);
							continue;
						}
					}
					component.text = BetterArchery.GetBindingLabel(i);
				}
				RectTransform orCreateBackground = GetOrCreateBackground(__instance, "QuiverSlotBkg");
				orCreateBackground.anchoredPosition = new Vector2(-174f + customLocation.x, -235f + customLocation.y);
				orCreateBackground.SetSizeWithCurrentAnchors((Axis)0, 235f);
				orCreateBackground.SetSizeWithCurrentAnchors((Axis)1, 90f);
				((Transform)orCreateBackground).localScale = new Vector3(1f, 1f, 1f);
				return;
			}
			int num2;
			Element element2;
			Text component2;
			Vector2 val5;
			Vector2 val6 = default(Vector2);
			Transform transform2;
			for (int j = 0; j < 3; ((Graphic)component2).rectTransform.anchoredPosition = new Vector2(28f, -7f), val5 = customLocation, ((Vector2)(ref val6))..ctor((float)num2 * __instance.m_elementSpace, 4f * (0f - __instance.m_elementSpace)), transform2 = element2.m_go.transform, ((RectTransform)((transform2 is RectTransform) ? transform2 : null)).anchoredPosition = val5 + val6, j++)
			{
				num2 = j;
				element2 = GetElement(___m_elements, num2, bonusInventoryRowIndex);
				element2.m_go.SetActive(true);
				component2 = ((Component)element2.m_go.transform.Find("binding")).GetComponent<Text>();
				((Behaviour)component2).enabled = true;
				component2.horizontalOverflow = (HorizontalWrapMode)1;
				component2.fontSize = 12;
				value = BetterArchery.HoldingKeyCode.Value;
				if (!string.IsNullOrEmpty(((KeyboardShortcut)(ref value)).Serialize()))
				{
					value = BetterArchery.HoldingKeyCode.Value;
					if (!(((KeyboardShortcut)(ref value)).Serialize() == "None"))
					{
						value = BetterArchery.HoldingKeyCode.Value;
						mainKey = ((KeyboardShortcut)(ref value)).MainKey;
						component2.text = ((object)(KeyCode)(ref mainKey)).ToString() + " + " + BetterArchery.GetBindingLabel(j);
						continue;
					}
				}
				component2.text = BetterArchery.GetBindingLabel(j);
			}
			RectTransform orCreateBackground2 = GetOrCreateBackground(__instance, "QuiverSlotBkg");
			float num3 = 3f - customLocation.x;
			float num4 = -25f - customLocation.y;
			orCreateBackground2.anchoredPosition = new Vector2(-176f + (0f - num3), -200f + (0f - num4));
			orCreateBackground2.SetSizeWithCurrentAnchors((Axis)0, 235f);
			orCreateBackground2.SetSizeWithCurrentAnchors((Axis)1, 90f);
			((Transform)orCreateBackground2).localScale = new Vector3(1f, 1f, 1f);
		}

		public static void RemoveQuiverSlots(InventoryGrid __instance, List<Element> ___m_elements)
		{
			int bonusInventoryRowIndex = BetterArchery.GetBonusInventoryRowIndex();
			for (int i = 0; i < 3; i++)
			{
				int x = i;
				Element element = GetElement(___m_elements, x, bonusInventoryRowIndex);
				element.m_go.SetActive(false);
			}
			Transform val = ((Component)__instance).transform.parent.Find("QuiverSlotBkg");
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)val).gameObject);
			}
		}

		private static RectTransform GetOrCreateBackground(InventoryGrid __instance, string name)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			Transform val = ((Component)__instance).transform.parent.Find(name);
			if ((Object)(object)val != (Object)null)
			{
				return (RectTransform)(object)((val is RectTransform) ? val : null);
			}
			if (BetterArchery.HasAuga)
			{
				BetterArchery.Log("GetOrCreateBackground: Auga is Active!");
				Transform parent = ((Component)__instance).transform.parent;
				GameObject val2 = API.Panel_Create(((Component)parent).transform, new Vector2(10f, 10f), name, withCornerDecoration: true);
				Transform val3 = ((Component)__instance).transform.Find("Main");
				((Behaviour)((Component)val3).GetComponent<RectMask2D>()).enabled = false;
				((Behaviour)((Component)((Component)val3).transform.Find("Grid")).GetComponent<GridLayoutGroup>()).enabled = false;
				if (val3.localPosition.y > -40f)
				{
					val3.localPosition = Vector2.op_Implicit(new Vector2(val3.localPosition.x, -64f));
				}
				val2.transform.SetSiblingIndex(((Component)val3).transform.GetSiblingIndex() + 1);
				val = val2.transform;
				return (RectTransform)(object)((val is RectTransform) ? val : null);
			}
			GameObject gameObject = ((Component)((Component)__instance).transform.parent.Find("Bkg")).gameObject;
			GameObject val4 = Object.Instantiate<GameObject>(gameObject, gameObject.transform.parent);
			((Object)val4).name = name;
			val4.transform.SetSiblingIndex(gameObject.transform.GetSiblingIndex() + 1);
			val = val4.transform;
			return (RectTransform)(object)((val is RectTransform) ? val : null);
		}

		private static Element GetElement(List<Element> elements, int x, int y)
		{
			int width = ((Humanoid)Player.m_localPlayer).GetInventory().GetWidth();
			return elements[y * width + x];
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnSelectedItem", new Type[]
	{
		typeof(InventoryGrid),
		typeof(ItemData),
		typeof(Vector2i),
		typeof(Modifier)
	})]
	public static class InventoryGui_OnSelectedItem_Patch
	{
		public static bool Prefix(InventoryGui __instance, InventoryGrid grid, ItemData item, Vector2i pos, Modifier mod, GameObject ___m_dragGo, ItemData ___m_dragItem)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Invalid comparison between Unknown and I4
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Invalid comparison between Unknown and I4
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Invalid comparison between Unknown and I4
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			if (!BetterArchery.configQuiverEnabled.Value)
			{
				return true;
			}
			BetterArchery.isContainerOpen = __instance.IsContainerOpen();
			if (grid.m_inventory.m_name.Equals("Inventory") && BetterArchery.IsQuiverSlot(pos))
			{
				if (___m_dragItem != null && (int)___m_dragItem.m_shared.m_itemType == 9)
				{
					return true;
				}
				if (___m_dragItem != null && (int)___m_dragItem.m_shared.m_itemType != 9)
				{
					MessageHud.instance.ShowMessage((MessageType)2, "You can not put this inside of the quiver.", 0, (Sprite)null);
					return false;
				}
			}
			if (Object.op_Implicit((Object)(object)__instance.m_dragGo))
			{
				if (item != null && item.m_equipped && __instance.m_dragInventory != grid.GetInventory())
				{
					MessageHud.instance.ShowMessage((MessageType)2, "Unequip the item.", 0, (Sprite)null);
					return false;
				}
				if (item != null && (int)___m_dragItem.m_shared.m_itemType == 9 && BetterArchery.IsQuiverSlot(___m_dragItem.m_gridPos))
				{
					BetterArchery.Log("Can't swap this item.");
					return false;
				}
			}
			if (___m_dragItem != null && ___m_dragItem.m_equipped && __instance.m_dragInventory != grid.GetInventory())
			{
				MessageHud.instance.ShowMessage((MessageType)2, "Unequip the item before moving it.", 0, (Sprite)null);
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "UpdateContainer")]
	public static class InventoryGui_UpdateContainer_Patch
	{
		public static bool Prefix(InventoryGui __instance, Player player)
		{
			if (!BetterArchery.configQuiverEnabled.Value)
			{
				return true;
			}
			BetterArchery.isContainerOpen = Object.op_Implicit((Object)(object)__instance.m_currentContainer) && __instance.m_currentContainer.IsOwner();
			return true;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnDropOutside")]
	public static class InventoryGui_OnDropOutside_Patch
	{
		public static bool Prefix(GameObject ___m_dragGo, ItemData ___m_dragItem)
		{
			if (___m_dragItem != null && ___m_dragItem.m_equipped && BetterArchery.configQuiverEnabled.Value)
			{
				MessageHud.instance.ShowMessage((MessageType)2, "Unequip the item first.", 0, (Sprite)null);
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "OnCraftPressed")]
	public static class InventoryGui_OnCraftPressed_Patch
	{
		public static void Prefix(InventoryGui __instance)
		{
			if (Object.op_Implicit((Object)(object)__instance.m_selectedRecipe.Key))
			{
				__instance.m_craftRecipe = __instance.m_selectedRecipe.Key;
				if ((Object)(object)__instance.m_craftRecipe != (Object)null && ((Object)__instance.m_craftRecipe).name == "Recipe_ArrowWoodAnywhere")
				{
					__instance.m_craftDuration = 7f;
				}
				else
				{
					__instance.m_craftDuration = 2f;
				}
			}
		}
	}
	[HarmonyPatch(typeof(InventoryGui), "UpdateRecipeList")]
	public static class InventoryGui_UpdateRecipeList_Patch
	{
		public static void Prefix(InventoryGui __instance, List<Recipe> recipes)
		{
			Player localPlayer = Player.m_localPlayer;
			if (Object.op_Implicit((Object)(object)localPlayer.GetCurrentCraftingStation()))
			{
				Recipe val = recipes.Find((Recipe e) => ((Object)e).name == "Recipe_ArrowWoodAnywhere");
				if ((Object)(object)val != (Object)null)
				{
					recipes.Remove(val);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Inventory), "HaveEmptySlot")]
	public static class Inventory_HaveEmptySlot_Patch
	{
		[HarmonyPriority(800)]
		public static bool Prefix(Inventory __instance, ref bool __result)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.GetName() != "Inventory" || !BetterArchery.configQuiverEnabled.Value)
			{
				return true;
			}
			int num = __instance.m_width * __instance.m_height - 3 - 5;
			if (__instance.GetHeight() > 5)
			{
				num -= 8;
			}
			int num2 = __instance.m_inventory.Count;
			for (int i = 0; i < 3; i++)
			{
				Vector2i quiverSlotPosition = BetterArchery.GetQuiverSlotPosition(i);
				ItemData itemAt = __instance.GetItemAt(quiverSlotPosition.x, quiverSlotPosition.y);
				num2 -= ((itemAt != null) ? 1 : 0);
			}
			__result = num2 < num;
			return false;
		}
	}
	[HarmonyPatch(typeof(Inventory), "FindEmptySlot")]
	public static class Inventory_FindEmptySlot_Patch
	{
		[HarmonyPriority(800)]
		public static bool Prefix(Inventory __instance, ref Vector2i __result, bool topFirst, int ___m_height, int ___m_width)
		{
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.GetName() != "Inventory" || !BetterArchery.configQuiverEnabled.Value)
			{
				return true;
			}
			if (topFirst)
			{
				int num = __instance.GetHeight() - 1;
				if (__instance.GetHeight() > 5)
				{
					num--;
				}
				for (int i = 0; i < num; i++)
				{
					for (int j = 0; j < ___m_width; j++)
					{
						if (__instance.GetItemAt(j, i) == null)
						{
							__result = new Vector2i(j, i);
							return false;
						}
					}
				}
			}
			else
			{
				int num2 = __instance.GetHeight() - 1;
				if (__instance.GetHeight() > 5)
				{
					num2--;
				}
				for (int k = 1; k < num2; k++)
				{
					for (int l = 0; l < ___m_width; l++)
					{
						if (__instance.GetItemAt(l, k) == null)
						{
							__result = new Vector2i(l, k);
							return false;
						}
					}
				}
			}
			__result = new Vector2i(-1, -1);
			return false;
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
	public static class ObjectDB_CopyOtherDB_Patch
	{
		public static void Postfix()
		{
			BetterArchery.TryRegisterItems();
			BetterArchery.TryRegisterRecipes();
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	public static class ObjectDB_Awake_Patch
	{
		public static void Postfix()
		{
			BetterArchery.TryRegisterItems();
			BetterArchery.TryRegisterRecipes();
		}
	}
	public static class PlayerBody
	{
		public static Transform spine;

		public static Transform leftHand;

		public static bool onBowDrawing;
	}
	[HarmonyPatch(typeof(Player), "Awake")]
	public static class Player_Awake_Patch
	{
		[HarmonyPriority(0)]
		private static void Prefix(ref Player __instance)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			if (BetterArchery.configQuiverEnabled.Value)
			{
				Traverse.Create((object)__instance).Field("m_inventory").SetValue((object)new Inventory("Inventory", (Sprite)null, 8, ((Humanoid)__instance).m_inventory.m_height + 2));
				BetterArchery.Log($"Inventory h: {((Humanoid)__instance).m_inventory.m_height}");
				BetterArchery.QuiverRowIndex = ((Humanoid)__instance).m_inventory.m_height - 1;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "OnSpawned")]
	public static class ModifyOnSpawned
	{
		private static void Prefix(Player __instance)
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			TutorialText item = new TutorialText
			{
				m_label = "BetterArchery",
				m_name = "betterarchery",
				m_text = "Thank you for using this mod! Don't forget to change configurations to get your own taste!",
				m_topic = "Welcome to BetterArchery"
			};
			if (!Tutorial.instance.m_texts.Contains(item))
			{
				Tutorial.instance.m_texts.Add(item);
			}
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				return;
			}
			localPlayer.ShowTutorial("betterarchery", false);
			if (BetterArchery.configQuiverEnabled.Value)
			{
				foreach (ItemData equippedItem in ((Humanoid)__instance).m_inventory.GetEquippedItems())
				{
					if (CustomSlotCreator.IsCustomSlotItem(equippedItem))
					{
						equippedItem.m_equipped = true;
					}
					equippedItem.m_equipped = true;
				}
			}
			if (!BetterArchery.BowZoomSFXEnabled.Value)
			{
				return;
			}
			try
			{
				BetterArchery.playerAudioSource = ((Component)((Component)localPlayer).transform).gameObject.AddComponent<AudioSource>();
				((Component)((Component)localPlayer).transform).gameObject.AddComponent<ZSFX>();
			}
			catch (Exception ex)
			{
				BetterArchery.Log(ex.ToString(), 0);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "LateUpdate")]
	public static class Player_LateUpdate_Patch
	{
		public static float spineTimer = 0.5f;

		private static void Postfix(Player __instance, Transform ___m_head, ref Rigidbody ___m_body, ref VisEquipment ___m_visEquipment, ItemData ___m_rightItem, ItemData ___m_leftItem)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Invalid comparison between Unknown and I4
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer != (Object)(object)__instance)
			{
				return;
			}
			if ((Object)(object)PlayerBody.spine == (Object)null)
			{
				PlayerBody.spine = ((IEnumerable<Transform>)((Humanoid)__instance).m_visEquipment.m_bodyModel.bones).SingleOrDefault((Func<Transform, bool>)((Transform x) => ((Object)x).name == "Spine"));
			}
			Quaternion rotation;
			if (___m_leftItem != null && (int)___m_leftItem.m_shared.m_itemType == 4 && Object.op_Implicit((Object)(object)___m_body) && PlayerBody.onBowDrawing)
			{
				spineTimer = 0.5f;
				rotation = ((Component)((Character)__instance).m_eye).transform.rotation;
				float num = ((Quaternion)(ref rotation)).eulerAngles.y + 90f;
				Transform spine = PlayerBody.spine;
				rotation = PlayerBody.spine.rotation;
				float x2 = ((Quaternion)(ref rotation)).eulerAngles.x;
				rotation = ((Component)((Character)__instance).m_eye).transform.rotation;
				spine.rotation = Quaternion.Euler(x2, num, ((Quaternion)(ref rotation)).eulerAngles.x);
			}
			else if (spineTimer > 0f)
			{
				spineTimer -= Time.deltaTime;
				rotation = ((Component)((Character)__instance).m_eye).transform.rotation;
				float num2 = ((Quaternion)(ref rotation)).eulerAngles.y + 90f;
				Transform spine2 = PlayerBody.spine;
				rotation = PlayerBody.spine.rotation;
				float x3 = ((Quaternion)(ref rotation)).eulerAngles.x;
				rotation = ((Component)((Character)__instance).m_eye).transform.rotation;
				spine2.rotation = Quaternion.Euler(x3, num2, ((Quaternion)(ref rotation)).eulerAngles.x);
			}
		}
	}
	[HarmonyPatch(typeof(Player), "UseHotbarItem")]
	public static class Player_UseHotbarItem_Patch
	{
		public static bool Prefix(Player __instance)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			if (!BetterArchery.configQuiverEnabled.Value)
			{
				return true;
			}
			KeyboardShortcut value = BetterArchery.HoldingKeyCode.Value;
			if (!string.IsNullOrEmpty(((KeyboardShortcut)(ref value)).Serialize()))
			{
				value = BetterArchery.HoldingKeyCode.Value;
				if (((KeyboardShortcut)(ref value)).Serialize() != "None")
				{
					value = BetterArchery.HoldingKeyCode.Value;
					if (Input.GetKey(((KeyboardShortcut)(ref value)).MainKey))
					{
						return false;
					}
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Player), "QueueUnequipAction")]
	public static class Player_QueueUnequipAction_Patch
	{
		public static bool Prefix(ItemData item, Player __instance)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			if (!BetterArchery.configQuiverEnabled.Value)
			{
				return true;
			}
			if (((Object)item.m_dropPrefab).name.Contains("Quiver"))
			{
				Inventory inventory = ((Humanoid)Player.m_localPlayer).m_inventory;
				foreach (ItemData item2 in inventory.m_inventory)
				{
					if (BetterArchery.IsQuiverSlot(item2.m_gridPos) && item2.GetWeight() > 0f)
					{
						MessageHud.instance.ShowMessage((MessageType)2, "Empty the quiver first.", 0, (Sprite)null);
						return false;
					}
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Player), "SetControls")]
	public static class Player_SetControls_Patch
	{
		private static void Prefix(Player __instance, ref Vector3 movedir, ref bool attack, ref bool attackHold, ref bool secondaryAttack, ref bool block, ref bool blockHold, ref bool jump, ref bool crouch, ref bool run, ref bool autoRun)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!BetterArchery.configBowZoomEnabled.Value)
			{
				return;
			}
			if (attackHold)
			{
				KeyboardShortcut value = BetterArchery.BowDrawCancelKey.Value;
				if (Input.GetKey(((KeyboardShortcut)(ref value)).MainKey))
				{
					blockHold = true;
				}
				else
				{
					blockHold = false;
				}
			}
			else
			{
				ItemData leftItem = ((Humanoid)__instance).GetLeftItem();
				if (leftItem != null && ((Object)leftItem.m_dropPrefab).name.Contains("Bow") && BetterArchery.__ZoomState == BetterArchery.ZoomState.ZoomingIn)
				{
					blockHold = false;
				}
			}
		}
	}
	[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
	public static class Player_GameCamera_Patch
	{
		[HarmonyPriority(100)]
		private static void Postfix(GameCamera __instance, float dt, Vector3 pos, Quaternion rot)
		{
			if (!((Object)(object)__instance == (Object)null) && BetterArchery.configBowZoomEnabled.Value && BetterArchery.__BaseFov == 0f)
			{
				BetterArchery.__BaseFov = __instance.m_fov;
			}
		}
	}
	[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
	public static class Player_GameCamera_UpdateCamera
	{
		[HarmonyPriority(0)]
		public static void Prefix(GameCamera __instance)
		{
			if (BetterArchery.configBowZoomEnabled.Value && (BetterArchery.__ZoomState == BetterArchery.ZoomState.ZoomingOut || BetterArchery.__ZoomState == BetterArchery.ZoomState.ZoomingIn))
			{
				__instance.m_fov = BetterArchery.__NewZoomFov;
			}
		}
	}
	[HarmonyPatch(typeof(Hud), "UpdateCrosshair")]
	[HarmonyPriority(0)]
	public static class Player_UpdateCrosshair_Patch
	{
		private static void Postfix(Hud __instance, Player player, float bowDrawPercentage)
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Invalid comparison between Unknown and I4
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			if (((Behaviour)__instance.m_crosshair).enabled != BetterArchery.IsCrosshairVisible.Value)
			{
				((Behaviour)__instance.m_crosshair).enabled = BetterArchery.IsCrosshairVisible.Value;
			}
			if (((Behaviour)__instance.m_crosshairBow).enabled != BetterArchery.IsBowCrosshairVisible.Value)
			{
				((Behaviour)__instance.m_crosshairBow).enabled = BetterArchery.IsBowCrosshairVisible.Value;
			}
			PlayerBody.onBowDrawing = bowDrawPercentage > 0.1f;
			if (BetterArchery.BowDrawMovementSpeedReductionEnabled.Value)
			{
				if (bowDrawPercentage > 0.1f)
				{
					((Character)player).SetWalk(true);
					BetterArchery.speedReduction = true;
				}
				else if (((Character)player).GetWalk() && BetterArchery.speedReduction)
				{
					BetterArchery.speedReduction = false;
					((Character)player).SetWalk(false);
				}
			}
			if (!BetterArchery.configBowZoomEnabled.Value || BetterArchery.__BaseFov == 0f)
			{
				return;
			}
			ItemData currentWeapon = ((Humanoid)player).GetCurrentWeapon();
			if (currentWeapon == null || (int)currentWeapon.m_shared.m_itemType != 4)
			{
				ZoomOut();
				return;
			}
			float skillFactor = ((Character)player).GetSkillFactor(currentWeapon.m_shared.m_skillType);
			float num = 2f * (1f - skillFactor);
			KeyboardShortcut value = BetterArchery.BowZoomKey.Value;
			bool key = Input.GetKey(((KeyboardShortcut)(ref value)).MainKey);
			if (BetterArchery.__ZoomState == BetterArchery.ZoomState.ZoomingIn && !BetterArchery.zoomSFX)
			{
				BetterArchery.PlayCustomSFX("inhale", checkIfPlaying: false);
				BetterArchery.zoomSFX = true;
			}
			else if (BetterArchery.__ZoomState == BetterArchery.ZoomState.ZoomingOut && BetterArchery.zoomSFX)
			{
				BetterArchery.PlayCustomSFX("exhale", checkIfPlaying: false);
				BetterArchery.zoomSFX = false;
			}
			if (BetterArchery.AutomaticBowZoom.Value)
			{
				if (bowDrawPercentage > 0.01f)
				{
					BetterArchery.ZoomInTimer += Time.deltaTime;
					BetterArchery.__ZoomState = BetterArchery.ZoomState.ZoomingIn;
					float num2 = ((!(BetterArchery.BowZoomConstantTime.Value > 0f)) ? Mathf.InverseLerp(0.05f, num, BetterArchery.ZoomInTimer) : Mathf.InverseLerp(0.05f, BetterArchery.BowZoomConstantTime.Value, BetterArchery.ZoomInTimer));
					GameCamera.instance.m_fov = (BetterArchery.__LastZoomFov = Mathf.Lerp(BetterArchery.__BaseFov, BetterArchery.__BaseFov / BetterArchery.BowZoomFactor.Value, num2));
					BetterArchery.__NewZoomFov = (BetterArchery.__LastZoomFov = Mathf.Lerp(BetterArchery.__BaseFov, BetterArchery.__BaseFov / BetterArchery.BowZoomFactor.Value, num2));
					return;
				}
				ZoomOut();
			}
			if (key)
			{
				if (!(bowDrawPercentage > 0.01f))
				{
					BetterArchery.ZoomOutDelayTimer += Time.deltaTime;
					if (BetterArchery.ZoomOutDelayTimer > BetterArchery.StayInZoomTime.Value)
					{
						ZoomOut();
					}
				}
				else
				{
					BetterArchery.ZoomInTimer += Time.deltaTime;
					BetterArchery.ZoomOutDelayTimer = 0f;
					BetterArchery.__ZoomState = BetterArchery.ZoomState.ZoomingIn;
					float num3 = ((!(BetterArchery.BowZoomConstantTime.Value > 0f)) ? Mathf.InverseLerp(0.05f, num, BetterArchery.ZoomInTimer) : Mathf.InverseLerp(0.05f, BetterArchery.BowZoomConstantTime.Value, BetterArchery.ZoomInTimer));
					GameCamera.instance.m_fov = (BetterArchery.__LastZoomFov = Mathf.Lerp(BetterArchery.__BaseFov, BetterArchery.__BaseFov / BetterArchery.BowZoomFactor.Value, num3));
					BetterArchery.__NewZoomFov = (BetterArchery.__LastZoomFov = Mathf.Lerp(BetterArchery.__BaseFov, BetterArchery.__BaseFov / BetterArchery.BowZoomFactor.Value, num3));
				}
			}
			else
			{
				BetterArchery.ZoomOutDelayTimer = 1f;
				ZoomOut();
			}
		}

		public static void ZoomOut()
		{
			if (BetterArchery.__ZoomState != 0)
			{
				if (BetterArchery.__ZoomState == BetterArchery.ZoomState.ZoomingIn)
				{
					BetterArchery.__ZoomState = BetterArchery.ZoomState.ZoomingOut;
					BetterArchery.ZoomOutTimer = 0f;
					BetterArchery.ZoomInTimer = 0f;
				}
				else
				{
					BetterArchery.ZoomOutTimer += Time.deltaTime;
					if (BetterArchery.ZoomOutTimer > 1f)
					{
						GameCamera.instance.m_fov = BetterArchery.__BaseFov;
						BetterArchery.__ZoomState = BetterArchery.ZoomState.Fixed;
						BetterArchery.ZoomOutDelayTimer = 0f;
						return;
					}
				}
				float num = Mathf.InverseLerp(0f, 0.3f, BetterArchery.ZoomOutTimer);
				GameCamera.instance.m_fov = Mathf.Lerp(BetterArchery.__LastZoomFov, BetterArchery.__BaseFov, num);
				BetterArchery.__NewZoomFov = Mathf.Lerp(BetterArchery.__LastZoomFov, BetterArchery.__BaseFov, num);
			}
			else if (GameCamera.instance.m_fov != BetterArchery.__BaseFov)
			{
				GameCamera.instance.m_fov = BetterArchery.__BaseFov;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "CreateTombStone")]
	public static class Player_CreateTombStone_Patch
	{
		public static bool Prefix(Player __instance)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			if (((Humanoid)__instance).GetInventory().GetAllItems().Count == 0)
			{
				return true;
			}
			if (!BetterArchery.IsQuiverEquipped())
			{
				return true;
			}
			GameObject val = Object.Instantiate<GameObject>(__instance.m_tombstone, ((Character)__instance).GetCenterPoint() + Vector3.up + ((Component)__instance).transform.forward * -0.5f, ((Component)__instance).transform.rotation);
			TombStone component = val.GetComponent<TombStone>();
			PlayerProfile playerProfile = Game.instance.GetPlayerProfile();
			string name = playerProfile.GetName();
			long playerID = playerProfile.GetPlayerID();
			component.Setup(name + "'s Quiver", playerID);
			Container component2 = val.GetComponent<Container>();
			Inventory inventory = component2.GetInventory();
			Inventory inventory2 = ((Humanoid)__instance).GetInventory();
			List<ItemData> list = new List<ItemData>();
			foreach (ItemData item in inventory2.m_inventory)
			{
				if (!BetterArchery.IsQuiverSlot(item.m_gridPos))
				{
					list.Add(item);
					continue;
				}
				Vector2i val2 = inventory.FindEmptySlot(false);
				inventory.AddItem(item, item.m_stack, val2.x, val2.y);
			}
			inventory2.m_inventory = list;
			inventory2.Changed();
			inventory.Changed();
			return true;
		}
	}
	[HarmonyPatch(typeof(Projectile), "Setup")]
	public static class RetrieveArrows
	{
		public static bool Prefix(ref Projectile __instance, Character owner, Vector3 velocity, float hitNoise, HitData hitData, ItemData item)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Invalid comparison between Unknown and I4
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || item == null)
			{
				return true;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)owner != (Object)(object)Player.m_localPlayer)
			{
				return true;
			}
			if (!((Object)__instance).name.Contains("bow_projectile") || (int)item.m_shared.m_itemType != 4)
			{
				return true;
			}
			if (BetterArchery.configArrowImprovementsEnabled.Value)
			{
				__instance.m_gravity = BetterArchery.ArrowGravity.Value;
			}
			if (!BetterArchery.configRetrievableArrowsEnabled.Value)
			{
				return true;
			}
			string arrowType = ((Object)((Humanoid)localPlayer).GetAmmoItem().m_dropPrefab).name;
			if (string.IsNullOrEmpty(arrowType))
			{
				return true;
			}
			Arrow arrow = BetterArchery.ArrowRetrieves.Find((Arrow e) => e.SpawnArrow == arrowType);
			if (arrow == null)
			{
				return true;
			}
			float num = Random.Range(0f, 1f);
			BetterArchery.Log($"m_dropPrefab: {arrowType}, x.SpawnChance: {arrow.SpawnChance}, x.SpawnArrow: {arrow.SpawnArrow}");
			BetterArchery.Log($"spawnChance: {num}, currentArrow.SpawnChance: {arrow.SpawnChance}");
			if (BetterArchery.ArrowRetrieveOldVersion.Value)
			{
				if (num < arrow.SpawnChance)
				{
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(arrow.SpawnArrow);
					__instance.m_spawnOffset = new Vector3(0.5f, 0.05f, -0.5f);
					__instance.m_spawnOnHitChance = 1f;
					__instance.m_spawnOnHit = itemPrefab;
					__instance.m_hideOnHit = ((Component)__instance).gameObject;
				}
				else
				{
					__instance.m_spawnOnHitChance = 0f;
					__instance.m_ttl = BetterArchery.ArrowDisappearTime.Value;
				}
			}
			else if (num < arrow.SpawnChance)
			{
				GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab(arrow.SpawnArrow);
				Pickable val = ((Component)__instance).gameObject.AddComponent<Pickable>();
				val.m_hideWhenPicked = ((Component)__instance).gameObject;
				val.m_amount = 1;
				val.m_itemPrefab = itemPrefab2;
			}
			else if (BetterArchery.ArrowDisappearOnHit.Value)
			{
				__instance.m_hideOnHit = ((Component)__instance).gameObject;
			}
			else
			{
				__instance.m_stayTTL = BetterArchery.ArrowDisappearTime.Value;
				if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponentInChildren<MeshRenderer>()))
				{
					((Renderer)((Component)__instance).GetComponentInChildren<MeshRenderer>()).material.color = Color.black;
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Projectile), "OnHit")]
	public static class Projectile_OnHit_Patch
	{
		public static void Prefix(Projectile __instance, Collider collider, Vector3 hitPoint, bool water)
		{
			if (BetterArchery.ArrowRetrieveOldVersion.Value || !BetterArchery.configRetrievableArrowsEnabled.Value || !Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent<Pickable>()) || !((Object)__instance).name.Contains("bow_projectile"))
			{
				return;
			}
			GameObject val = (Object.op_Implicit((Object)(object)collider) ? Projectile.FindHitObject(collider) : null);
			bool flag = false;
			IDestructible val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<IDestructible>() : null);
			if (val2 != null)
			{
				flag = val2 is Character;
				if (!__instance.IsValidTarget(val2))
				{
					return;
				}
			}
			BoxCollider val3 = null;
			val3 = ((((Object)__instance).name == "bow_projectile_needle(Clone)") ? ((Component)((Component)((Component)__instance).transform.GetChild(0)).gameObject.transform.GetChild(0)).gameObject.AddComponent<BoxCollider>() : ((!(((Object)__instance).name == "bow_projectile_frost(Clone)")) ? ((Component)((Component)__instance).transform.GetChild(0)).gameObject.AddComponent<BoxCollider>() : ((Component)((Component)__instance).transform.GetChild(3)).gameObject.AddComponent<BoxCollider>()));
			if ((Object)(object)val3 != (Object)null)
			{
				((Collider)val3).enabled = true;
				__instance.m_stayTTL = BetterArchery.ArrowDisappearTime.Value;
			}
		}
	}
	[HarmonyPatch(typeof(Attack), "FireProjectileBurst")]
	public static class Attack_FireProjectileBurst_Patch
	{
		public static bool Prefix(ref Attack __instance)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Invalid comparison between Unknown and I4
			if (!((Character)__instance.m_character).IsPlayer() || !BetterArchery.configArrowImprovementsEnabled.Value)
			{
				return true;
			}
			ItemData ammoItem = ((Humanoid)Player.m_localPlayer).m_ammoItem;
			ItemData leftItem = ((Humanoid)Player.m_localPlayer).GetLeftItem();
			if (leftItem == null)
			{
				return true;
			}
			if ((int)leftItem.m_shared.m_itemType != 4)
			{
				return true;
			}
			if (ammoItem != null)
			{
				__instance.m_projectileVel = BetterArchery.ArrowVelocity.Value;
				if (BetterArchery.ArrowAccuracy.Value >= 0f)
				{
					__instance.m_projectileAccuracy = BetterArchery.ArrowAccuracy.Value;
				}
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Attack), "GetProjectileSpawnPoint")]
	public static class Attack_GetProjectileSpawnPoint_Patch
	{
		public static void Postfix(ref Attack __instance, ref Vector3 spawnPoint, ref Vector3 aimDir)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			if (!((Character)__instance.m_character).IsPlayer() || !BetterArchery.configArrowImprovementsEnabled.Value)
			{
				return;
			}
			ItemData leftItem = ((Humanoid)Player.m_localPlayer).GetLeftItem();
			if (leftItem == null || (int)leftItem.m_shared.m_itemType != 4)
			{
				return;
			}
			Transform leftHand = __instance.m_character.m_visEquipment.m_leftHand;
			Transform transform = ((Component)__instance.m_character).transform;
			spawnPoint = leftHand.position;
			aimDir = __instance.m_character.GetAimDir(spawnPoint);
			if (aimDir.y <= -0.8f)
			{
				leftHand = __instance.GetAttackOrigin();
				spawnPoint = leftHand.position + transform.up * __instance.m_attackHeight + transform.forward * 0.7f + transform.right * __instance.m_attackOffset;
				aimDir = __instance.m_character.GetAimDir(spawnPoint);
			}
			if (__instance.m_useCharacterFacing)
			{
				Vector3 forward = Vector3.forward;
				if (__instance.m_useCharacterFacingYAim)
				{
					forward.y = aimDir.y;
				}
				aimDir = transform.TransformDirection(forward);
			}
			ItemData ammoItem = ((Humanoid)Player.m_localPlayer).m_ammoItem;
			if (ammoItem != null && Object.op_Implicit((Object)(object)ammoItem.m_shared.m_attack.m_attackProjectile))
			{
				aimDir += BetterArchery.ArrowAimDir.Value;
			}
		}
	}
	[HarmonyPatch(typeof(Humanoid), "OnDamaged")]
	public static class Humanoid_OnDamaged_Patch
	{
		public static void Postfix(ref Humanoid __instance, HitData hit)
		{
			if (Object.op_Implicit((Object)(object)__instance) && hit.HaveAttacker() && hit.GetAttacker().IsPlayer() && BetterArchery.ShowSneakDamage.Value)
			{
				BetterArchery.Log($"(Humanoid) - __instance.m_name: {((Character)__instance).m_name}, __instance.InAttack(): {((Character)__instance).InAttack()}, __instance.m_baseAI.IsAlerted(): {((Character)__instance).m_baseAI.IsAlerted()}, __instance.m_baseAI.m_alerted: {((Character)__instance).m_baseAI.m_alerted}");
				BetterArchery.Log($"(Humanoid) - GetTotalPhysicalDamage: {hit.GetTotalPhysicalDamage()}, GetTotalDamage: {hit.GetTotalDamage()}");
				if (!((Character)__instance).InAttack() && !((Character)__instance).m_baseAI.IsAlerted())
				{
					hit.GetAttacker().Message((MessageType)1, string.Format("<size=25>Sneak attack for {0}X ({1}) damage!</size>", hit.m_backstabBonus, hit.GetTotalDamage().ToString("0.0")), 0, (Sprite)null);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Character), "OnDamaged")]
	public static class Character_OnDamaged_Patch
	{
		public static void Postfix(ref Character __instance, HitData hit)
		{
			if (Object.op_Implicit((Object)(object)__instance) && hit.HaveAttacker() && hit.GetAttacker().IsPlayer() && BetterArchery.ShowSneakDamage.Value)
			{
				BetterArchery.Log($"(Character) - __instance.m_name: {__instance.m_name}, __instance.InAttack(): {__instance.InAttack()}, __instance.m_baseAI.IsAlerted(): {__instance.m_baseAI.IsAlerted()}, __instance.m_baseAI.m_alerted: {__instance.m_baseAI.m_alerted}");
				BetterArchery.Log($"(Character) - GetTotalPhysicalDamage: {hit.GetTotalPhysicalDamage()}, GetTotalDamage: {hit.GetTotalDamage()}");
				if (!__instance.InAttack() && !__instance.m_baseAI.IsAlerted())
				{
					hit.GetAttacker().Message((MessageType)1, string.Format("<size=25>Sneak attack for {0}X ({1}) damage!</size>", hit.m_backstabBonus, hit.GetTotalDamage().ToString("0.0")), 0, (Sprite)null);
				}
			}
		}
	}
	internal class Tombstone
	{
		[HarmonyPatch(typeof(TombStone), "OnTakeAllSuccess")]
		[HarmonyPriority(0)]
		public static class TombStone_OnTakeAllSuccess_Patch
		{
			public static void Postfix()
			{
				//IL_0172: Unknown result type (might be due to invalid IL or missing references)
				//IL_017d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0187: Unknown result type (might be due to invalid IL or missing references)
				//IL_018c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0191: Unknown result type (might be due to invalid IL or missing references)
				//IL_0196: Unknown result type (might be due to invalid IL or missing references)
				//IL_019b: Unknown result type (might be due to invalid IL or missing references)
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer == (Object)null)
				{
					return;
				}
				Inventory inventory = ((Humanoid)localPlayer).m_inventory;
				BetterArchery.Log("Recovered Tombstone Items, verifying inventory...");
				List<ItemData> list = new List<ItemData>();
				for (int num = inventory.m_inventory.Count - 1; num >= 0; num--)
				{
					ItemData val = inventory.m_inventory[num];
					if (val.m_gridPos.x < 0 || val.m_gridPos.x >= inventory.m_width || val.m_gridPos.y < 0 || val.m_gridPos.y >= 5)
					{
						string text = Localization.instance.Localize(val.m_shared.m_name) + ((val.m_stack > 1) ? $" x{val.m_stack}" : "");
						BetterArchery.Log($"> Item Outside Inventory Grid! ({text}, <{val.m_gridPos.x},{val.m_gridPos.y}>)");
						inventory.RemoveItem(val);
						if (!inventory.AddItem(val))
						{
							BetterArchery.Log("> Could not add item to inventory, item dropped! (" + text + ")");
							list.Add(val);
							ItemDrop.DropItem(val, val.m_stack, ((Component)localPlayer).transform.position + ((Component)localPlayer).transform.forward * 2f + Vector3.up, Quaternion.identity);
						}
					}
				}
				if (list.Count > 0)
				{
					IEnumerable<string> values = list.Select((ItemData x) => Localization.instance.Localize(x.m_shared.m_name) + ((x.m_stack > 1) ? $" x{x.m_stack}" : ""));
					string text2 = "Not enough space in inventory, Items Dropped: " + string.Join(", ", values);
					((Character)localPlayer).Message((MessageType)2, text2, 0, (Sprite)null);
					BetterArchery.Log(text2);
				}
				else
				{
					BetterArchery.Log("> No issues!");
				}
			}
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	public static class ZNetScene_Awake_Patch
	{
		public static bool Prefix(ZNetScene __instance)
		{
			BetterArchery.TryRegisterPrefabs(__instance);
			return true;
		}

		public static void Postfix(ZNetScene __instance)
		{
			BetterArchery.TryCreateCustomSlot(__instance);
			BetterArchery.TryCreateCustomSFX();
		}
	}
	public static class PlayerExtensions
	{
		public static ZDO GetZDO(this Player player)
		{
			return ((Character)player).m_nview.GetZDO();
		}
	}
}
namespace PocketCloudAgent
{
	internal class PocketCloudVersion
	{
		public const string version = "2.7.15";
	}
}
namespace LitJson
{
	internal enum JsonType
	{
		None,
		Object,
		Array,
		String,
		Int,
		Long,
		Double,
		Boolean
	}
	internal interface IJsonWrapper : IList, IOrderedDictionary, IDictionary, ICollection, IEnumerable
	{
		bool IsArray { get; }

		bool IsBoolean { get; }

		bool IsDouble { get; }

		bool IsInt { get; }

		bool IsLong { get; }

		bool IsObject { get; }

		bool IsString { get; }

		bool GetBoolean();

		double GetDouble();

		int GetInt();

		JsonType GetJsonType();

		long GetLong();

		string GetString();

		void SetBoolean(bool val);

		void SetDouble(double val);

		void SetInt(int val);

		void SetJsonType(JsonType type);

		void SetLong(long val);

		void SetString(string val);

		string ToJson();

		void ToJson(JsonWriter writer);
	}
	internal class JsonData : IJsonWrapper, IList, IOrderedDictionary, IDictionary, ICollection, IEnumerable, IEquatable<JsonData>
	{
		private IList<JsonData> inst_array;

		private bool inst_boolean;

		private double inst_double;

		private int inst_int;

		private long inst_long;

		private IDictionary<string, JsonData> inst_object;

		private string inst_string;

		private string json;

		private JsonType type;

		private IList<KeyValuePair<string, JsonData>> object_list;

		public int Count => EnsureCollection().Count;

		public bool IsArray => type == JsonType.Array;

		public bool IsBoolean => type == JsonType.Boolean;

		public bool IsDouble => type == JsonType.Double;

		public bool IsInt => type == JsonType.Int;

		public bool IsLong => type == JsonType.Long;

		public bool IsObject => type == JsonType.Object;

		public bool IsString => type == JsonType.String;

		int ICollection.Count => Count;

		bool ICollection.IsSynchronized => EnsureCollection().IsSynchronized;

		object ICollection.SyncRoot => EnsureCollection().SyncRoot;

		bool IDictionary.IsFixedSize => EnsureDictionary().IsFixedSize;

		bool IDictionary.IsReadOnly => EnsureDictionary().IsReadOnly;

		ICollection IDictionary.Keys
		{
			get
			{
				EnsureDictionary();
				IList<string> list = new List<string>();
				foreach (KeyValuePair<string, JsonData> item in object_list)
				{
					list.Add(item.Key);
				}
				return (ICollection)list;
			}
		}

		ICollection IDictionary.Values
		{
			get
			{
				EnsureDictionary();
				IList<JsonData> list = new List<JsonData>();
				foreach (KeyValuePair<string, JsonData> item in object_list)
				{
					list.Add(item.Value);
				}
				return (ICollection)list;
			}
		}

		bool IJsonWrapper.IsArray => IsArray;

		bool IJsonWrapper.IsBoolean => IsBoolean;

		bool IJsonWrapper.IsDouble => IsDouble;

		bool IJsonWrapper.IsInt => IsInt;

		bool IJsonWrapper.IsLong => IsLong;

		bool IJsonWrapper.IsObject => IsObject;

		bool IJsonWrapper.IsString => IsString;

		bool IList.IsFixedSize => EnsureList().IsFixedSize;

		bool IList.IsReadOnly => EnsureList().IsReadOnly;

		object IDictionary.this[object key]
		{
			get
			{
				return EnsureDictionary()[key];
			}
			set
			{
				if (!(key is string))
				{
					throw new ArgumentException("The key has to be a string");
				}
				JsonData value2 = ToJsonData(value);
				this[(string)key] = value2;
			

BepInEx/plugins/JereKuusela-Infinity_Hammer/InfinityHammer.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using InfinityHammer;
using Microsoft.CodeAnalysis;
using Service;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("InfinityHammer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("InfinityHammer")]
[assembly: AssemblyTitle("InfinityHammer")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<afb628c3-ba45-4498-9e46-031bcd7d8e91>Embedded]
	internal sealed class <afb628c3-ba45-4498-9e46-031bcd7d8e91>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<afb628c3-ba45-4498-9e46-031bcd7d8e91>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <bdedce9d-15b6-4151-a2f6-197cd4e997fd>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <bdedce9d-15b6-4151-a2f6-197cd4e997fd>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <bdedce9d-15b6-4151-a2f6-197cd4e997fd>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<afb628c3-ba45-4498-9e46-031bcd7d8e91>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <af58accb-5660-4d5b-a709-7d898b0c5541>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <af58accb-5660-4d5b-a709-7d898b0c5541>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[<afb628c3-ba45-4498-9e46-031bcd7d8e91>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 Service
{
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	public class ConfigWrapper
	{
		private readonly ConfigFile ConfigFile;

		private readonly Dictionary<string, Action<Terminal, string>> SettingHandlers = new Dictionary<string, Action<Terminal, string>>();

		private readonly List<Action> BindCalls = new List<Action>();

		private static readonly HashSet<string> Truthies = new HashSet<string> { "1", "true", "yes", "on" };

		private static readonly HashSet<string> Falsies = new HashSet<string> { "0", "false", "no", "off" };

		public ConfigWrapper(string command, ConfigFile configFile)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_004c: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			ConfigFile = configFile;
			new ConsoleCommand(command, "[key] [value] - Toggles or sets a config value.", (ConsoleEvent)delegate(ConsoleEventArgs args)
			{
				if (args.Length >= 2 && SettingHandlers.TryGetValue(args[1].ToLower(), out var value))
				{
					if (args.Length == 2)
					{
						value(args.Context, "");
					}
					else
					{
						value(args.Context, string.Join(" ", args.Args, 2, args.Length - 2));
					}
				}
			}, false, false, false, false, false, (ConsoleOptionsFetcher)([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] () => SettingHandlers.Keys.ToList()), false);
		}

		private ConfigEntry<T> Create<[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)] T>(string group, string name, T value, ConfigDescription description)
		{
			return ConfigFile.Bind<T>(group, name, value, description);
		}

		private ConfigEntry<T> Create<[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)] T>(string group, string name, T value, string description)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return Create(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}

		public ConfigEntry<T> Bind<[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)] T>(string group, string name, T value, ConfigDescription description)
		{
			ConfigEntry<T> val = Create(group, name, value, description);
			if (val is ConfigEntry<bool> setting)
			{
				Register(setting);
			}
			else if (val is ConfigEntry<KeyboardShortcut> setting2)
			{
				Register(setting2);
			}
			else
			{
				Register<T>(val);
			}
			return val;
		}

		public ConfigEntry<string> BindList(string group, string name, string value, string description)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return Bind(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}

		public ConfigEntry<string> BindList(string group, string name, string value, ConfigDescription description)
		{
			ConfigEntry<string> val = Create(group, name, value, description);
			RegisterList(val);
			return val;
		}

		public ConfigEntry<KeyboardShortcut> BindCommand(Func<string> command, string group, string name, KeyboardShortcut value, string description, string mode = "")
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry<KeyboardShortcut> val = Create<KeyboardShortcut>(group, name, value, description);
			RegisterCommand(val, command, mode);
			return val;
		}

		public ConfigEntry<KeyboardShortcut> BindCommand(string command, string group, string name, KeyboardShortcut value, string description, string mode = "")
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry<KeyboardShortcut> val = Create<KeyboardShortcut>(group, name, value, description);
			RegisterCommand(val, () => command, mode);
			return val;
		}

		public ConfigEntry<KeyboardShortcut> BindWheelCommand(string command, string group, string name, KeyboardShortcut value, string description, string mode = "")
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry<KeyboardShortcut> val = Create<KeyboardShortcut>(group, name, value, description);
			RegisterWheelCommand(val, command, mode);
			return val;
		}

		public ConfigEntry<T> Bind<[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)] T>(string group, string name, T value, string description)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return Bind(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}

		private static void AddMessage(Terminal context, string message)
		{
			context.AddString(message);
			Player localPlayer = Player.m_localPlayer;
			if (localPlayer != null)
			{
				((Character)localPlayer).Message((MessageType)1, message, 0, (Sprite)null);
			}
		}

		private void Register(ConfigEntry<bool> setting)
		{
			string name = ((ConfigEntryBase)setting).Definition.Key;
			string key = ToKey(name);
			SettingHandlers.Add(key, delegate(Terminal terminal, string value)
			{
				Toggle(terminal, setting, name, value);
			});
		}

		public static string GetKeys(KeyboardShortcut key)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if ((int)((KeyboardShortcut)(ref key)).MainKey == 0)
			{
				return "unbound";
			}
			KeyCode mainKey = ((KeyboardShortcut)(ref key)).MainKey;
			string text = ((object)(KeyCode)(ref mainKey)).ToString().ToLower();
			if (((KeyboardShortcut)(ref key)).Modifiers.Count() > 0)
			{
				text = text + "," + string.Join(",", ((KeyboardShortcut)(ref key)).Modifiers);
			}
			return text;
		}

		private static void UpdateKey(string name, KeyboardShortcut key, Func<string> command, string mode = "")
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			((Terminal)Console.instance).TryRunCommand("unbind " + name + " silent", false, false);
			if ((int)((KeyboardShortcut)(ref key)).MainKey != 0)
			{
				string text = GetKeys(key);
				if (mode != "")
				{
					text = text + "," + mode;
				}
				string text2 = "bind " + text + " tag=" + name + " " + command();
				((Terminal)Console.instance).TryRunCommand(text2, false, false);
			}
		}

		public void SetupBinds()
		{
			foreach (Action bindCall in BindCalls)
			{
				bindCall();
			}
		}

		private string ToKey(string name)
		{
			return name.ToLower().Replace(' ', '_').Replace("(", "")
				.Replace(")", "");
		}

		private void RegisterCommand(ConfigEntry<KeyboardShortcut> setting, Func<string> command, string mode = "")
		{
			string name = ((ConfigEntryBase)setting).Definition.Key;
			string key = ToKey(name);
			setting.SettingChanged += [<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (object s, EventArgs e) =>
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				UpdateKey(key, setting.Value, command, mode);
			};
			BindCalls.Add(delegate
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				UpdateKey(key, setting.Value, command, mode);
			});
			SettingHandlers.Add(key, delegate(Terminal terminal, string value)
			{
				SetKey(terminal, setting, name, value);
			});
		}

		private static void UpdateWheelKey(string name, KeyboardShortcut key, string command, string mode = "")
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			((Terminal)Console.instance).TryRunCommand("unbind " + name + " silent", false, false);
			if ((int)((KeyboardShortcut)(ref key)).MainKey != 0)
			{
				KeyCode mainKey = ((KeyboardShortcut)(ref key)).MainKey;
				string text = ((object)(KeyCode)(ref mainKey)).ToString().ToLower();
				if (((KeyboardShortcut)(ref key)).Modifiers.Count() > 0)
				{
					text = text + "," + string.Join(",", ((KeyboardShortcut)(ref key)).Modifiers);
				}
				if (mode != "")
				{
					text = text + "," + mode;
				}
				string text2 = "bind wheel," + text + " tag=" + name + " " + command;
				((Terminal)Console.instance).TryRunCommand(text2, false, false);
			}
		}

		private void RegisterWheelCommand(ConfigEntry<KeyboardShortcut> setting, string command, string mode = "")
		{
			string name = ((ConfigEntryBase)setting).Definition.Key;
			string key = ToKey(name);
			setting.SettingChanged += [<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (object s, EventArgs e) =>
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				UpdateWheelKey(key, setting.Value, command, mode);
			};
			BindCalls.Add(delegate
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				UpdateWheelKey(key, setting.Value, command, mode);
			});
			SettingHandlers.Add(key, delegate(Terminal terminal, string value)
			{
				SetKey(terminal, setting, name, value);
			});
		}

		private void Register(ConfigEntry<KeyboardShortcut> setting)
		{
			string name = ((ConfigEntryBase)setting).Definition.Key;
			string key = ToKey(name);
			SettingHandlers.Add(key, delegate(Terminal terminal, string value)
			{
				SetKey(terminal, setting, name, value);
			});
		}

		private void RegisterList(ConfigEntry<string> setting)
		{
			string name = ((ConfigEntryBase)setting).Definition.Key;
			string key = ToKey(name);
			SettingHandlers.Add(key, delegate(Terminal terminal, string value)
			{
				ToggleFlag(terminal, setting, name, value);
			});
		}

		private void Register<[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)] T>(ConfigEntry<T> setting)
		{
			string name = ((ConfigEntryBase)setting).Definition.Key;
			string key = ToKey(name);
			SettingHandlers.Add(key, delegate(Terminal terminal, string value)
			{
				SetValue<T>(terminal, setting, name, value);
			});
		}

		private static string State(bool value)
		{
			if (!value)
			{
				return "disabled";
			}
			return "enabled";
		}

		private static string Flag(bool value)
		{
			if (!value)
			{
				return "Added";
			}
			return "Removed";
		}

		private static bool IsTruthy(string value)
		{
			return Truthies.Contains(value);
		}

		private static bool IsFalsy(string value)
		{
			return Falsies.Contains(value);
		}

		private static void Toggle(Terminal context, ConfigEntry<bool> setting, string name, string value)
		{
			if (value == "")
			{
				setting.Value = !setting.Value;
			}
			else if (IsTruthy(value))
			{
				setting.Value = true;
			}
			else if (IsFalsy(value))
			{
				setting.Value = false;
			}
			AddMessage(context, name + " " + State(setting.Value) + ".");
		}

		private static void SetKey(Terminal context, ConfigEntry<KeyboardShortcut> setting, string name, string value)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			if (value == "")
			{
				AddMessage(context, $"{name}: {setting.Value}.");
				return;
			}
			if (!Enum.TryParse<KeyCode>(value, ignoreCase: true, out KeyCode result))
			{
				throw new InvalidOperationException("'" + value + "' is not a valid UnityEngine.KeyCode.");
			}
			setting.Value = new KeyboardShortcut(result, Array.Empty<KeyCode>());
			AddMessage(context, name + " set to " + value + ".");
		}

		public static int TryParseInt(string value, int defaultValue)
		{
			if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			return defaultValue;
		}

		public static int TryParseInt(ConfigEntry<string> setting)
		{
			if (int.TryParse(setting.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			return TryParseInt((string)((ConfigEntryBase)setting).DefaultValue, 0);
		}

		private static float TryParseFloat(string value, float defaultValue)
		{
			if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			return defaultValue;
		}

		public static float TryParseFloat(ConfigEntry<string> setting)
		{
			if (float.TryParse(setting.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			return TryParseFloat((string)((ConfigEntryBase)setting).DefaultValue, 0f);
		}

		private static HashSet<string> ParseList(string value)
		{
			return (from s in value.Split(new char[1] { ',' })
				select s.Trim().ToLower()).ToHashSet();
		}

		private static void ToggleFlag(Terminal context, ConfigEntry<string> setting, string name, string value)
		{
			if (value == "")
			{
				AddMessage(context, name + ": " + setting.Value + "\".");
				return;
			}
			HashSet<string> hashSet = ParseList(setting.Value);
			foreach (string item in ParseList(value))
			{
				bool flag = hashSet.Contains(item);
				if (flag)
				{
					hashSet.Remove(item);
				}
				else
				{
					hashSet.Add(item);
				}
				setting.Value = string.Join(",", hashSet);
				AddMessage(context, name + ": " + Flag(flag) + " \"" + item + "\".");
			}
		}

		private static void SetValue<[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)] T>(Terminal context, ConfigEntry<T> setting, string name, string value)
		{
			if (value == "")
			{
				AddMessage(context, $"{name}: {setting.Value}.");
				return;
			}
			setting.Value = (T)(object)value;
			AddMessage(context, name + " set to " + value + ".");
		}
	}
	public static class Hash
	{
		public static int OverrideItems = StringExtensionMethods.GetStableHashCode("override_items");

		public static int AddedDefaultItems = StringExtensionMethods.GetStableHashCode("addedDefaultItems");

		public static int Items = StringExtensionMethods.GetStableHashCode("items");

		public static int PlantTime = StringExtensionMethods.GetStableHashCode("plantTime");

		public static int Wear = StringExtensionMethods.GetStableHashCode("override_wear");

		public static int Fall = StringExtensionMethods.GetStableHashCode("override_fall");

		public static int Growth = StringExtensionMethods.GetStableHashCode("override_growth");

		public static int Interact = StringExtensionMethods.GetStableHashCode("override_interact");

		public static int Restrict = StringExtensionMethods.GetStableHashCode("override_restrict");

		public static int Render = StringExtensionMethods.GetStableHashCode("override_render");

		public static int Collision = StringExtensionMethods.GetStableHashCode("override_collision");

		public static int Health = StringExtensionMethods.GetStableHashCode("health");

		public static int MaxHealth = StringExtensionMethods.GetStableHashCode("max_health");

		public static int Level = StringExtensionMethods.GetStableHashCode("level");

		public static int Creator = StringExtensionMethods.GetStableHashCode("creator");

		public static int Text = StringExtensionMethods.GetStableHashCode("text");

		public static int Pose = StringExtensionMethods.GetStableHashCode("pose");

		public static int Item = StringExtensionMethods.GetStableHashCode("item");

		public static int Variant = StringExtensionMethods.GetStableHashCode("variant");

		public static int Quality = StringExtensionMethods.GetStableHashCode("quality");

		public static int TamedName = StringExtensionMethods.GetStableHashCode("TamedName");

		public static int Tamed = StringExtensionMethods.GetStableHashCode("Tamed");

		public static int Tag = StringExtensionMethods.GetStableHashCode("tag");

		public static int Seed = StringExtensionMethods.GetStableHashCode("seed");

		public static int Location = StringExtensionMethods.GetStableHashCode("location");

		public static int SpawnPoint = StringExtensionMethods.GetStableHashCode("spawnpoint");

		public static int Scale = StringExtensionMethods.GetStableHashCode("scale");

		public static int Portal = StringExtensionMethods.GetStableHashCode("portal_wood");
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	public class Range<[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)] T>
	{
		public T Min;

		public T Max;

		public Range(T value)
		{
			Min = value;
			Max = value;
		}

		public Range(T min, T max)
		{
			Min = min;
			Max = max;
		}

		public override string ToString()
		{
			if (Min != null && Min.Equals(Max))
			{
				return Min.ToString();
			}
			if (Min == null || Max == null)
			{
				return "";
			}
			return $"{Min}-{Max}";
		}
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	public static class Parse
	{
		private static readonly HashSet<string> Truthies = new HashSet<string> { "1", "true", "yes", "on" };

		private static readonly HashSet<string> Falsies = new HashSet<string> { "0", "false", "no", "off" };

		private static Range<string> TryRange(string arg)
		{
			List<string> list = arg.Split(new char[1] { '-' }).ToList();
			if (list.Count > 1 && list[0] == "")
			{
				list[0] = "-" + list[1];
				list.RemoveAt(1);
			}
			if (list.Count > 2 && list[1] == "")
			{
				list[1] = "-" + list[2];
				list.RemoveAt(2);
			}
			if (list.Count == 1)
			{
				return new Range<string>(list[0]);
			}
			return new Range<string>(list[0], list[1]);
		}

		public static int TryInt(string arg, int defaultValue = 0)
		{
			if (!int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				return defaultValue;
			}
			return result;
		}

		public static int TryInt(string[] args, int index, int defaultValue = 0)
		{
			if (args.Length <= index)
			{
				return defaultValue;
			}
			return TryInt(args[index], defaultValue);
		}

		public static Range<int> TryIntRange(string arg, int defaultValue = 0)
		{
			Range<string> range = TryRange(arg);
			return new Range<int>(TryInt(range.Min, defaultValue), TryInt(range.Max, defaultValue));
		}

		public static Range<int> TryIntRange(string[] args, int index, int defaultValue = 0)
		{
			if (args.Length <= index)
			{
				return new Range<int>(defaultValue);
			}
			return TryIntRange(args[index], defaultValue);
		}

		public static uint TryUInt(string arg, uint defaultValue = 0u)
		{
			if (!uint.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				return defaultValue;
			}
			return result;
		}

		public static uint TryUInt(string[] args, int index, uint defaultValue = 0u)
		{
			if (args.Length <= index)
			{
				return defaultValue;
			}
			return TryUInt(args[index], defaultValue);
		}

		public static Range<uint> TryUIntRange(string arg, uint defaultValue = 0u)
		{
			Range<string> range = TryRange(arg);
			return new Range<uint>(TryUInt(range.Min, defaultValue), TryUInt(range.Max, defaultValue));
		}

		public static Range<uint> TryUIntRange(string[] args, int index, uint defaultValue = 0u)
		{
			if (args.Length <= index)
			{
				return new Range<uint>(defaultValue);
			}
			return TryUIntRange(args[index], defaultValue);
		}

		public static long TryLong(string arg, long defaultValue = 1L)
		{
			if (!long.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				return defaultValue;
			}
			return result;
		}

		public static long TryLong(string[] args, int index, long defaultValue = 1L)
		{
			if (args.Length <= index)
			{
				return defaultValue;
			}
			return TryLong(args[index], defaultValue);
		}

		public static Range<long> TryLongRange(string arg, long defaultValue = 1L)
		{
			Range<string> range = TryRange(arg);
			return new Range<long>(TryLong(range.Min, defaultValue), TryLong(range.Max, defaultValue));
		}

		public static Range<long> TryLongRange(string[] args, int index, long defaultValue = 1L)
		{
			if (args.Length <= index)
			{
				return new Range<long>(defaultValue);
			}
			return TryLongRange(args[index], defaultValue);
		}

		public static float TryFloat(string arg, float defaultValue = 1f)
		{
			if (!float.TryParse(arg, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return defaultValue;
			}
			return result;
		}

		public static float? TryFloatNull(string arg)
		{
			if (!float.TryParse(arg, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return null;
			}
			return result;
		}

		public static float TryFloat(string[] args, int index, float defaultValue = 1f)
		{
			if (args.Length <= index)
			{
				return defaultValue;
			}
			return TryFloat(args[index], defaultValue);
		}

		public static Range<float> TryFloatRange(string arg, float defaultValue = 1f)
		{
			Range<string> range = TryRange(arg);
			return new Range<float>(TryFloat(range.Min, defaultValue), TryFloat(range.Max, defaultValue));
		}

		public static Range<float?> TryFloatNullRange(string arg)
		{
			Range<string> range = TryRange(arg);
			return new Range<float?>(TryFloatNull(range.Min), TryFloatNull(range.Max));
		}

		public static Range<float> TryFloatRange(string[] args, int index, float defaultValue = 1f)
		{
			if (args.Length <= index)
			{
				return new Range<float>(defaultValue);
			}
			return TryFloatRange(args[index], defaultValue);
		}

		public static string String(string arg)
		{
			return arg;
		}

		public static string TryString(string[] args, int index, string defaultValue = "")
		{
			if (args.Length <= index)
			{
				return defaultValue;
			}
			return args[index];
		}

		private static bool IsTruthy(string value)
		{
			return Truthies.Contains(value);
		}

		private static bool IsFalsy(string value)
		{
			return Falsies.Contains(value);
		}

		public static bool? Boolean(string arg)
		{
			if (IsTruthy(arg))
			{
				return true;
			}
			if (IsFalsy(arg))
			{
				return false;
			}
			return null;
		}

		public static Quaternion TryAngleYXZ(string arg)
		{
			//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)
			return TryAngleYXZ(arg, Quaternion.identity);
		}

		public static Quaternion TryAngleYXZ(string arg, Quaternion defaultValue)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			string[] args = Split(arg);
			Vector3 zero = Vector3.zero;
			zero.y = TryFloat(args, 0, ((Quaternion)(ref defaultValue)).eulerAngles.y);
			zero.x = TryFloat(args, 1, ((Quaternion)(ref defaultValue)).eulerAngles.x);
			zero.z = TryFloat(args, 2, ((Quaternion)(ref defaultValue)).eulerAngles.z);
			return Quaternion.Euler(zero);
		}

		public static Range<Quaternion> TryAngleYXZRange(string arg)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return TryAngleYXZRange(arg, Quaternion.identity);
		}

		public static Range<Quaternion> TryAngleYXZRange(string arg, Quaternion defaultValue)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			string[] args = Split(arg);
			Range<float> y = TryFloatRange(args, 0, defaultValue.y);
			Range<float> x = TryFloatRange(args, 1, defaultValue.x);
			Range<float> z = TryFloatRange(args, 2, defaultValue.z);
			return ToAngleRange(x, y, z);
		}

		private static Range<Quaternion> ToAngleRange(Range<float> x, Range<float> y, Range<float> z)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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)
			Quaternion min = Quaternion.Euler(new Vector3(x.Min, y.Min, z.Min));
			Quaternion max = Quaternion.Euler(new Vector3(x.Max, y.Max, z.Max));
			return new Range<Quaternion>(min, max);
		}

		public static Vector3 TryVectorXZY(string[] args)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return TryVectorXZY(args, 0, Vector3.zero);
		}

		public static Vector3 TryVectorXZY(string[] args, Vector3 defaultValue)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return TryVectorXZY(args, 0, defaultValue);
		}

		public static Vector3 TryVectorXZY(string[] args, int index)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return TryVectorXZY(args, index, Vector3.zero);
		}

		public static Vector3 TryVectorXZY(string[] args, int index, Vector3 defaultValue)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			Vector3 zero = Vector3.zero;
			zero.x = TryFloat(args, index, defaultValue.x);
			zero.y = TryFloat(args, index + 2, defaultValue.y);
			zero.z = TryFloat(args, index + 1, defaultValue.z);
			return zero;
		}

		public static Range<Vector3> TryVectorXZYRange(string arg, Vector3 defaultValue)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			string[] args = Split(arg);
			Range<float> x = TryFloatRange(args, 0, defaultValue.x);
			Range<float> y = TryFloatRange(args, 2, defaultValue.y);
			Range<float> z = TryFloatRange(args, 1, defaultValue.z);
			return ToVectorRange(x, y, z);
		}

		public static Vector3 TryVectorZXY(string[] args)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return TryVectorZXY(args, 0, Vector3.zero);
		}

		public static Vector3 TryVectorZXY(string[] args, Vector3 defaultValue)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return TryVectorZXY(args, 0, defaultValue);
		}

		public static Vector3 TryVectorZXY(string[] args, int index)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return TryVectorZXY(args, index, Vector3.zero);
		}

		public static Vector3 TryVectorZXY(string[] args, int index, Vector3 defaultValue)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			Vector3 zero = Vector3.zero;
			zero.x = TryFloat(args, index + 1, defaultValue.x);
			zero.y = TryFloat(args, index + 2, defaultValue.y);
			zero.z = TryFloat(args, index, defaultValue.z);
			return zero;
		}

		public static Range<Vector3> TryVectorZXYRange(string arg, Vector3 defaultValue)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			string[] args = Split(arg);
			Range<float> x = TryFloatRange(args, 1, defaultValue.x);
			Range<float> y = TryFloatRange(args, 2, defaultValue.y);
			Range<float> z = TryFloatRange(args, 0, defaultValue.z);
			return ToVectorRange(x, y, z);
		}

		private static Range<Vector3> ToVectorRange(Range<float> x, Range<float> y, Range<float> z)
		{
			//IL_0012: 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)
			Vector3 min = new Vector3(x.Min, y.Min, z.Min);
			Vector3 max = default(Vector3);
			((Vector3)(ref max))..ctor(x.Max, y.Max, z.Max);
			return new Range<Vector3>(min, max);
		}

		public static Vector3 TryVectorYXZ(string[] args)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return TryVectorYXZ(args, 0, Vector3.zero);
		}

		public static Vector3 TryVectorYXZ(string[] args, Vector3 defaultValue)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return TryVectorYXZ(args, 0, defaultValue);
		}

		public static Vector3 TryVectorYXZ(string[] args, int index)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return TryVectorYXZ(args, index, Vector3.zero);
		}

		public static Vector3 TryVectorYXZ(string[] args, int index, Vector3 defaultValue)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			Vector3 zero = Vector3.zero;
			zero.y = TryFloat(args, index, defaultValue.y);
			zero.x = TryFloat(args, index + 1, defaultValue.x);
			zero.z = TryFloat(args, index + 2, defaultValue.z);
			return zero;
		}

		public static Range<Vector3> TryVectorYXZRange(string arg, Vector3 defaultValue)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			string[] args = Split(arg);
			Range<float> x = TryFloatRange(args, 1, defaultValue.x);
			Range<float> y = TryFloatRange(args, 0, defaultValue.y);
			Range<float> z = TryFloatRange(args, 2, defaultValue.z);
			return ToVectorRange(x, y, z);
		}

		public static Vector3 TryScale(string[] args)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return TryScale(args, 0);
		}

		public static Vector3 TryScale(string[] args, int index)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return SanityCheck(TryVectorXZY(args, index));
		}

		private static Vector3 SanityCheck(Vector3 scale)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			if (scale.x == 0f)
			{
				scale.x = 1f;
			}
			if (scale.y == 0f)
			{
				scale.y = scale.x;
			}
			if (scale.z == 0f)
			{
				scale.z = scale.x;
			}
			return scale;
		}

		public static Range<Vector3> TryScaleRange(string arg)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			string[] args = Split(arg);
			Range<float> x = TryFloatRange(args, 0, 0f);
			Range<float> y = TryFloatRange(args, 1, 0f);
			Range<float> z = TryFloatRange(args, 2, 0f);
			Range<Vector3> range = ToVectorRange(x, y, z);
			range.Min = SanityCheck(range.Min);
			range.Max = SanityCheck(range.Max);
			return range;
		}

		public static string[] Split(string arg, char separator = ',')
		{
			return (from s in arg.Split(new char[1] { separator })
				select s.Trim()).ToArray();
		}

		public static string[] TrySplit(string[] args, int index, char separator)
		{
			if (args.Length <= index)
			{
				return new string[0];
			}
			return Split(args[index], separator);
		}

		public static float Direction(string value)
		{
			if (TryFloat(value) > 0f)
			{
				return 1f;
			}
			return -1f;
		}

		public static float Direction(string[] args, int index)
		{
			if (args.Length <= index)
			{
				return 1f;
			}
			if (TryFloat(args[index]) > 0f)
			{
				return 1f;
			}
			return -1f;
		}

		public static Vector3Int ParseXYZInt(string value)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			Vector3Int zero = Vector3Int.zero;
			string[] array = value.Split(new char[1] { ',' });
			if (array.Length != 0)
			{
				((Vector3Int)(ref zero)).x = TryInt(array[0]);
			}
			if (array.Length > 1)
			{
				((Vector3Int)(ref zero)).y = TryInt(array[1]);
			}
			if (array.Length > 2)
			{
				((Vector3Int)(ref zero)).z = TryInt(array[2]);
			}
			return zero;
		}

		public static float Multiplier(string value)
		{
			float num = 1f;
			string[] array = value.Split(new char[1] { '*' });
			foreach (string arg in array)
			{
				num *= TryFloat(arg);
			}
			return num;
		}

		public static float TryMultiplier(string[] args, int index, float defaultValue = 1f)
		{
			if (args.Length <= index)
			{
				return defaultValue;
			}
			return Multiplier(args[index]);
		}
	}
	public enum ObjectType
	{
		All,
		Character,
		Structure
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	public class Hovered
	{
		public ZNetView Obj;

		public int Index;

		public Hovered(ZNetView obj, int index)
		{
			Obj = obj;
			Index = index;
		}
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	public static class Selector
	{
		public static bool IsValid(ZNetView view)
		{
			if (Object.op_Implicit((Object)(object)view))
			{
				return IsValid(view.GetZDO());
			}
			return false;
		}

		public static bool IsValid(ZDO zdo)
		{
			if (zdo != null)
			{
				return zdo.IsValid();
			}
			return false;
		}

		[return: <bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)]
		public static ZNetView GetHovered(float range, List<string> ignoredIds)
		{
			return GetHovered(Player.m_localPlayer, range, ignoredIds)?.Obj;
		}

		[return: <bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)]
		public static Hovered GetHovered(Player obj, float maxDistance, List<string> ignoredIds, bool allowOtherPlayers = false)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			HashSet<int> ignoredPrefabs = GetIgnoredPrefabs(ignoredIds);
			float num = Math.Max(maxDistance + 5f, 50f);
			int mask = LayerMask.GetMask(new string[11]
			{
				"item", "piece", "piece_nonsolid", "Default", "static_solid", "Default_small", "character", "character_net", "terrain", "vehicle",
				"character_trigger"
			});
			RaycastHit[] array = Physics.RaycastAll(((Component)GameCamera.instance).transform.position, ((Component)GameCamera.instance).transform.forward, num, mask);
			Array.Sort(array, (RaycastHit x, RaycastHit y) => ((RaycastHit)(ref x)).distance.CompareTo(((RaycastHit)(ref y)).distance));
			RaycastHit[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				RaycastHit val = array2[i];
				if (Vector3.Distance(((RaycastHit)(ref val)).point, ((Character)obj).m_eye.position) >= maxDistance)
				{
					continue;
				}
				ZNetView componentInParent = ((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<ZNetView>();
				if (!IsValid(componentInParent) || ignoredPrefabs.Contains(componentInParent.GetZDO().GetPrefab()) || Object.op_Implicit((Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponent<EffectArea>()))
				{
					continue;
				}
				Player componentInChildren = ((Component)componentInParent).GetComponentInChildren<Player>();
				if (!((Object)(object)componentInChildren == (Object)(object)obj) && (allowOtherPlayers || !Object.op_Implicit((Object)(object)componentInChildren)))
				{
					MineRock5 component = ((Component)componentInParent).GetComponent<MineRock5>();
					int index = 0;
					if (Object.op_Implicit((Object)(object)component))
					{
						index = component.GetAreaIndex(((RaycastHit)(ref val)).collider);
					}
					return new Hovered(componentInParent, index);
				}
			}
			return null;
		}

		private static float GetX(float x, float y, float angle)
		{
			return Mathf.Cos(angle) * x - Mathf.Sin(angle) * y;
		}

		private static float GetY(float x, float y, float angle)
		{
			return Mathf.Sin(angle) * x + Mathf.Cos(angle) * y;
		}

		public static bool Within(Vector3 position, Vector3 center, float angle, float width, float depth, float height)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			float x = position.x - center.x;
			float y = position.z - center.z;
			float x2 = GetX(x, y, angle);
			float y2 = GetY(x, y, angle);
			if (center.y - position.y > 1000f)
			{
				return false;
			}
			if (position.y - center.y > ((height == 0f) ? 1000f : height))
			{
				return false;
			}
			if (Mathf.Abs(x2) > width)
			{
				return false;
			}
			if (Mathf.Abs(y2) > depth)
			{
				return false;
			}
			return true;
		}

		public static bool Within(Vector3 position, Vector3 center, float radius, float height)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (Utils.DistanceXZ(position, center) <= radius && center.y - position.y < 1000f)
			{
				return position.y - center.y <= ((height == 0f) ? 1000f : height);
			}
			return false;
		}

		private static bool IsIncluded(string id, string name)
		{
			if (id.StartsWith("*", StringComparison.Ordinal) && id.EndsWith("*", StringComparison.Ordinal))
			{
				return name.Contains(id.Substring(1, id.Length - 3));
			}
			if (id.StartsWith("*", StringComparison.Ordinal))
			{
				return name.EndsWith(id.Substring(1), StringComparison.Ordinal);
			}
			if (id.EndsWith("*", StringComparison.Ordinal))
			{
				return name.StartsWith(id.Substring(0, id.Length - 2), StringComparison.Ordinal);
			}
			return id == name;
		}

		private static HashSet<int> GetIgnoredPrefabs(List<string> ids)
		{
			HashSet<int> hashSet = new HashSet<int>();
			foreach (string id in ids)
			{
				hashSet.UnionWith(GetIgnoredPrefabs(id));
			}
			return hashSet;
		}

		private static HashSet<int> GetIgnoredPrefabs(string id)
		{
			if (id == "")
			{
				return new HashSet<int>();
			}
			id = id.ToLower();
			return (from prefab in ZNetScene.instance.m_namedPrefabs.Values
				where IsIncluded(id, ((Object)prefab).name.ToLower())
				select StringExtensionMethods.GetStableHashCode(((Object)prefab).name)).ToHashSet();
		}

		public static HashSet<int> GetPrefabs(string id)
		{
			id = id.ToLower();
			IEnumerable<GameObject> values = ZNetScene.instance.m_namedPrefabs.Values;
			values = values.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (GameObject prefab) => ((Object)prefab).name != "Player");
			values = ((id == "*" || id == "") ? values.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (GameObject prefab) => !((Object)prefab).name.StartsWith("_", StringComparison.Ordinal)) : ((!id.Contains("*")) ? values.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (GameObject prefab) => ((Object)prefab).name.ToLower() == id) : values.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (GameObject prefab) => IsIncluded(id, ((Object)prefab).name.ToLower()))));
			return values.Select([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (GameObject prefab) => StringExtensionMethods.GetStableHashCode(((Object)prefab).name)).ToHashSet();
		}

		public static ZNetView[] GetNearby(string id, ObjectType type, List<string> ignoredIds, Vector3 center, float radius, float height)
		{
			//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)
			HashSet<int> ignoredPrefabs = GetIgnoredPrefabs(ignoredIds);
			Func<Vector3, bool> checker = (Vector3 pos) => Within(pos, center, radius, height);
			return GetNearby(id, type, ignoredPrefabs, checker);
		}

		public static ZNetView[] GetNearby(string id, ObjectType type, List<string> ignoredIds, Vector3 center, float angle, float width, float depth, float height)
		{
			//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)
			HashSet<int> ignoredPrefabs = GetIgnoredPrefabs(ignoredIds);
			Func<Vector3, bool> checker = (Vector3 pos) => Within(pos, center, angle, width, depth, height);
			return GetNearby(id, type, ignoredPrefabs, checker);
		}

		public static ZNetView[] GetNearby(string id, ObjectType type, HashSet<int> ignoredPrefabs, Func<Vector3, bool> checker)
		{
			HashSet<int> codes = GetPrefabs(id);
			ZNetScene scene = ZNetScene.instance;
			IEnumerable<ZNetView> source = ZNetScene.instance.m_instances.Values.Where(IsValid);
			source = source.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (ZNetView view) => codes.Contains(view.GetZDO().GetPrefab()));
			source = source.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (ZNetView view) => !ignoredPrefabs.Contains(view.GetZDO().GetPrefab()));
			source = source.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (ZNetView view) => checker(view.GetZDO().GetPosition()));
			if (type == ObjectType.Structure)
			{
				source = source.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (ZNetView view) => Object.op_Implicit((Object)(object)scene.GetPrefab(view.GetZDO().GetPrefab()).GetComponent<Piece>()));
			}
			if (type == ObjectType.Character)
			{
				source = source.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (ZNetView view) => Object.op_Implicit((Object)(object)scene.GetPrefab(view.GetZDO().GetPrefab()).GetComponent<Character>()));
			}
			ZNetView[] array = source.ToArray();
			if (array.Length == 0)
			{
				throw new InvalidOperationException("Nothing is nearby.");
			}
			return array;
		}

		public static ZNetView[] GetConnected(ZNetView baseView, List<string> ignoredIds)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: 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)
			HashSet<int> ignoredPrefabs = GetIgnoredPrefabs(ignoredIds);
			if (ValheimRAFT.IsInRaft(baseView))
			{
				return ValheimRAFT.GetConnectedRaft(baseView, ignoredPrefabs);
			}
			WearNTear item = ((Component)baseView).GetComponent<WearNTear>() ?? throw new InvalidOperationException("Connected doesn't work for this object.");
			HashSet<ZNetView> hashSet = new HashSet<ZNetView> { baseView };
			Queue<WearNTear> queue = new Queue<WearNTear>();
			queue.Enqueue(item);
			while (queue.Count > 0)
			{
				WearNTear val = queue.Dequeue();
				if (val.m_colliders == null)
				{
					val.SetupColliders();
				}
				foreach (BoundData bound in val.m_bounds)
				{
					int num = Physics.OverlapBoxNonAlloc(bound.m_pos, bound.m_size, WearNTear.s_tempColliders, bound.m_rot, WearNTear.s_rayMask);
					for (int i = 0; i < num; i++)
					{
						Collider val2 = WearNTear.s_tempColliders[i];
						if (!val2.isTrigger && !((Object)(object)val2.attachedRigidbody != (Object)null) && !val.m_colliders.Contains(val2))
						{
							WearNTear componentInParent = ((Component)val2).GetComponentInParent<WearNTear>();
							if (Object.op_Implicit((Object)(object)componentInParent) && IsValid(componentInParent.m_nview) && !ignoredPrefabs.Contains(componentInParent.m_nview.GetZDO().GetPrefab()) && !hashSet.Contains(componentInParent.m_nview))
							{
								hashSet.Add(componentInParent.m_nview);
								queue.Enqueue(componentInParent);
							}
						}
					}
				}
			}
			return hashSet.ToArray();
		}
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	public class FakeZDO
	{
		private readonly ZDOData Data;

		public readonly ZDO Source;

		public int Prefab => Source.m_prefab;

		public Vector3 Position => Source.m_position;

		public FakeZDO(ZDO zdo)
		{
			Data = new ZDOData(zdo);
			Source = zdo.Clone();
		}

		public ZDO Create()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			ZDO val = ZDOMan.instance.CreateNewZDO(Position, Prefab);
			Copy(val);
			return val;
		}

		public void Copy(ZDO zdo)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_003a: Unknown result type (might be due to invalid IL or missing references)
			zdo.m_prefab = Source.m_prefab;
			zdo.m_position = Source.m_position;
			zdo.m_rotation = Source.m_rotation;
			zdo.Type = Source.Type;
			zdo.Distant = Source.Distant;
			zdo.Persistent = Source.Persistent;
			Data.Copy(zdo);
		}
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	public class ZDOData
	{
		public Dictionary<int, string> Strings = new Dictionary<int, string>();

		public Dictionary<int, float> Floats = new Dictionary<int, float>();

		public Dictionary<int, int> Ints = new Dictionary<int, int>();

		public Dictionary<int, long> Longs = new Dictionary<int, long>();

		public Dictionary<int, Vector3> Vecs = new Dictionary<int, Vector3>();

		public Dictionary<int, Quaternion> Quats = new Dictionary<int, Quaternion>();

		public Dictionary<int, byte[]> ByteArrays = new Dictionary<int, byte[]>();

		public ZDOData()
		{
		}

		public ZDOData(ZDO zdo)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			ZDOID uid = zdo.m_uid;
			Floats = (ZDOExtraData.s_floats.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, float>>)ZDOExtraData.s_floats[uid]).ToDictionary([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, float> kvp) => kvp.Key, [<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, float> kvp) => kvp.Value) : new Dictionary<int, float>());
			Ints = (ZDOExtraData.s_ints.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, int>>)ZDOExtraData.s_ints[uid]).ToDictionary([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, int> kvp) => kvp.Key, [<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, int> kvp) => kvp.Value) : new Dictionary<int, int>());
			Longs = (ZDOExtraData.s_longs.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, long>>)ZDOExtraData.s_longs[uid]).ToDictionary([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, long> kvp) => kvp.Key, [<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, long> kvp) => kvp.Value) : new Dictionary<int, long>());
			Strings = (ZDOExtraData.s_strings.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, string>>)ZDOExtraData.s_strings[uid]).ToDictionary([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, string> kvp) => kvp.Key, [<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, string> kvp) => kvp.Value) : new Dictionary<int, string>());
			Vecs = (ZDOExtraData.s_vec3.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, Vector3>>)ZDOExtraData.s_vec3[uid]).ToDictionary([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, Vector3> kvp) => kvp.Key, [<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, Vector3> kvp) => kvp.Value) : new Dictionary<int, Vector3>());
			Quats = (ZDOExtraData.s_quats.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, Quaternion>>)ZDOExtraData.s_quats[uid]).ToDictionary([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, Quaternion> kvp) => kvp.Key, [<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, Quaternion> kvp) => kvp.Value) : new Dictionary<int, Quaternion>());
			ByteArrays = (ZDOExtraData.s_byteArrays.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, byte[]>>)ZDOExtraData.s_byteArrays[uid]).ToDictionary([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, byte[]> kvp) => kvp.Key, [<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (KeyValuePair<int, byte[]> kvp) => kvp.Value) : new Dictionary<int, byte[]>());
		}

		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(2)]
		public ZDOData(ZPackage pkg)
		{
			if (pkg != null)
			{
				Load(pkg);
			}
		}

		public void Copy(ZDO zdo)
		{
			//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_001a: 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_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			ZDOID uid = zdo.m_uid;
			if (Floats.Count > 0)
			{
				ZDOHelper.Release<float>(ZDOExtraData.s_floats, uid);
				foreach (KeyValuePair<int, float> @float in Floats)
				{
					ZDOExtraData.Set(uid, @float.Key, @float.Value);
				}
			}
			if (Ints.Count > 0)
			{
				ZDOHelper.Release<int>(ZDOExtraData.s_ints, uid);
				foreach (KeyValuePair<int, int> @int in Ints)
				{
					ZDOExtraData.Set(uid, @int.Key, @int.Value);
				}
			}
			if (Longs.Count > 0)
			{
				ZDOHelper.Release<long>(ZDOExtraData.s_longs, uid);
				foreach (KeyValuePair<int, long> @long in Longs)
				{
					ZDOExtraData.Set(uid, @long.Key, @long.Value);
				}
			}
			if (Strings.Count > 0)
			{
				ZDOHelper.Release<string>(ZDOExtraData.s_strings, uid);
				foreach (KeyValuePair<int, string> @string in Strings)
				{
					ZDOExtraData.Set(uid, @string.Key, @string.Value);
				}
			}
			if (Vecs.Count > 0)
			{
				ZDOHelper.Release<Vector3>(ZDOExtraData.s_vec3, uid);
				foreach (KeyValuePair<int, Vector3> vec in Vecs)
				{
					ZDOExtraData.Set(uid, vec.Key, vec.Value);
				}
			}
			if (Quats.Count > 0)
			{
				ZDOHelper.Release<Quaternion>(ZDOExtraData.s_quats, uid);
				foreach (KeyValuePair<int, Quaternion> quat in Quats)
				{
					ZDOExtraData.Set(uid, quat.Key, quat.Value);
				}
			}
			if (ByteArrays.Count > 0)
			{
				ZDOHelper.Release<byte[]>(ZDOExtraData.s_byteArrays, uid);
				foreach (KeyValuePair<int, byte[]> byteArray in ByteArrays)
				{
					ZDOExtraData.Set(uid, byteArray.Key, byteArray.Value);
				}
			}
			zdo.IncreaseDataRevision();
		}

		public string GetString(int hash, string defautlValue = "")
		{
			if (!Strings.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public string GetString(string key, string defautlValue = "")
		{
			return GetString(StringExtensionMethods.GetStableHashCode(key), defautlValue);
		}

		public void Set(int hash, string value)
		{
			Strings[hash] = value;
		}

		public void Set(string key, string value)
		{
			Set(StringExtensionMethods.GetStableHashCode(key), value);
		}

		public float GetFloat(int hash, float defautlValue = 0f)
		{
			if (!Floats.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public void Set(int hash, float value)
		{
			Floats[hash] = value;
		}

		public int GetInt(int hash, int defautlValue = 0)
		{
			if (!Ints.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public int GetInt(string key, int defautlValue = 0)
		{
			return GetInt(StringExtensionMethods.GetStableHashCode(key), defautlValue);
		}

		public void Set(int hash, int value)
		{
			Ints[hash] = value;
		}

		public void Set(string key, int value)
		{
			Set(StringExtensionMethods.GetStableHashCode(key), value);
		}

		public void Set(int hash, bool value)
		{
			Ints[hash] = (value ? 1 : 0);
		}

		public long GetLong(int hash, long defautlValue = 0L)
		{
			if (!Longs.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)]
		public ZDOID GetZDOID(KeyValuePair<int, int> hashPair)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			long @long = GetLong(hashPair.Key, 0L);
			uint num = (uint)GetLong(hashPair.Value, 0L);
			if (@long == 0L || num == 0)
			{
				return ZDOID.None;
			}
			return new ZDOID(@long, num);
		}

		public void Set(int hash, long value)
		{
			Longs[hash] = value;
		}

		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)]
		public void Set(KeyValuePair<int, int> hashPair, ZDOID id)
		{
			Set(hashPair.Key, ((ZDOID)(ref id)).UserID);
			Set(hashPair.Value, (long)((ZDOID)(ref id)).ID);
		}

		public Vector3 GetVector(int hash, Vector3 defautlValue)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (!Vecs.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public void Set(int hash, Vector3 value)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Vecs[hash] = value;
		}

		public Quaternion GetQuaternion(int hash, Quaternion defautlValue)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (!Quats.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public void Set(int hash, Quaternion value)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Quats[hash] = value;
		}

		public byte[] GetByteArray(int hash, byte[] defautlValue)
		{
			if (!ByteArrays.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public void Set(int hash, byte[] value)
		{
			ByteArrays[hash] = value;
		}

		public ZPackage Save()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			Vecs.Remove(Hash.Scale);
			Vecs.Remove(Hash.SpawnPoint);
			if (Strings.ContainsKey(Hash.OverrideItems))
			{
				Ints.Remove(Hash.AddedDefaultItems);
				Strings.Remove(Hash.Items);
			}
			int num = 0;
			if (Floats.Count > 0)
			{
				num |= 1;
			}
			if (Vecs.Count > 0)
			{
				num |= 2;
			}
			if (Quats.Count > 0)
			{
				num |= 4;
			}
			if (Ints.Count > 0)
			{
				num |= 8;
			}
			if (Strings.Count > 0)
			{
				num |= 0x10;
			}
			if (Longs.Count > 0)
			{
				num |= 0x40;
			}
			if (ByteArrays.Count > 0)
			{
				num |= 0x80;
			}
			val.Write(num);
			if (Floats.Count > 0)
			{
				val.Write((byte)Floats.Count);
				foreach (KeyValuePair<int, float> @float in Floats)
				{
					val.Write(@float.Key);
					val.Write(@float.Value);
				}
			}
			if (Vecs.Count > 0)
			{
				val.Write((byte)Vecs.Count);
				foreach (KeyValuePair<int, Vector3> vec in Vecs)
				{
					val.Write(vec.Key);
					val.Write(vec.Value);
				}
			}
			if (Quats.Count > 0)
			{
				val.Write((byte)Quats.Count);
				foreach (KeyValuePair<int, Quaternion> quat in Quats)
				{
					val.Write(quat.Key);
					val.Write(quat.Value);
				}
			}
			if (Ints.Count > 0)
			{
				val.Write((byte)Ints.Count);
				foreach (KeyValuePair<int, int> @int in Ints)
				{
					val.Write(@int.Key);
					val.Write(@int.Value);
				}
			}
			if (Longs.Count > 0)
			{
				val.Write((byte)Longs.Count);
				foreach (KeyValuePair<int, long> @long in Longs)
				{
					val.Write(@long.Key);
					val.Write(@long.Value);
				}
			}
			if (Strings.Count > 0)
			{
				val.Write((byte)Strings.Count);
				foreach (KeyValuePair<int, string> @string in Strings)
				{
					val.Write(@string.Key);
					val.Write(@string.Value);
				}
			}
			if (ByteArrays.Count > 0)
			{
				val.Write((byte)ByteArrays.Count);
				foreach (KeyValuePair<int, byte[]> byteArray in ByteArrays)
				{
					val.Write(byteArray.Key);
					val.Write(byteArray.Value);
				}
			}
			return val;
		}

		public void Load(ZPackage pkg)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			pkg.SetPos(0);
			int num = pkg.ReadInt();
			if (((uint)num & (true ? 1u : 0u)) != 0)
			{
				byte b = pkg.ReadByte();
				for (int i = 0; i < b; i++)
				{
					Floats[pkg.ReadInt()] = pkg.ReadSingle();
				}
			}
			if (((uint)num & 2u) != 0)
			{
				byte b2 = pkg.ReadByte();
				for (int j = 0; j < b2; j++)
				{
					Vecs[pkg.ReadInt()] = pkg.ReadVector3();
				}
			}
			if (((uint)num & 4u) != 0)
			{
				byte b3 = pkg.ReadByte();
				for (int k = 0; k < b3; k++)
				{
					Quats[pkg.ReadInt()] = pkg.ReadQuaternion();
				}
			}
			if (((uint)num & 8u) != 0)
			{
				byte b4 = pkg.ReadByte();
				for (int l = 0; l < b4; l++)
				{
					Ints[pkg.ReadInt()] = pkg.ReadInt();
				}
			}
			if (((uint)num & 0x40u) != 0)
			{
				byte b5 = pkg.ReadByte();
				for (int m = 0; m < b5; m++)
				{
					Longs[pkg.ReadInt()] = pkg.ReadLong();
				}
			}
			if (((uint)num & 0x10u) != 0)
			{
				byte b6 = pkg.ReadByte();
				for (int n = 0; n < b6; n++)
				{
					Strings[pkg.ReadInt()] = pkg.ReadString();
				}
			}
			if (((uint)num & 0x80u) != 0)
			{
				byte b7 = pkg.ReadByte();
				for (int num2 = 0; num2 < b7; num2++)
				{
					ByteArrays[pkg.ReadInt()] = pkg.ReadByteArray();
				}
			}
		}
	}
}
namespace InfinityHammer
{
	public class BuildMenuCommand : Piece
	{
		[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(1)]
		public string Command = "";
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	[HarmonyPatch(typeof(PieceTable), "UpdateAvailable")]
	public static class UpdateAvailable
	{
		private static Piece Build(string command)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			CommandParameters commandParameters = new CommandParameters(command, Configuration.AlwaysShowCommand);
			BuildMenuCommand buildMenuCommand = new GameObject().AddComponent<BuildMenuCommand>();
			buildMenuCommand.Command = command;
			((Piece)buildMenuCommand).m_description = commandParameters.Description;
			((Piece)buildMenuCommand).m_name = commandParameters.Name;
			((Piece)buildMenuCommand).m_icon = commandParameters.Icon;
			return (Piece)(object)buildMenuCommand;
		}

		private static void Postfix(PieceTable __instance)
		{
			if (!Configuration.IsCheats)
			{
				return;
			}
			List<string> list = null;
			int num = 0;
			int val = 0;
			if (Hammer.HasTool(Helper.GetPlayer(), Tool.Hammer))
			{
				list = CommandManager.HammerCommands;
				num = Configuration.HammerMenuTab;
				val = Configuration.HammerMenuIndex;
			}
			if (Hammer.HasTool(Helper.GetPlayer(), Tool.Hoe))
			{
				list = CommandManager.HoeCommands;
				num = Configuration.HoeMenuTab;
				val = Configuration.HoeMenuIndex;
			}
			if (list == null || __instance.m_availablePieces.Count <= num)
			{
				return;
			}
			List<Piece> list2 = __instance.m_availablePieces[num];
			val = Math.Min(val, list2.Count);
			foreach (string item in Enumerable.Reverse(list))
			{
				list2.Insert(val, Build(item));
			}
		}
	}
	[HarmonyPatch(typeof(Player), "SetSelectedPiece", new Type[] { typeof(Vector2Int) })]
	public class RunBuildMenuCommands
	{
		public static bool InstantCommand;

		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		[HarmonyPriority(200)]
		public static bool Prefix(Player __instance, Vector2Int p)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			Piece piece = __instance.GetPiece(p);
			BuildMenuCommand buildMenuCommand = default(BuildMenuCommand);
			if (Object.op_Implicit((Object)(object)piece) && ((Component)piece).TryGetComponent<BuildMenuCommand>(ref buildMenuCommand))
			{
				InstantCommand = false;
				((Terminal)Console.instance).TryRunCommand(buildMenuCommand.Command, false, false);
				if (!InstantCommand)
				{
					__instance.m_buildPieces.SetSelected(p);
				}
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Terminal), "TryRunCommand")]
	public class ReplaceModifierKeys
	{
		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		[HarmonyPriority(600)]
		private static void Prefix(ref string text)
		{
			if (!text.StartsWith("bind ", StringComparison.OrdinalIgnoreCase) && !text.StartsWith("alias ", StringComparison.OrdinalIgnoreCase))
			{
				text = text.Replace("cmd_mod1", Configuration.ModifierKey1());
				text = text.Replace("cmd_mod2", Configuration.ModifierKey2());
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "TryRunCommand")]
	public class RemoveCmdParameters
	{
		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		[HarmonyPriority(200)]
		private static void Prefix(ref string text)
		{
			if (!text.StartsWith("hammer_command ", StringComparison.OrdinalIgnoreCase) && !text.StartsWith("hoe_command ", StringComparison.OrdinalIgnoreCase) && !text.StartsWith("hammer_add ", StringComparison.OrdinalIgnoreCase) && !text.StartsWith("hoe_add ", StringComparison.OrdinalIgnoreCase))
			{
				text = CommandParameters.RemoveCmdParameters(text);
				RunBuildMenuCommands.InstantCommand = true;
			}
		}
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	public static class CoverCheck
	{
		public const float CoverRayCastLength = 30f;

		public const float CoverRaycastStart = 0.5f;

		public const float CoverBedLimit = 0.8f;

		public const float CoverCraftingStationLimit = 0.7f;

		public const float CoverFermenterLimit = 0.7f;

		public const float CoverFireplaceLimit = 0.7f;

		public const string FORMAT = "0.##";

		public static string CurrentCover = "";

		public static Vector3 GetCoverPoint(CraftingStation obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return obj.m_roofCheckPoint.position;
		}

		public static Vector3 GetCoverPoint(Fermenter obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return obj.m_roofCheckPoint.position;
		}

		public static Vector3 GetCoverPoint(Beehive obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return obj.m_coverPoint.position;
		}

		public static Vector3 GetCoverPoint(Fireplace obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			return ((Component)obj).transform.position + Vector3.up * obj.m_coverCheckOffset;
		}

		public static Vector3 GetCoverPoint(Bed obj)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return obj.GetSpawnPoint();
		}

		public static Vector3 GetCoverPoint(Windmill obj)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			return ((Component)obj.m_propeller).transform.position;
		}

		public static bool ChecksCover(Fireplace obj)
		{
			if ((Object)(object)obj.m_enabledObjectLow != (Object)null)
			{
				return (Object)(object)obj.m_enabledObjectHigh != (Object)null;
			}
			return false;
		}

		public static string String(string value, string color = "white")
		{
			return "<color=" + color + ">" + value + "</color>";
		}

		public static string Percent(double value, string color = "white")
		{
			return String(value.ToString("P0"), color);
		}

		public static string JoinLines(IEnumerable<string> lines)
		{
			return string.Join(". ", lines.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (string line) => line != ""));
		}

		public static void CheckCover(GameObject obj)
		{
			CurrentCover = "";
			GetCover(obj.GetComponent<Beehive>());
			GetCover(obj.GetComponent<Fermenter>());
			GetCover(obj.GetComponent<Fireplace>());
			GetCover(obj.GetComponent<Bed>());
			GetCover(obj.GetComponent<CraftingStation>());
			GetCover(obj.GetComponent<Windmill>());
		}

		public static void GetCover(Beehive obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)obj))
			{
				GetCover(GetCoverPoint(obj), obj.m_maxCover, checkRoof: false, minLimit: false);
			}
		}

		public static void GetCover(Fermenter obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)obj))
			{
				GetCover(GetCoverPoint(obj), 0.7f);
			}
		}

		public static void GetCover(Fireplace obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)obj))
			{
				GetCover(GetCoverPoint(obj), 0.7f, checkRoof: false);
			}
		}

		public static void GetCover(Bed obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)obj))
			{
				GetCover(GetCoverPoint(obj), 0.8f);
			}
		}

		public static void GetCover(CraftingStation obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)obj))
			{
				GetCover(GetCoverPoint(obj), 0.7f);
			}
		}

		public static void GetCover(Windmill obj)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)obj))
			{
				GetCover(GetCoverPoint(obj), 0f, checkRoof: false);
			}
		}

		public static void GetCover(Vector3 position, float limit, bool checkRoof = true, bool minLimit = true)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = new List<string>();
			float num = default(float);
			bool flag = default(bool);
			Cover.GetCoverForPoint(position, ref num, ref flag, 0.5f);
			string text = Percent(num) + " cover";
			if (limit > 0f)
			{
				bool flag2 = (minLimit ? (num < limit) : (num > limit));
				text = text + " (" + Percent(limit, flag2 ? "yellow" : "white") + ")";
			}
			list.Add(text);
			if (checkRoof && !flag)
			{
				list.Add(String("Missing roof", "yellow"));
			}
			CurrentCover = JoinLines(list);
		}
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	[HarmonyPatch(typeof(Hud), "SetupPieceInfo")]
	public class AddExtraInfo
	{
		public static bool ShowId;

		private static string DescriptionHover()
		{
			if (!Selection.IsCommand())
			{
				return "";
			}
			if (!ShowId)
			{
				return "";
			}
			ZNetView hovered = Selector.GetHovered(Configuration.Range, Configuration.IgnoredIds);
			string text = (((Object)(object)hovered == (Object)null) ? "" : Utils.GetPrefabName(((Component)hovered).gameObject));
			return "id: " + text;
		}

		public static void Postfix(Hud __instance, Piece piece)
		{
			if (Object.op_Implicit((Object)(object)piece))
			{
				string[] source = new string[3]
				{
					Selection.Description(),
					Ruler.Description(),
					DescriptionHover()
				};
				string text = string.Join("\n", source.Where([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(0)] (string s) => s != ""));
				if (__instance.m_pieceDescription.text != "")
				{
					text = "\n" + text;
				}
				Text pieceDescription = __instance.m_pieceDescription;
				pieceDescription.text += text;
			}
		}
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	public class DataHelper
	{
		public static void Init(string name, Transform tr, [<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)] ZDOData data = null)
		{
			Init(StringExtensionMethods.GetStableHashCode(name), tr, data);
		}

		public static void Init(int hash, Transform tr, [<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(2)] ZDOData data = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			Init(hash, tr.position, tr.rotation, tr.lossyScale, data);
		}

		public static void Init(ZDO zdo)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			Init(zdo.GetPrefab(), zdo.GetPosition(), zdo.GetRotation(), zdo.GetVec3("scale", Vector3.one), new ZDOData(zdo));
		}

		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(2)]
		public static void Init(int hash, Vector3 pos, Quaternion rot, Vector3 scale, ZDOData data = null)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			Clear();
			ZNetView val = default(ZNetView);
			if (ZNetScene.instance.m_namedPrefabs.TryGetValue(hash, out var value) && value.TryGetComponent<ZNetView>(ref val) && (data != null || (val.m_syncInitialScale && !(scale == Vector3.one))))
			{
				ZNetView.m_initZDO = ZDOMan.instance.CreateNewZDO(pos, hash);
				data?.Copy(ZNetView.m_initZDO);
				ZNetView.m_initZDO.m_rotation = ((Quaternion)(ref rot)).eulerAngles;
				ZNetView.m_initZDO.Type = val.m_type;
				ZNetView.m_initZDO.Distant = val.m_distant;
				ZNetView.m_initZDO.Persistent = val.m_persistent;
				ZNetView.m_initZDO.m_prefab = hash;
				if (val.m_syncInitialScale)
				{
					ZNetView.m_initZDO.Set("scale", scale);
				}
				ZNetView.m_initZDO.DataRevision = 1u;
			}
		}

		public static void Clear()
		{
			ZNetView.m_initZDO = null;
		}
	}
	[HarmonyPatch(typeof(Player), "FindClosestSnapPoints")]
	public class DisableSnapsWhenFrozen
	{
		private static bool Prefix()
		{
			return !Position.Override.HasValue;
		}
	}
	[HarmonyPatch(typeof(Player), "PieceRayTest")]
	public class FreezePlacementMarker
	{
		private static Vector3 CurrentNormal = Vector3.up;

		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		private static void Postfix(ref Vector3 point, ref Vector3 normal, ref Piece piece, ref Heightmap heightmap, ref Collider waterSurface, ref bool __result)
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			if (__result && Grid.Enabled)
			{
				point = Grid.Apply(point, Object.op_Implicit((Object)(object)heightmap) ? Vector3.up : normal);
				if (Object.op_Implicit((Object)(object)heightmap))
				{
					point.y = ZoneSystem.instance.GetGroundHeight(point) + 2f;
					RaycastHit val = default(RaycastHit);
					if (Physics.Raycast(point, Vector3.down, ref val, 50f, Player.m_localPlayer.m_placeRayMask))
					{
						point = ((RaycastHit)(ref val)).point;
						normal = ((RaycastHit)(ref val)).normal;
					}
				}
			}
			if (Position.Override.HasValue)
			{
				point = Position.Override.Value;
				normal = CurrentNormal;
				__result = true;
				piece = null;
				heightmap = null;
				waterSurface = null;
			}
			else
			{
				CurrentNormal = normal;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
	public class OverridePlacementGhost
	{
		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: 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_0037: Expected O, but got Unknown
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(Location), "IsInsideNoBuildLocation", (Type[])null, (Type[])null), (string)null)
			}).Advance(-2).Insert((CodeInstruction[])(object)new CodeInstruction[3]
			{
				new CodeInstruction(OpCodes.Call, Transpilers.EmitDelegate<Action<GameObject>>((Action<GameObject>)([<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)] (GameObject ghost) =>
				{
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					ghost.transform.position = Position.Apply(ghost.transform.position);
				})).operand),
				new CodeInstruction(OpCodes.Ldarg_0, (object)null),
				new CodeInstruction(OpCodes.Ldfld, (object)AccessTools.Field(typeof(Player), "m_placementGhost"))
			})
				.InstructionEnumeration();
		}
	}
	public static class Grid
	{
		private static float Precision;

		private static Vector3 Center;

		public static bool Enabled => Precision != 0f;

		public static Vector3 Apply(Vector3 point, Vector3 normal)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//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_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: 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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: 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)
			if (!Enabled)
			{
				return point;
			}
			Quaternion val = Quaternion.FromToRotation(Vector3.up, normal);
			point = val * point;
			Vector3 val2 = val * Center;
			point.x = val2.x + Mathf.Round((point.x - val2.x) / Precision) * Precision;
			point.z = val2.z + Mathf.Round((point.z - val2.z) / Precision) * Precision;
			return Quaternion.Inverse(val) * point;
		}

		public static void Set(float precision, Vector3 center)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (Precision == precision)
			{
				Precision = 0f;
				return;
			}
			Center = center;
			Precision = precision;
		}
	}
	public static class Position
	{
		public static Vector3? Override = null;

		public static Vector3 Offset = Vector3.zero;

		public static void ToggleFreeze()
		{
			if (Override.HasValue)
			{
				Unfreeze();
			}
			else
			{
				Freeze();
			}
		}

		public static void Freeze(Vector3 position)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Override = position;
		}

		public static void Freeze()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			Player player = Helper.GetPlayer();
			GameObject placementGhost = player.m_placementGhost;
			Override = (Object.op_Implicit((Object)(object)placementGhost) ? Deapply(placementGhost.transform.position) : ((Component)player).transform.position);
		}

		public static void Unfreeze()
		{
			//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)
			Override = null;
			if (Configuration.ResetOffsetOnUnfreeze)
			{
				Offset = Vector3.zero;
			}
		}

		public static Vector3 Apply(Vector3 point)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			GameObject placementGhost = Helper.GetPlayer().m_placementGhost;
			if (!Object.op_Implicit((Object)(object)placementGhost))
			{
				return point;
			}
			if (Override.HasValue)
			{
				point = Override.Value;
			}
			Quaternion rotation = placementGhost.transform.rotation;
			point += rotation * Vector3.right * Offset.x;
			point += rotation * Vector3.up * Offset.y;
			point += rotation * Vector3.forward * Offset.z;
			return point;
		}

		public static Vector3 Deapply(Vector3 point)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			GameObject placementGhost = Helper.GetPlayer().m_placementGhost;
			if (!Object.op_Implicit((Object)(object)placementGhost))
			{
				return point;
			}
			if (Override.HasValue)
			{
				point = Override.Value;
			}
			Quaternion rotation = placementGhost.transform.rotation;
			point -= rotation * Vector3.right * Offset.x;
			point -= rotation * Vector3.up * Offset.y;
			point -= rotation * Vector3.forward * Offset.z;
			return point;
		}

		public static void SetX(float value)
		{
			Offset.x = value;
		}

		public static void SetY(float value)
		{
			Offset.y = value;
		}

		public static void SetZ(float value)
		{
			Offset.z = value;
		}

		public static void MoveLeft(float value)
		{
			Offset.x -= value;
		}

		public static void MoveRight(float value)
		{
			Offset.x += value;
		}

		public static void MoveDown(float value)
		{
			Offset.y -= value;
		}

		public static void MoveUp(float value)
		{
			Offset.y += value;
		}

		public static void MoveBackward(float value)
		{
			Offset.z -= value;
		}

		public static void MoveForward(float value)
		{
			Offset.z += value;
		}

		public static void Set(Vector3 value)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			Offset = value;
		}

		public static void Move(Vector3 value)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Offset += value;
		}

		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		public static void Print(Terminal terminal)
		{
			if (!Configuration.DisableOffsetMessages)
			{
				Helper.AddMessage(terminal, "Offset set to forward: " + Offset.z.ToString("F1", CultureInfo.InvariantCulture) + ", up: " + Offset.y.ToString("F1", CultureInfo.InvariantCulture) + ", right: " + Offset.x.ToString("F1", CultureInfo.InvariantCulture) + ".");
			}
		}
	}
	public static class Rotating
	{
		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		public static void UpdatePlacementRotation(GameObject obj)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			Player player = Helper.GetPlayer();
			Quaternion rotation = obj.transform.rotation;
			player.m_placeRotation = Mathf.RoundToInt(((Quaternion)(ref rotation)).eulerAngles.y / 22.5f);
			GizmoWrapper.SetRotation(rotation);
		}

		public static void RotateX(float value)
		{
			Helper.GetPlayer();
			GizmoWrapper.RotateX(value);
		}

		public static void RotateY(float value)
		{
			Player player = Helper.GetPlayer();
			player.m_placeRotation = Mathf.RoundToInt(((float)player.m_placeRotation * 22.5f + value) / 22.5f);
			GizmoWrapper.RotateY(value);
		}

		public static void RotateZ(float value)
		{
			Helper.GetPlayer();
			GizmoWrapper.RotateZ(value);
		}
	}
	[HarmonyPatch(typeof(PieceTable), "GetSelectedPiece")]
	public class GetSelectedPiece
	{
		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		public static bool Prefix(ref Piece __result)
		{
			if (Object.op_Implicit((Object)(object)Selection.Ghost))
			{
				__result = Selection.Ghost.GetComponent<Piece>();
			}
			return !Object.op_Implicit((Object)(object)__result);
		}
	}
	[HarmonyPatch(typeof(Player), "SetSelectedPiece", new Type[] { typeof(Vector2Int) })]
	public class SetSelectedPiece
	{
		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		public static void Prefix(Player __instance)
		{
			Hammer.RemoveSelection();
			__instance.SetupPlacementGhost();
		}
	}
	[HarmonyPatch(typeof(Player), "SetSelectedPiece", new Type[] { typeof(Piece) })]
	public class SetSelectedPiece2
	{
		[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
		public static void Prefix(Player __instance)
		{
			Hammer.RemoveSelection();
			__instance.SetupPlacementGhost();
		}
	}
	[<af58accb-5660-4d5b-a709-7d898b0c5541>NullableContext(1)]
	[<bdedce9d-15b6-4151-a2f6-197cd4e997fd>Nullable(0)]
	[HarmonyPatch(typeof(Player), "PlacePiece")]
	public class PlacePiece
	{
		private static bool Clear;

		private static void Prefix()
		{
			HideEffects.Active = true;
			Clear = Selection.IsSingleUse();
		}

		private static void Finalizer(bool __result)
		{
			HideEffects.Active = false;
			DataHelper.Clear();
			if (__result && Clear)
			{
				Selection.Clear();
				Hammer.Clear();
			}
		}

		private static GameObject GetPrefab(GameObject obj)
		{
			//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_0083: Expected O, but got Unknown
			if (!Configuration.Enabled)
			{
				return obj;
			}
			SelectedType type = Selection.Type;
			GameObject placementGhost = Helper.GetPlayer().m_placementGhost;
			if (!Object.op_Implicit((Object)(object)placementGhost))
			{
				return obj;
			}
			string prefabName =

BepInEx/plugins/JereKuusela-Server_devcommands/ServerDevcommands.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Fishlabs;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ServerDevcommands")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ServerDevcommands")]
[assembly: AssemblyTitle("ServerDevcommands")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<c44be0de-eb88-4316-8fa4-d1cfa405ecbc>Embedded]
	internal sealed class <c44be0de-eb88-4316-8fa4-d1cfa405ecbc>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<c44be0de-eb88-4316-8fa4-d1cfa405ecbc>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <79ee238e-4936-43cd-ab4d-2c0eb2499f37>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <79ee238e-4936-43cd-ab4d-2c0eb2499f37>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <79ee238e-4936-43cd-ab4d-2c0eb2499f37>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<c44be0de-eb88-4316-8fa4-d1cfa405ecbc>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[<c44be0de-eb88-4316-8fa4-d1cfa405ecbc>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 ServerDevcommands
{
	public class AddStatusCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__0_0;

			public static ConsoleEvent <>9__0_1;

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
			internal List<string> <.ctor>b__0_0(int index)
			{
				return index switch
				{
					0 => ParameterInfo.StatusEffects, 
					1 => ParameterInfo.Create("Effect duration in seconds."), 
					2 => ParameterInfo.Create("Effect intensity."), 
					_ => ParameterInfo.None, 
				};
			}

			internal void <.ctor>b__0_1(ConsoleEventArgs args)
			{
				Helper.ArgsCheck(args, 2, "Missing status name");
				Player player = Helper.GetPlayer();
				int stableHashCode = StringExtensionMethods.GetStableHashCode(args[1]);
				((Character)player).GetSEMan().AddStatusEffect(stableHashCode, true, 0, 0f);
				StatusEffect statusEffect = ((Character)player).GetSEMan().GetStatusEffect(stableHashCode);
				if ((Object)(object)statusEffect == (Object)null)
				{
					return;
				}
				float ttl = default(float);
				if (args.TryParameterFloat(2, ref ttl))
				{
					statusEffect.m_ttl = ttl;
				}
				float num = default(float);
				if (!args.TryParameterFloat(3, ref num))
				{
					return;
				}
				SE_Shield val = (SE_Shield)(object)((statusEffect is SE_Shield) ? statusEffect : null);
				if (val != null)
				{
					val.m_absorbDamage = num;
				}
				SE_Burning val2 = (SE_Burning)(object)((statusEffect is SE_Burning) ? statusEffect : null);
				if (val2 != null)
				{
					if (args[1] == "Burning")
					{
						val2.m_fireDamageLeft = 0f;
						val2.AddFireDamage(num);
					}
					else
					{
						val2.m_spiritDamageLeft = 0f;
						val2.AddSpiritDamage(num);
					}
				}
				SE_Poison val3 = (SE_Poison)(object)((statusEffect is SE_Poison) ? statusEffect : null);
				if (val3 != null)
				{
					val3.m_damageLeft = num;
					val3.m_damagePerHit = num / statusEffect.m_ttl * val3.m_damageInterval;
				}
			}
		}

		public AddStatusCommand()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			AutoComplete.Register("addstatus", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => index switch
			{
				0 => ParameterInfo.StatusEffects, 
				1 => ParameterInfo.Create("Effect duration in seconds."), 
				2 => ParameterInfo.Create("Effect intensity."), 
				_ => ParameterInfo.None, 
			});
			object obj = <>c.<>9__0_1;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					Helper.ArgsCheck(args, 2, "Missing status name");
					Player player = Helper.GetPlayer();
					int stableHashCode = StringExtensionMethods.GetStableHashCode(args[1]);
					((Character)player).GetSEMan().AddStatusEffect(stableHashCode, true, 0, 0f);
					StatusEffect statusEffect = ((Character)player).GetSEMan().GetStatusEffect(stableHashCode);
					if (!((Object)(object)statusEffect == (Object)null))
					{
						float ttl = default(float);
						if (args.TryParameterFloat(2, ref ttl))
						{
							statusEffect.m_ttl = ttl;
						}
						float num = default(float);
						if (args.TryParameterFloat(3, ref num))
						{
							SE_Shield val2 = (SE_Shield)(object)((statusEffect is SE_Shield) ? statusEffect : null);
							if (val2 != null)
							{
								val2.m_absorbDamage = num;
							}
							SE_Burning val3 = (SE_Burning)(object)((statusEffect is SE_Burning) ? statusEffect : null);
							if (val3 != null)
							{
								if (args[1] == "Burning")
								{
									val3.m_fireDamageLeft = 0f;
									val3.AddFireDamage(num);
								}
								else
								{
									val3.m_spiritDamageLeft = 0f;
									val3.AddSpiritDamage(num);
								}
							}
							SE_Poison val4 = (SE_Poison)(object)((statusEffect is SE_Poison) ? statusEffect : null);
							if (val4 != null)
							{
								val4.m_damageLeft = num;
								val4.m_damagePerHit = num / statusEffect.m_ttl * val4.m_damageInterval;
							}
						}
					}
				};
				<>c.<>9__0_1 = val;
				obj = (object)val;
			}
			Helper.Command("addstatus", "[name] [duration] [intenstiy] - Adds a status effect.", (ConsoleEvent)obj);
		}
	}
	public class AliasCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__0_0;

			public static Func<string, string> <>9__1_2;

			public static ConsoleEvent <>9__1_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, int, List<string>> <>9__1_1;

			internal void <AddCommand>b__0_0(ConsoleEventArgs args)
			{
			}

			internal void <.ctor>b__1_0(ConsoleEventArgs args)
			{
				if (args.Length < 2)
				{
					args.Context.AddString(string.Join("\n", Settings.AliasKeys.Select((string key) => key + " -> " + Settings.GetAliasValue(key))));
				}
				else if (args.Length < 3)
				{
					Settings.RemoveAlias(args[1]);
					if (Terminal.commands.ContainsKey(args[1]))
					{
						Terminal.commands.Remove(args[1]);
					}
					args.Context.updateCommandList();
					AliasManager.ToBeSaved = true;
				}
				else
				{
					string value = string.Join(" ", args.Args.Skip(2));
					Settings.AddAlias(args[1], value);
					AddCommand(args[1], value);
					args.Context.updateCommandList();
					AliasManager.ToBeSaved = true;
				}
			}

			internal string <.ctor>b__1_2(string key)
			{
				return key + " -> " + Settings.GetAliasValue(key);
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
			internal List<string> <.ctor>b__1_1(int index, int subIndex)
			{
				if (index == 0)
				{
					return ParameterInfo.Create("Name of the alias.");
				}
				return ParameterInfo.None;
			}
		}

		[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
		public static void AddCommand(string key, string value)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			string text = Aliasing.Plain(value);
			string key2 = text.Split(new char[1] { ' ' }).First();
			if (Terminal.commands.TryGetValue(key2, out var value2))
			{
				new ConsoleCommand(key, text, value2.action, value2.IsCheat, value2.IsNetwork, value2.OnlyServer, value2.IsSecret, value2.AllowInDevBuild, value2.m_tabOptionsFetcher, false);
				return;
			}
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate
				{
				};
				<>c.<>9__0_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand(key, text, (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
		}

		public AliasCommand()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			object obj = <>c.<>9__1_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					if (args.Length < 2)
					{
						args.Context.AddString(string.Join("\n", Settings.AliasKeys.Select((string key) => key + " -> " + Settings.GetAliasValue(key))));
					}
					else if (args.Length < 3)
					{
						Settings.RemoveAlias(args[1]);
						if (Terminal.commands.ContainsKey(args[1]))
						{
							Terminal.commands.Remove(args[1]);
						}
						args.Context.updateCommandList();
						AliasManager.ToBeSaved = true;
					}
					else
					{
						string value = string.Join(" ", args.Args.Skip(2));
						Settings.AddAlias(args[1], value);
						AddCommand(args[1], value);
						args.Context.updateCommandList();
						AliasManager.ToBeSaved = true;
					}
				};
				<>c.<>9__1_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("alias", "[name] [command] - Sets a command alias.", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			AutoComplete.Register("alias", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index, int subIndex) => (index == 0) ? ParameterInfo.Create("Name of the alias.") : ParameterInfo.None);
		}
	}
	[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
	[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
	[HarmonyPatch]
	public class BindCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static readonly <>c <>9 = new <>c();

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<string, string> <>9__1_6;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static ConsoleEvent <>9__1_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static ConsoleOptionsFetcher <>9__1_1;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, int, List<string>> <>9__1_2;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__1_7;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__1_4;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<KeyValuePair<KeyCode, List<string>>, bool> <>9__3_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<KeyValuePair<KeyCode, List<string>>, IEnumerable<string>> <>9__3_1;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<string, bool> <>9__4_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<string, bool> <>9__5_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<string, bool> <>9__6_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<string, bool> <>9__10_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<string, bool> <>9__10_1;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<string, bool> <>9__10_2;

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal void <.ctor>b__1_0(ConsoleEventArgs args)
			{
				//IL_0053: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				if (args.Length < 2)
				{
					return;
				}
				string[] array = (from key in Parse.Split(args[1])
					select key.ToLower()).ToArray();
				if (array[0] == "wheel")
				{
					KeyCode mouseWheelBindKey = Settings.MouseWheelBindKey;
					array[0] = ((object)(KeyCode)(ref mouseWheelBindKey)).ToString().ToLower();
				}
				if (!Enum.TryParse<KeyCode>(array[0], ignoreCase: true, out KeyCode _))
				{
					args.Context.AddString("'" + array[0] + "' is not a valid UnityEngine.KeyCode.");
					return;
				}
				string text = array[0];
				if (array.Length > 1)
				{
					text = text + " keys=" + string.Join(",", array.Skip(1));
				}
				string item = text + " " + string.Join(" ", args.Args.Skip(2));
				Terminal.m_bindList.Add(item);
				Terminal.updateBinds();
				BindManager.ToBeSaved = true;
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal string <.ctor>b__1_6(string key)
			{
				return key.ToLower();
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal List<string> <.ctor>b__1_1()
			{
				return ParameterInfo.KeyCodes;
			}

			internal List<string> <.ctor>b__1_2(int index, int subIndex)
			{
				if (index == 0 && subIndex == 0)
				{
					return ParameterInfo.KeyCodes;
				}
				if (index == 0 && subIndex == 1)
				{
					return ParameterInfo.KeyCodesWithNegative;
				}
				return ParameterInfo.Create("The command to bind.");
			}

			internal List<string> <.ctor>b__1_7(int index)
			{
				return ParameterInfo.KeyCodesWithNegative;
			}

			internal List<string> <.ctor>b__1_4(int index)
			{
				return index switch
				{
					0 => ParameterInfo.KeyCodes, 
					1 => ParameterInfo.Create("Amount of binds to remove from the key."), 
					_ => ParameterInfo.None, 
				};
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <ExecuteBestBinds>b__3_0(KeyValuePair<KeyCode, List<string>> kvp)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				return Input.GetKeyDown(kvp.Key);
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal IEnumerable<string> <ExecuteBestBinds>b__3_1(KeyValuePair<KeyCode, List<string>> kvp)
			{
				return kvp.Value;
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <CountKeys>b__4_0(string arg)
			{
				return arg.StartsWith("keys=");
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <CountKeys>b__5_0(string key)
			{
				KeyCode result;
				if (!key.StartsWith("-", StringComparison.Ordinal))
				{
					return Enum.TryParse<KeyCode>(key, ignoreCase: true, out result);
				}
				return false;
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <Valid>b__6_0(string arg)
			{
				return arg.StartsWith("keys=");
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <CleanUp>b__10_0(string arg)
			{
				return !arg.StartsWith("tag=", StringComparison.OrdinalIgnoreCase);
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <CleanUp>b__10_1(string arg)
			{
				return arg.StartsWith("keys=", StringComparison.OrdinalIgnoreCase);
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <CleanUp>b__10_2(string arg)
			{
				return !arg.StartsWith("keys=", StringComparison.OrdinalIgnoreCase);
			}
		}

		private static string Mode = "";

		private void Print(Terminal terminal, string command)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			KeyCode mouseWheelBindKey = Settings.MouseWheelBindKey;
			string text = ((object)(KeyCode)(ref mouseWheelBindKey)).ToString();
			if (command.StartsWith(text, StringComparison.OrdinalIgnoreCase))
			{
				command = "wheel" + command.Substring(text.Length);
			}
			terminal.AddString(command);
		}

		public BindCommand()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			object obj = <>c.<>9__1_0;
			if (obj == null)
			{
				ConsoleEvent val = [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ConsoleEventArgs args) =>
				{
					//IL_0053: Unknown result type (might be due to invalid IL or missing references)
					//IL_0058: Unknown result type (might be due to invalid IL or missing references)
					if (args.Length >= 2)
					{
						string[] array = (from key in Parse.Split(args[1])
							select key.ToLower()).ToArray();
						if (array[0] == "wheel")
						{
							KeyCode mouseWheelBindKey = Settings.MouseWheelBindKey;
							array[0] = ((object)(KeyCode)(ref mouseWheelBindKey)).ToString().ToLower();
						}
						if (!Enum.TryParse<KeyCode>(array[0], ignoreCase: true, out KeyCode _))
						{
							args.Context.AddString("'" + array[0] + "' is not a valid UnityEngine.KeyCode.");
						}
						else
						{
							string text2 = array[0];
							if (array.Length > 1)
							{
								text2 = text2 + " keys=" + string.Join(",", array.Skip(1));
							}
							string item = text2 + " " + string.Join(" ", args.Args.Skip(2));
							Terminal.m_bindList.Add(item);
							Terminal.updateBinds();
							BindManager.ToBeSaved = true;
						}
					}
				};
				<>c.<>9__1_0 = val;
				obj = (object)val;
			}
			object obj2 = <>c.<>9__1_1;
			if (obj2 == null)
			{
				ConsoleOptionsFetcher val2 = [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] () => ParameterInfo.KeyCodes;
				<>c.<>9__1_1 = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("bind", "[keycode,modifier1,modifier2,...] [command] [parameters] - Binds a key (with modifier keys) to a command.", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)obj2, false);
			AutoComplete.Register("bind", delegate(int index, int subIndex)
			{
				if (index == 0 && subIndex == 0)
				{
					return ParameterInfo.KeyCodes;
				}
				return (index == 0 && subIndex == 1) ? ParameterInfo.KeyCodesWithNegative : ParameterInfo.Create("The command to bind.");
			}, new Dictionary<string, Func<int, List<string>>> { 
			{
				"keys",
				(int index) => ParameterInfo.KeyCodesWithNegative
			} });
			new ConsoleCommand("unbind", "[keycode/tag] [amount = 0] [silent] - Clears binds from a key. Optional parameter can be used to specify amount of removed binds.", (ConsoleEvent)([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ConsoleEventArgs args) =>
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				if (args.Length >= 2)
				{
					KeyCode result;
					if (args[1] == "wheel")
					{
						string[] args2 = args.Args;
						result = Settings.MouseWheelBindKey;
						args2[1] = ((object)(KeyCode)(ref result)).ToString().ToLower();
					}
					string text = args.Args[1].ToLower();
					if (Enum.TryParse<KeyCode>(args.Args[1], ignoreCase: true, out result))
					{
						bool flag = args.Length > 3;
						int num = Parse.Int(args.Args, 2);
						if (num == 0)
						{
							num = int.MaxValue;
						}
						int num2 = Terminal.m_bindList.Count - 1;
						while (num2 >= 0 && num > 0)
						{
							if (!(Terminal.m_bindList[num2].Split(new char[1] { ' ' })[0].ToLower() != text))
							{
								if (!flag)
								{
									Print(args.Context, Terminal.m_bindList[num2]);
								}
								Terminal.m_bindList.RemoveAt(num2);
								num--;
							}
							num2--;
						}
					}
					else
					{
						bool flag2 = args.Length > 2;
						text = "tag=" + text;
						for (int num3 = Terminal.m_bindList.Count - 1; num3 >= 0; num3--)
						{
							if (Terminal.m_bindList[num3].Contains(text))
							{
								if (!flag2)
								{
									Print(args.Context, Terminal.m_bindList[num3]);
								}
								Terminal.m_bindList.RemoveAt(num3);
							}
						}
					}
					Terminal.updateBinds();
					BindManager.ToBeSaved = true;
				}
			}), false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			AutoComplete.Register("unbind", (int index) => index switch
			{
				0 => ParameterInfo.KeyCodes, 
				1 => ParameterInfo.Create("Amount of binds to remove from the key."), 
				_ => ParameterInfo.None, 
			});
			new ConsoleCommand("printbinds", "Prints all key binds.", (ConsoleEvent)([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ConsoleEventArgs args) =>
			{
				foreach (string bind in Terminal.m_bindList)
				{
					Print(args.Context, bind);
				}
			}), false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			AutoComplete.RegisterEmpty("printbinds");
		}

		[HarmonyPatch(typeof(Chat), "Update")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> DisableDefaultBindExecution(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Stfld, (object)AccessTools.Field(typeof(Chat), "m_wasFocused"), (string)null)
			}).Advance(4).Insert((CodeInstruction[])(object)new CodeInstruction[2]
			{
				new CodeInstruction(OpCodes.Pop, (object)null),
				new CodeInstruction(OpCodes.Ldc_I4_1, (object)null)
			})
				.InstructionEnumeration();
		}

		[HarmonyPatch(typeof(Chat), "Update")]
		[HarmonyPostfix]
		private static void ExecuteBestBinds(Chat __instance)
		{
			if (((TMP_InputField)((Terminal)__instance).m_input).isFocused || (Object.op_Implicit((Object)(object)Console.instance) && ((Component)((Terminal)Console.instance).m_chatWindow).gameObject.activeInHierarchy))
			{
				return;
			}
			string[] array = Terminal.m_binds.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (KeyValuePair<KeyCode, List<string>> kvp) => Input.GetKeyDown(kvp.Key)).SelectMany([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (KeyValuePair<KeyCode, List<string>> kvp) => kvp.Value).Where(Valid)
				.ToArray();
			if (array.Length != 0)
			{
				int max = ((IEnumerable<string>)array).Max((Func<string, int>)CountKeys);
				array = array.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (string cmd) => CountKeys(cmd) == max).ToArray();
				array = array.Select(CleanUp).ToArray();
				string[] array2 = array;
				foreach (string text in array2)
				{
					((Terminal)__instance).TryRunCommand(text, true, true);
				}
			}
		}

		public static int CountKeys(string command)
		{
			if (!command.Contains("keys="))
			{
				return 0;
			}
			string[] array = command.Split(new char[1] { ' ' }).First([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (string arg) => arg.StartsWith("keys=")).Split(new char[1] { '=' });
			if (array.Length < 2)
			{
				return 0;
			}
			return CountKeys(Parse.Split(array[1]));
		}

		public static int CountKeys(string[] keys)
		{
			KeyCode result;
			return keys.Count([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (string key) => !key.StartsWith("-", StringComparison.Ordinal) && Enum.TryParse<KeyCode>(key, ignoreCase: true, out result));
		}

		public static bool Valid(string command)
		{
			if (!command.Contains("keys="))
			{
				return true;
			}
			string[] array = command.Split(new char[1] { ' ' }).First([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (string arg) => arg.StartsWith("keys=")).Split(new char[1] { '=' });
			if (array.Length < 2)
			{
				return true;
			}
			return Valid(Parse.Split(array[1]));
		}

		public static void SetMode(string mode)
		{
			Mode = mode;
		}

		public static bool Valid(string[] keys)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			bool flag2 = false;
			Player localPlayer = Player.m_localPlayer;
			bool flag3 = localPlayer != null && ((Character)localPlayer).InPlaceMode();
			foreach (string text in keys)
			{
				KeyCode result2;
				if (text.StartsWith("-"))
				{
					string text2 = text.Substring(1);
					if (Enum.TryParse<KeyCode>(text2, ignoreCase: true, out KeyCode result))
					{
						if (Input.GetKey(result))
						{
							return false;
						}
					}
					else if (text2 == "build")
					{
						if (flag3)
						{
							return false;
						}
					}
					else if (text2 == Mode)
					{
						return false;
					}
				}
				else if (Enum.TryParse<KeyCode>(text, ignoreCase: true, out result2))
				{
					if (!Input.GetKey(result2))
					{
						return false;
					}
				}
				else if (text == "build")
				{
					if (!flag3)
					{
						return false;
					}
				}
				else
				{
					flag = true;
					if (text == Mode)
					{
						flag2 = true;
					}
				}
			}
			if (flag && !flag2)
			{
				return false;
			}
			return true;
		}

		public static string CleanUp(string command)
		{
			command = string.Join(" ", from arg in command.Split(new char[1] { ' ' })
				where !arg.StartsWith("tag=", StringComparison.OrdinalIgnoreCase)
				select arg);
			if (command.Split(new char[1] { ' ' }).Count([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (string arg) => arg.StartsWith("keys=", StringComparison.OrdinalIgnoreCase)) < 2)
			{
				command = string.Join(" ", from arg in command.Split(new char[1] { ' ' })
					where !arg.StartsWith("keys=", StringComparison.OrdinalIgnoreCase)
					select arg);
			}
			return command;
		}
	}
	[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
	[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
	public class BroadcastCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static readonly <>c <>9 = new <>c();

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static ConsoleEvent <>9__2_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__2_1;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__2_2;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__2_3;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__2_4;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__2_5;

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal void <.ctor>b__2_0(ConsoleEventArgs args)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				Helper.ArgsCheck(args, 2, "Missing the center/side parameter.");
				Helper.ArgsCheck(args, 3, "Missing the message");
				MessageType val = (MessageType)2;
				if (args[1] == "side")
				{
					val = (MessageType)1;
				}
				string text = string.Join(" ", args.Args.Skip(2));
				MessageHud.instance.MessageAll(val, text);
			}

			internal List<string> <.ctor>b__2_1(int index)
			{
				if (index == 0)
				{
					return Types;
				}
				return Modifiers;
			}

			internal List<string> <.ctor>b__2_2(int index)
			{
				return ParameterInfo.Create("Bolds the text.");
			}

			internal List<string> <.ctor>b__2_3(int index)
			{
				return ParameterInfo.Create("Italics the text.");
			}

			internal List<string> <.ctor>b__2_4(int index)
			{
				return ParameterInfo.Colors;
			}

			internal List<string> <.ctor>b__2_5(int index)
			{
				return ParameterInfo.Create("Size in pixels.");
			}
		}

		private static readonly List<string> Types = new List<string> { "center", "side" };

		private static readonly List<string> Modifiers = new List<string> { "<b", "<color", "<i", "<size" };

		public BroadcastCommand()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			object obj = <>c.<>9__2_0;
			if (obj == null)
			{
				ConsoleEvent val = [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ConsoleEventArgs args) =>
				{
					//IL_0019: Unknown result type (might be due to invalid IL or missing references)
					//IL_004b: Unknown result type (might be due to invalid IL or missing references)
					//IL_002e: Unknown result type (might be due to invalid IL or missing references)
					Helper.ArgsCheck(args, 2, "Missing the center/side parameter.");
					Helper.ArgsCheck(args, 3, "Missing the message");
					MessageType val2 = (MessageType)2;
					if (args[1] == "side")
					{
						val2 = (MessageType)1;
					}
					string text = string.Join(" ", args.Args.Skip(2));
					MessageHud.instance.MessageAll(val2, text);
				};
				<>c.<>9__2_0 = val;
				obj = (object)val;
			}
			Helper.Command("broadcast", "[center/side] [message] - Broadcasts a message.", (ConsoleEvent)obj);
			AutoComplete.Register("broadcast", (int index) => (index == 0) ? Types : Modifiers, new Dictionary<string, Func<int, List<string>>>
			{
				{
					"<b",
					(int index) => ParameterInfo.Create("Bolds the text.")
				},
				{
					"<i",
					(int index) => ParameterInfo.Create("Italics the text.")
				},
				{
					"<color",
					(int index) => ParameterInfo.Colors
				},
				{
					"<size",
					(int index) => ParameterInfo.Create("Size in pixels.")
				}
			});
		}
	}
	public class CalmCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__0_0;

			public static ConsoleEvent <>9__0_1;

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
			internal List<string> <.ctor>b__0_0(int index)
			{
				if (index == 0)
				{
					return ParameterInfo.Create("Radius", "a positive integer");
				}
				return ParameterInfo.None;
			}

			internal void <.ctor>b__0_1(ConsoleEventArgs args)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				Vector3 position = ((Component)Helper.GetPlayer()).transform.position;
				float num = args.TryParameterFloat(1, 20f);
				int num2 = 0;
				foreach (BaseAI instance in BaseAI.Instances)
				{
					if (Vector3.Distance(position, ((Component)instance).transform.position) <= num && (instance.IsAlerted() || instance.IsAggravated()))
					{
						instance.m_nview.ClaimOwnership();
						instance.SetAggravated(false, (AggravatedReason)1);
						instance.SetAlerted(false);
						num2++;
					}
				}
				Helper.AddMessage(args.Context, $"Calmed {num2} creatures.");
			}
		}

		public CalmCommand()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			AutoComplete.Register("calm", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Create("Radius", "a positive integer") : ParameterInfo.None);
			object obj = <>c.<>9__0_1;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					//IL_000a: Unknown result type (might be due to invalid IL or missing references)
					//IL_000f: Unknown result type (might be due to invalid IL or missing references)
					//IL_0035: Unknown result type (might be due to invalid IL or missing references)
					//IL_003d: Unknown result type (might be due to invalid IL or missing references)
					Vector3 position = ((Component)Helper.GetPlayer()).transform.position;
					float num = args.TryParameterFloat(1, 20f);
					int num2 = 0;
					foreach (BaseAI instance in BaseAI.Instances)
					{
						if (Vector3.Distance(position, ((Component)instance).transform.position) <= num && (instance.IsAlerted() || instance.IsAggravated()))
						{
							instance.m_nview.ClaimOwnership();
							instance.SetAggravated(false, (AggravatedReason)1);
							instance.SetAlerted(false);
							num2++;
						}
					}
					Helper.AddMessage(args.Context, $"Calmed {num2} creatures.");
				};
				<>c.<>9__0_1 = val;
				obj = (object)val;
			}
			Helper.Command("calm", "[radius=20] - Calms creatures within given meters.", (ConsoleEvent)obj);
		}
	}
	public class ConfigCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__0_0;

			public static ConsoleEvent <>9__1_0;

			public static ConsoleOptionsFetcher <>9__1_1;

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
			internal List<string> <RegisterAutoComplete>b__0_0(int index)
			{
				if (index == 0)
				{
					return Settings.Options;
				}
				return ParameterInfo.Create("Value");
			}

			internal void <.ctor>b__1_0(ConsoleEventArgs args)
			{
				if (args.Length >= 2)
				{
					if (args.Length == 2)
					{
						Settings.UpdateValue(args.Context, args[1], "");
					}
					else
					{
						Settings.UpdateValue(args.Context, args[1], string.Join(" ", args.Args.Skip(2)));
					}
				}
			}

			internal List<string> <.ctor>b__1_1()
			{
				return Settings.Options;
			}
		}

		[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
		private void RegisterAutoComplete(string command)
		{
			AutoComplete.Register(command, [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? Settings.Options : ParameterInfo.Create("Value"));
		}

		public ConfigCommand()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			object obj = <>c.<>9__1_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					if (args.Length >= 2)
					{
						if (args.Length == 2)
						{
							Settings.UpdateValue(args.Context, args[1], "");
						}
						else
						{
							Settings.UpdateValue(args.Context, args[1], string.Join(" ", args.Args.Skip(2)));
						}
					}
				};
				<>c.<>9__1_0 = val;
				obj = (object)val;
			}
			object obj2 = <>c.<>9__1_1;
			if (obj2 == null)
			{
				ConsoleOptionsFetcher val2 = () => Settings.Options;
				<>c.<>9__1_1 = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("dev_config", "[key] [value] - Toggles or sets config value.", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)obj2, false);
			RegisterAutoComplete("dev_config");
		}
	}
	public static class DefaultAutoComplete
	{
		public static void Register()
		{
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Expected O, but got Unknown
			AutoComplete.RegisterEmpty("aggravate");
			AutoComplete.RegisterEmpty("challenge");
			AutoComplete.RegisterEmpty("cheers");
			AutoComplete.RegisterEmpty("clear");
			AutoComplete.Register("fov ", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Create("Amount", "a positive number") : ParameterInfo.None);
			AutoComplete.RegisterEmpty("hidebetatext");
			AutoComplete.Register("help ", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => index switch
			{
				0 => ParameterInfo.Create("Page", "number"), 
				1 => ParameterInfo.Create("Page size", "a positive integer (default is 5)"), 
				_ => ParameterInfo.None, 
			});
			AutoComplete.RegisterEmpty("info");
			AutoComplete.Register("lodbias", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Create("Amount", "a positive number") : ParameterInfo.None);
			AutoComplete.RegisterEmpty("nonono");
			AutoComplete.RegisterEmpty("opterrain");
			AutoComplete.RegisterEmpty("point");
			AutoComplete.RegisterEmpty("ping");
			ConsoleOptionsFetcher originalFetcher = Terminal.commands["raiseskill"].m_tabOptionsFetcher;
			Terminal.commands["raiseskill"].m_tabOptionsFetcher = new ConsoleOptionsFetcher(newFetcher);
			AutoComplete.Register("raiseskill", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) =>
			{
				ConsoleOptionsFetcher tabOptionsFetcher = Terminal.commands["raiseskill"].m_tabOptionsFetcher;
				return index switch
				{
					0 => tabOptionsFetcher.Invoke(), 
					1 => ParameterInfo.Create("Amount of skill levels gained or lost (if negative)."), 
					_ => ParameterInfo.None, 
				};
			});
			AutoComplete.RegisterEmpty("resetbinds");
			AutoComplete.RegisterEmpty("resetsharedmap");
			AutoComplete.RegisterEmpty("resetspawn");
			AutoComplete.RegisterEmpty("respawn");
			AutoComplete.Register("s", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => ParameterInfo.Create("Message"));
			AutoComplete.Register("say", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => ParameterInfo.Create("Message"));
			AutoComplete.RegisterEmpty("restartparty");
			AutoComplete.RegisterEmpty("sit");
			AutoComplete.RegisterEmpty("thumbsup");
			AutoComplete.RegisterEmpty("tutorialreset");
			AutoComplete.RegisterEmpty("tutorialtoggle");
			AutoComplete.RegisterEmpty("wave");
			AutoComplete.Register("W", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.PlayerNames : ParameterInfo.Create("Message"));
			AutoComplete.RegisterAdmin("ban");
			AutoComplete.RegisterEmpty("banned");
			AutoComplete.RegisterAdmin("kick");
			AutoComplete.RegisterEmpty("save");
			AutoComplete.RegisterAdmin("unban");
			AutoComplete.Register("beard", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Beards : ParameterInfo.None);
			AutoComplete.RegisterEmpty("clearstatus");
			AutoComplete.RegisterEmpty("dpsdebug");
			AutoComplete.RegisterEmpty("exploremap");
			AutoComplete.Register("ffsmooth", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Create("0 = normal, 1 = add smooth movement") : ParameterInfo.None);
			AutoComplete.RegisterEmpty("fly");
			AutoComplete.RegisterEmpty("freefly");
			AutoComplete.Register("forcedelete", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => index switch
			{
				0 => ParameterInfo.Create("Radius", "in meters (from 0.0 to 50.0, default is 5.0)."), 
				1 => ParameterInfo.ObjectIds, 
				_ => ParameterInfo.None, 
			});
			AutoComplete.RegisterEmpty("gc");
			AutoComplete.RegisterEmpty("ghost");
			AutoComplete.RegisterEmpty("god");
			AutoComplete.Register("hair", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Hairs : ParameterInfo.None);
			AutoComplete.RegisterEmpty("heal");
			AutoComplete.Register("itemset", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => index switch
			{
				0 => Terminal.commands["itemset"].m_tabOptionsFetcher.Invoke(), 
				1 => new List<string> { "keep", "clear" }, 
				_ => ParameterInfo.None, 
			});
			AutoComplete.RegisterEmpty("killall");
			AutoComplete.RegisterEmpty("killenemies");
			AutoComplete.RegisterEmpty("killtame");
			AutoComplete.RegisterEmpty("listkeys");
			AutoComplete.Register("location", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => index switch
			{
				0 => ParameterInfo.LocationIds, 
				1 => new List<string> { "SAVE" }, 
				_ => ParameterInfo.None, 
			});
			AutoComplete.Register("maxfps", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Create("Amount", "a positive integer") : ParameterInfo.None);
			AutoComplete.Register("model", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Create("<color=yellow>0</color> = male, <color=yellow>1</color> = female") : ParameterInfo.None);
			AutoComplete.RegisterEmpty("nocost");
			AutoComplete.RegisterEmpty("noportals");
			AutoComplete.Register("players", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Create("Amount", "a positive integer (0 disables the override)") : ParameterInfo.None);
			AutoComplete.RegisterEmpty("printcreatures");
			AutoComplete.RegisterEmpty("printseeds");
			AutoComplete.RegisterEmpty("printlocations");
			AutoComplete.RegisterEmpty("puke");
			AutoComplete.RegisterEmpty("removebirds");
			AutoComplete.RegisterEmpty("removedrops");
			AutoComplete.RegisterEmpty("removefish");
			AutoComplete.Register("recall ", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.PlayerNames : ParameterInfo.None);
			AutoComplete.RegisterEmpty("resetcharacter");
			AutoComplete.RegisterEmpty("resetenv");
			AutoComplete.RegisterEmpty("resetwind");
			AutoComplete.Register("removekey", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.GlobalKeys : ParameterInfo.None);
			AutoComplete.Register("setkey", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.GlobalKeys : ParameterInfo.None);
			AutoComplete.RegisterDefault("setpower");
			AutoComplete.Register("spawn", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) =>
			{
				switch (index)
				{
				case 0:
					return ParameterInfo.ObjectIds;
				case 1:
					if (Settings.DisableParameterWarnings)
					{
						return ParameterInfo.Create("Amount", "a positive integer (default 1)");
					}
					return ParameterInfo.Create("Amount", "a positive integer (default 1), <color=yellow>WARNING</color>: Very high values (100+) may crash the game!, <color=yellow>WARNING</color>: Some objects can't be removed after spawning!");
				case 2:
					if (Settings.DisableParameterWarnings)
					{
						return ParameterInfo.Create("Level", "a positive integer (default 1)");
					}
					return ParameterInfo.Create("Level", "a positive integer (default 1), <color=yellow>WARNING</color>: High values (5+) may crash the server when the creature is killed!, <color=yellow>WARNING</color>: Some objects can't be removed after spawning!");
				default:
					if (index == 2)
					{
						return ParameterInfo.Create("<color=yellow>p</color> to automatically pick up items. <color=yellow>e</color> to automatically equip items.");
					}
					return ParameterInfo.None;
				}
			});
			AutoComplete.RegisterEmpty("tame");
			AutoComplete.Register("test", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? new List<string> { "oldcomfort" } : ParameterInfo.None);
			AutoComplete.RegisterEmpty("time");
			AutoComplete.Register("timescale", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => index switch
			{
				0 => ParameterInfo.Create("Multiplier", "sets how fast the time goes (from 0.0 to 3.0). Value 0 can be used to pause the game."), 
				1 => ParameterInfo.Create("Transition duration", "causes the change to be applied gradually over time (seconds). Default value 0 applies the change instantly."), 
				_ => ParameterInfo.None, 
			});
			AutoComplete.Register("tod", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Create("Time", "overrides the time of the day (from 0.0 to 1.0, with 0.5 being the mid day). Value -1 removes the override.") : ParameterInfo.None);
			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
			List<string> newFetcher()
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				List<string> list = originalFetcher.Invoke();
				SkillType val = (SkillType)999;
				if (!list.Contains(((object)(SkillType)(ref val)).ToString()))
				{
					val = (SkillType)999;
					list.Add(((object)(SkillType)(ref val)).ToString());
				}
				return list;
			}
		}
	}
	[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
	[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
	public class DevcommandsCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static readonly <>c <>9 = new <>c();

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static ConsoleEvent <>9__3_0;

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal void <.ctor>b__3_0(ConsoleEventArgs args)
			{
				if (Terminal.m_cheat)
				{
					Set(args.Context, value: false);
					return;
				}
				if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer())
				{
					Toggle(args.Context);
					return;
				}
				args.Context.AddString("Authenticating for devcommands...");
				Admin.ManualCheck();
			}
		}

		public static void Toggle(Terminal terminal)
		{
			bool value = !Terminal.m_cheat;
			if (terminal != null)
			{
				terminal.AddString("Devcommands: " + value);
			}
			Gogan.LogEvent("Cheat", "CheatsEnabled", value.ToString(), 0L);
			Set(value);
		}

		public static void Set(Terminal terminal, bool value)
		{
			if (terminal != null)
			{
				terminal.AddString("Devcommands: " + value);
			}
			Gogan.LogEvent("Cheat", "CheatsEnabled", value.ToString(), 0L);
			Set(value);
		}

		public static void Set(bool value)
		{
			if (Terminal.m_cheat == value)
			{
				return;
			}
			if (Settings.AutoTod != "" && !value)
			{
				((Terminal)Console.instance).TryRunCommand("tod -1", false, false);
			}
			if (Settings.AutoEnv != "" && !value)
			{
				((Terminal)Console.instance).TryRunCommand("resetenv", false, false);
			}
			Terminal.m_cheat = value;
			if (Settings.AutoTod != "" && value)
			{
				((Terminal)Console.instance).TryRunCommand("tod " + Settings.AutoTod, false, false);
			}
			if (Settings.AutoEnv != "" && value)
			{
				((Terminal)Console.instance).TryRunCommand("env " + Settings.AutoEnv, false, false);
			}
			((Terminal)Console.instance).updateCommandList();
			((Terminal)Chat.instance).updateCommandList();
			Player localPlayer = Player.m_localPlayer;
			if (Settings.AutoDebugMode)
			{
				Player.m_debugMode = value;
			}
			if (Object.op_Implicit((Object)(object)localPlayer))
			{
				if (Settings.AutoGodMode)
				{
					localPlayer.SetGodMode(value);
				}
				if (Settings.AutoGhostMode)
				{
					localPlayer.SetGhostMode(value);
				}
				if (Settings.AutoFly)
				{
					localPlayer.m_debugFly = value;
					((Character)localPlayer).m_nview.GetZDO().Set("DebugFly", value);
				}
				if (Settings.AutoNoCost)
				{
					localPlayer.m_noPlacementCost = value;
				}
			}
			if (value && Settings.AutoExecDevOn != "")
			{
				((Terminal)Console.instance).TryRunCommand(Settings.AutoExecDevOn, false, false);
			}
			if (!value && Settings.AutoExecDevOff != "")
			{
				((Terminal)Console.instance).TryRunCommand(Settings.AutoExecDevOff, false, false);
			}
		}

		public DevcommandsCommand()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			object obj = <>c.<>9__3_0;
			if (obj == null)
			{
				ConsoleEvent val = [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ConsoleEventArgs args) =>
				{
					if (Terminal.m_cheat)
					{
						Set(args.Context, value: false);
					}
					else if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer())
					{
						Toggle(args.Context);
					}
					else
					{
						args.Context.AddString("Authenticating for devcommands...");
						Admin.ManualCheck();
					}
				};
				<>c.<>9__3_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("devcommands", "Toggles cheats", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			AutoComplete.RegisterEmpty("devcommands");
		}
	}
	public class DevCommandsAdmin : DefaultAdmin
	{
		protected override void OnSuccess()
		{
			base.OnSuccess();
			DevcommandsCommand.Set(value: true);
			((Terminal)Console.instance).AddString("Authorized to use devcommands.");
		}

		protected override void OnFail()
		{
			base.OnFail();
			DevcommandsCommand.Set(value: false);
			((Terminal)Console.instance).AddString("Unauthorized to use devcommands.");
		}

		public override void AutomaticCheck()
		{
			if (Settings.AutoDevcommands)
			{
				base.AutomaticCheck();
			}
		}

		public override void Reset()
		{
			base.Reset();
			DevcommandsCommand.Set(value: false);
		}
	}
	[HarmonyPatch(typeof(Terminal), "IsCheatsEnabled")]
	public class IsCheatsEnabledWithoutServerCheck
	{
		private static void Postfix(ref bool __result)
		{
			int num;
			if (!Terminal.m_cheat)
			{
				ZNet instance = ZNet.instance;
				num = ((instance != null && instance.IsDedicated()) ? 1 : 0);
			}
			else
			{
				num = 1;
			}
			__result = (byte)num != 0;
		}
	}
	[HarmonyPatch(typeof(ConsoleCommand), "IsValid")]
	public class IsValidWithoutServerCheck
	{
		private static void Postfix(ref bool __result)
		{
			int num;
			if (!__result && !Terminal.m_cheat)
			{
				ZNet instance = ZNet.instance;
				num = ((instance != null && instance.IsDedicated()) ? 1 : 0);
			}
			else
			{
				num = 1;
			}
			__result = (byte)num != 0;
		}
	}
	[HarmonyPatch(typeof(Terminal), "Awake")]
	public class AutoCompleteSecrets
	{
		private static void Postfix(ref bool ___m_autoCompleteSecrets)
		{
			___m_autoCompleteSecrets = true;
		}
	}
	public class EnvCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__0_0;

			public static ConsoleOptionsFetcher <>9__0_1;

			internal void <.ctor>b__0_0(ConsoleEventArgs args)
			{
				<>c__DisplayClass0_0 CS$<>8__locals0 = new <>c__DisplayClass0_0();
				EnvMan instance = EnvMan.instance;
				if (!Object.op_Implicit((Object)(object)instance))
				{
					return;
				}
				if (args.Length < 2)
				{
					Helper.AddMessage(args.Context, $"Environment: {instance.GetCurrentEnvironment()}.");
					return;
				}
				CS$<>8__locals0.text = string.Join(" ", args.Args, 1, args.Args.Length - 1);
				if (!EnvMan.instance.m_environments.Any((EnvSetup env) => env.m_name == CS$<>8__locals0.text))
				{
					CS$<>8__locals0.text = CS$<>8__locals0.text.Replace("_", " ");
				}
				Helper.AddMessage(args.Context, "Setting debug environment: " + CS$<>8__locals0.text);
				instance.m_debugEnv = CS$<>8__locals0.text;
			}

			internal List<string> <.ctor>b__0_1()
			{
				return ParameterInfo.Environments;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass0_0
		{
			public string text;

			internal bool <.ctor>b__2(EnvSetup env)
			{
				return env.m_name == text;
			}
		}

		public EnvCommand()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					EnvMan instance = EnvMan.instance;
					if (Object.op_Implicit((Object)(object)instance))
					{
						if (args.Length < 2)
						{
							Helper.AddMessage(args.Context, $"Environment: {instance.GetCurrentEnvironment()}.");
						}
						else
						{
							string text = string.Join(" ", args.Args, 1, args.Args.Length - 1);
							if (!EnvMan.instance.m_environments.Any((EnvSetup env) => env.m_name == text))
							{
								text = text.Replace("_", " ");
							}
							Helper.AddMessage(args.Context, "Setting debug environment: " + text);
							instance.m_debugEnv = text;
						}
					}
				};
				<>c.<>9__0_0 = val;
				obj = (object)val;
			}
			object obj2 = <>c.<>9__0_1;
			if (obj2 == null)
			{
				ConsoleOptionsFetcher val2 = () => ParameterInfo.Environments;
				<>c.<>9__0_1 = val2;
				obj2 = (object)val2;
			}
			Helper.Command("env", "[value] - Prints or overrides the environment.", (ConsoleEvent)obj, (ConsoleOptionsFetcher)obj2);
			AutoComplete.RegisterDefault("env");
		}
	}
	public class FindCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<LocationInstance, Vector3> <>9__0_4;

			public static Func<ZDO, Vector3> <>9__0_6;

			public static ConsoleOptionsFetcher <>9__0_1;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__0_2;

			internal Vector3 <.ctor>b__0_4(LocationInstance l)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return l.m_position;
			}

			internal Vector3 <.ctor>b__0_6(ZDO zdo)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return zdo.GetPosition();
			}

			internal List<string> <.ctor>b__0_1()
			{
				return ParameterInfo.Ids;
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
			internal List<string> <.ctor>b__0_2(int index)
			{
				return index switch
				{
					0 => ParameterInfo.Ids, 
					1 => ParameterInfo.Create("Max amount", "a positive integer (default 10)"), 
					2 => ParameterInfo.Create("X coordinate", "if not specified, the current position is used"), 
					3 => ParameterInfo.Create("Z coordinate", "if not specified, the current position is used"), 
					_ => ParameterInfo.None, 
				};
			}
		}

		public FindCommand()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			ConsoleCommand defaultCommand = Terminal.commands["find"];
			string description = defaultCommand.Description;
			ConsoleEvent val = delegate(ConsoleEventArgs args)
			{
				//IL_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
				Helper.ArgsCheck(args, 2, "Missing the search term.");
				if (!Object.op_Implicit((Object)(object)ZNet.m_instance) || (ZNet.instance.IsServer() && !ZNet.instance.IsDedicated()))
				{
					defaultCommand.RunAction(args);
				}
				else
				{
					if (args.Length < 3)
					{
						args.Args = args.Args.Append("10").ToArray();
					}
					string[] args2 = Helper.AddPlayerPosXZY(args.Args, 3);
					if (!ZNet.instance.IsServer())
					{
						ServerExecution.Send((IEnumerable<string>)args2);
					}
					else
					{
						int prefab = StringExtensionMethods.GetStableHashCode(args[1]);
						Vector3 pos = Parse.VectorXZY(string.Join(",", args.Args.Skip(3)));
						List<Vector3> list = (from l in ZoneSystem.instance.GetLocationList()
							where l.m_location != null && l.m_location.m_prefabName == args[1]
							select l.m_position).ToList();
						IEnumerable<ZDO> source = ZDOMan.instance.m_objectsByID.Values.Where((ZDO zdo) => zdo.IsValid() && zdo.GetPrefab() == prefab);
						list.AddRange(source.Select((ZDO zdo) => zdo.GetPosition()));
						list.Sort((Vector3 a, Vector3 b) => Vector3.Distance(a, pos).CompareTo(Vector3.Distance(b, pos)));
						int count = list.Count;
						list = list.Take(Parse.Int(args.Args, 2, 10)).ToList();
						List<string> values = list.Select((Vector3 p) => Format(pos, p)).ToList();
						args.Context.AddString($"Found {count} of {args[1]}. Showing {list.Count} closest:");
						args.Context.AddString(string.Join("\n", values));
						if (RedirectOutput.Target != null)
						{
							RedirectOutput.Target.Invoke(ServerExecution.RPC_Pins, new object[1] { string.Join("|", list.Select(Helper.PrintVectorXZY)) });
						}
					}
				}
			};
			object obj = <>c.<>9__0_1;
			if (obj == null)
			{
				ConsoleOptionsFetcher val2 = () => ParameterInfo.Ids;
				<>c.<>9__0_1 = val2;
				obj = (object)val2;
			}
			Helper.Command("find", description, val, (ConsoleOptionsFetcher)obj);
			AutoComplete.Register("find", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => index switch
			{
				0 => ParameterInfo.Ids, 
				1 => ParameterInfo.Create("Max amount", "a positive integer (default 10)"), 
				2 => ParameterInfo.Create("X coordinate", "if not specified, the current position is used"), 
				3 => ParameterInfo.Create("Z coordinate", "if not specified, the current position is used"), 
				_ => ParameterInfo.None, 
			});
		}

		[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
		private static string Format(Vector3 pos, Vector3 p)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			float num = Vector3.Distance(pos, p);
			return string.Format(Settings.FindFormat.Replace("{pos_x", "{0").Replace("{pos_y", "{1").Replace("{pos_z", "{2")
				.Replace("{distance", "{3"), p.x, p.y, p.z, num);
		}
	}
	public class GotoCommand
	{
		private Vector3? LastPosition;

		private Quaternion? LastRotation;

		[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
		private void ParseArgs(ConsoleEventArgs args, Player player, ref Vector3 pos, ref Quaternion rot)
		{
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			if (args.Length < 2)
			{
				pos.y = WorldGenerator.instance.GetHeight(pos.x, pos.z);
				return;
			}
			if (args.Length == 2 && args[1] == "last")
			{
				if (!LastPosition.HasValue)
				{
					throw new InvalidOperationException("No last position");
				}
				pos = (Vector3)(((??)LastPosition) ?? pos);
				rot = (Quaternion)(((??)LastRotation) ?? rot);
				return;
			}
			string[] array = Parse.Split(args[1]);
			if (args.Length > 2)
			{
				array = args.Args.Skip(1).ToArray();
			}
			if (Parse.TryFloat(array[0], out var value))
			{
				if (array.Length < 2)
				{
					pos.y = value;
					return;
				}
				Vector3 val = Parse.VectorXZY(array);
				float num = (((Character)player).IsDebugFlying() ? ((Component)player).transform.position.y : WorldGenerator.instance.GetHeight(val.x, val.z));
				pos = Parse.VectorXZY(array, new Vector3(pos.x, num, pos.z));
			}
			else
			{
				PlayerInfo val2 = Helper.FindPlayer(string.Join(" ", args.Args.Skip(1)));
				pos = val2.m_position;
			}
		}

		public GotoCommand()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			AutoComplete.Register("goto", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index, int subIndex) =>
			{
				if (index == 0 && subIndex == 0)
				{
					return ParameterInfo.PublicPlayerNames;
				}
				return (index == 0) ? ParameterInfo.XZY("Coordinates", subIndex) : ParameterInfo.XZY("Coordinates", index);
			});
			Helper.Command("goto", "[x,z,y or altitude or last or player or no parameter] - Teleports to the coordinates. If y is not given, teleports to the ground level.", (ConsoleEvent)delegate(ConsoleEventArgs args)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				//IL_0081: Unknown result type (might be due to invalid IL or missing references)
				Player player = Helper.GetPlayer();
				Vector3 pos = ((Component)player).transform.position;
				Quaternion rot = ((Component)player).transform.rotation;
				ParseArgs(args, player, ref pos, ref rot);
				LastPosition = ((Component)player).transform.position;
				LastRotation = ((Component)player).transform.rotation;
				((Character)player).TeleportTo(pos, rot, true);
				Helper.AddMessage(args.Context, $"Teleported to (X,Z,Y): {pos.x}, {pos.z}, {pos.y}.");
			}, (ConsoleOptionsFetcher)null);
		}
	}
	[HarmonyPatch(typeof(Player), "TeleportTo")]
	public class FasterTeleport1
	{
		[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
		private static void Postfix(Player __instance, bool __result)
		{
			if (Settings.DebugModeFastTeleport && __result && Player.m_debugMode)
			{
				__instance.m_teleportTimer = 15f;
			}
		}
	}
	[HarmonyPatch(typeof(Player), "UpdateTeleport")]
	public class FasterTeleport2
	{
		[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
		private static void Postfix(Player __instance)
		{
			if (Settings.DebugModeFastTeleport && Player.m_debugMode)
			{
				__instance.m_teleportCooldown = Mathf.Max(__instance.m_teleportCooldown, 1.5f);
			}
		}
	}
	public class HUDCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__0_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__0_1;

			internal void <.ctor>b__0_0(ConsoleEventArgs args)
			{
				if (!Object.op_Implicit((Object)(object)Hud.m_instance))
				{
					Helper.AddMessage(args.Context, "Error: No HUD instance.");
					return;
				}
				if (args.Length >= 2)
				{
					Hud.m_instance.m_userHidden = args[1] != "1";
				}
				else
				{
					Hud.m_instance.m_userHidden = !Hud.m_instance.m_userHidden;
				}
				string text = (Hud.m_instance.m_userHidden ? "disabled" : "enabled");
				Helper.AddMessage(args.Context, "Hud " + text + ".");
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
			internal List<string> <.ctor>b__0_1(int index)
			{
				if (index == 0)
				{
					return ParameterInfo.Create("1 = enable, 0 = disable, no value = toggle");
				}
				return ParameterInfo.None;
			}
		}

		public HUDCommand()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					if (!Object.op_Implicit((Object)(object)Hud.m_instance))
					{
						Helper.AddMessage(args.Context, "Error: No HUD instance.");
					}
					else
					{
						if (args.Length >= 2)
						{
							Hud.m_instance.m_userHidden = args[1] != "1";
						}
						else
						{
							Hud.m_instance.m_userHidden = !Hud.m_instance.m_userHidden;
						}
						string text = (Hud.m_instance.m_userHidden ? "disabled" : "enabled");
						Helper.AddMessage(args.Context, "Hud " + text + ".");
					}
				};
				<>c.<>9__0_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("hud", "[value] -  Toggles or sets the HUD visibility.", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			AutoComplete.Register("hud", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index == 0) ? ParameterInfo.Create("1 = enable, 0 = disable, no value = toggle") : ParameterInfo.None);
		}
	}
	[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
	[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
	public class InventoryCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static readonly <>c <>9 = new <>c();

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<ItemData, bool> <>9__5_3;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<ItemData, bool> <>9__5_4;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static Func<ItemData, bool> <>9__5_5;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static ConsoleEvent <>9__5_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static ConsoleOptionsFetcher <>9__5_1;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__5_2;

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal void <.ctor>b__5_0(ConsoleEventArgs args)
			{
				<>c__DisplayClass5_0 CS$<>8__locals0 = new <>c__DisplayClass5_0();
				Helper.ArgsCheck(args, 2, "Missing clear, level, refill, repair or upgrade.");
				CS$<>8__locals0.amount = Parse.IntNull(args.Args, 2);
				string text = Parse.String(args.Args, 3, "all");
				if (!CS$<>8__locals0.amount.HasValue)
				{
					text = Parse.String(args.Args, 2, "all");
					CS$<>8__locals0.amount = Parse.IntNull(args.Args, 3);
				}
				Player player = Helper.GetPlayer();
				Inventory inventory = ((Humanoid)player).GetInventory();
				List<ItemData> list = inventory.GetAllItems();
				if (text == "hand" || text == "worn")
				{
					list = inventory.GetEquippedItems();
				}
				if (text == "hand")
				{
					list = list.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ItemData item) => HandTypes.Contains(item.m_shared.m_itemType)).ToList();
				}
				switch (args[1])
				{
				case "repair":
				{
					ItemData[] array5 = list.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ItemData item) => item.m_durability < item.GetMaxDurability()).ToArray();
					ItemData[] array2 = array5;
					foreach (ItemData obj3 in array2)
					{
						obj3.m_durability = obj3.GetMaxDurability();
					}
					Helper.AddMessage(args.Context, $"{array5.Length} items repaired.");
					break;
				}
				case "refill":
				{
					ItemData[] array3 = list.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ItemData item) => item.m_stack < item.m_shared.m_maxStackSize).ToArray();
					ItemData[] array2 = array3;
					foreach (ItemData obj in array2)
					{
						obj.m_stack = obj.m_shared.m_maxStackSize;
					}
					Helper.AddMessage(args.Context, $"{array3.Length} items filled.");
					break;
				}
				case "clear":
					((Humanoid)player).UnequipAllItems();
					Helper.AddMessage(args.Context, $"{list.Count} items cleared.");
					inventory.RemoveAll();
					break;
				case "level":
				{
					if (!CS$<>8__locals0.amount.HasValue)
					{
						throw new InvalidOperationException("Missing the level.");
					}
					ItemData[] array4 = list.Where(Valid).ToArray();
					ItemData[] array2 = array4;
					foreach (ItemData obj2 in array2)
					{
						obj2.m_quality = CS$<>8__locals0.amount.Value;
						obj2.m_durability = obj2.GetMaxDurability();
					}
					Helper.AddMessage(args.Context, $"{array4.Length} items upgraded.");
					break;
				}
				case "upgrade":
				{
					ItemData[] array = list.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ItemData item) => Valid(item) && (CS$<>8__locals0.amount.HasValue || item.m_quality != item.m_shared.m_maxQuality)).ToArray();
					ItemData[] array2 = array;
					foreach (ItemData val in array2)
					{
						if (CS$<>8__locals0.amount.HasValue)
						{
							val.m_quality = CS$<>8__locals0.amount.Value;
						}
						else
						{
							val.m_quality = val.m_shared.m_maxQuality;
						}
						val.m_durability = val.GetMaxDurability();
					}
					Helper.AddMessage(args.Context, $"{array.Length} items upgraded.");
					break;
				}
				default:
					throw new InvalidOperationException("Invalid operation. Use level, repair or upgrade.");
				}
				inventory.Changed();
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <.ctor>b__5_3(ItemData item)
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return HandTypes.Contains(item.m_shared.m_itemType);
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <.ctor>b__5_4(ItemData item)
			{
				return item.m_durability < item.GetMaxDurability();
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <.ctor>b__5_5(ItemData item)
			{
				return item.m_stack < item.m_shared.m_maxStackSize;
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal List<string> <.ctor>b__5_1()
			{
				return Operations;
			}

			internal List<string> <.ctor>b__5_2(int index)
			{
				return index switch
				{
					0 => Operations, 
					1 => Targets, 
					2 => ParameterInfo.Create("Amount", "How many levels to upgrade."), 
					_ => ParameterInfo.None, 
				};
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass5_0
		{
			public int? amount;

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal bool <.ctor>b__6(ItemData item)
			{
				if (Valid(item))
				{
					if (!amount.HasValue)
					{
						return item.m_quality != item.m_shared.m_maxQuality;
					}
					return true;
				}
				return false;
			}
		}

		private static readonly List<string> Operations = new List<string> { "clear", "level", "refill", "repair", "upgrade" };

		private static readonly List<string> Targets = new List<string> { "all", "hand", "worn" };

		private static readonly HashSet<ItemType> HandTypes = new HashSet<ItemType>
		{
			(ItemType)4,
			(ItemType)3,
			(ItemType)5,
			(ItemType)15,
			(ItemType)19,
			(ItemType)14
		};

		private static readonly HashSet<ItemType> ArmorTypes = new HashSet<ItemType>
		{
			(ItemType)7,
			(ItemType)12,
			(ItemType)6,
			(ItemType)11,
			(ItemType)17
		};

		private static bool Valid(ItemData item)
		{
			//IL_0019: 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)
			if (item.m_shared.m_maxQuality <= 1 && !HandTypes.Contains(item.m_shared.m_itemType))
			{
				return ArmorTypes.Contains(item.m_shared.m_itemType);
			}
			return true;
		}

		public InventoryCommand()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			object obj = <>c.<>9__5_0;
			if (obj == null)
			{
				ConsoleEvent val = [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ConsoleEventArgs args) =>
				{
					Helper.ArgsCheck(args, 2, "Missing clear, level, refill, repair or upgrade.");
					int? amount = Parse.IntNull(args.Args, 2);
					string text = Parse.String(args.Args, 3, "all");
					if (!amount.HasValue)
					{
						text = Parse.String(args.Args, 2, "all");
						amount = Parse.IntNull(args.Args, 3);
					}
					Player player = Helper.GetPlayer();
					Inventory inventory = ((Humanoid)player).GetInventory();
					List<ItemData> list = inventory.GetAllItems();
					if (text == "hand" || text == "worn")
					{
						list = inventory.GetEquippedItems();
					}
					if (text == "hand")
					{
						list = list.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ItemData item) => HandTypes.Contains(item.m_shared.m_itemType)).ToList();
					}
					switch (args[1])
					{
					case "repair":
					{
						ItemData[] array5 = list.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ItemData item) => item.m_durability < item.GetMaxDurability()).ToArray();
						ItemData[] array2 = array5;
						foreach (ItemData obj5 in array2)
						{
							obj5.m_durability = obj5.GetMaxDurability();
						}
						Helper.AddMessage(args.Context, $"{array5.Length} items repaired.");
						break;
					}
					case "refill":
					{
						ItemData[] array3 = list.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ItemData item) => item.m_stack < item.m_shared.m_maxStackSize).ToArray();
						ItemData[] array2 = array3;
						foreach (ItemData obj3 in array2)
						{
							obj3.m_stack = obj3.m_shared.m_maxStackSize;
						}
						Helper.AddMessage(args.Context, $"{array3.Length} items filled.");
						break;
					}
					case "clear":
						((Humanoid)player).UnequipAllItems();
						Helper.AddMessage(args.Context, $"{list.Count} items cleared.");
						inventory.RemoveAll();
						break;
					case "level":
					{
						if (!amount.HasValue)
						{
							throw new InvalidOperationException("Missing the level.");
						}
						ItemData[] array4 = list.Where(Valid).ToArray();
						ItemData[] array2 = array4;
						foreach (ItemData obj4 in array2)
						{
							obj4.m_quality = amount.Value;
							obj4.m_durability = obj4.GetMaxDurability();
						}
						Helper.AddMessage(args.Context, $"{array4.Length} items upgraded.");
						break;
					}
					case "upgrade":
					{
						ItemData[] array = list.Where([<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ItemData item) => Valid(item) && (amount.HasValue || item.m_quality != item.m_shared.m_maxQuality)).ToArray();
						ItemData[] array2 = array;
						foreach (ItemData val3 in array2)
						{
							if (amount.HasValue)
							{
								val3.m_quality = amount.Value;
							}
							else
							{
								val3.m_quality = val3.m_shared.m_maxQuality;
							}
							val3.m_durability = val3.GetMaxDurability();
						}
						Helper.AddMessage(args.Context, $"{array.Length} items upgraded.");
						break;
					}
					default:
						throw new InvalidOperationException("Invalid operation. Use level, repair or upgrade.");
					}
					inventory.Changed();
				};
				<>c.<>9__5_0 = val;
				obj = (object)val;
			}
			object obj2 = <>c.<>9__5_1;
			if (obj2 == null)
			{
				ConsoleOptionsFetcher val2 = [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] () => Operations;
				<>c.<>9__5_1 = val2;
				obj2 = (object)val2;
			}
			Helper.Command("inventory", "[level/repair/upgrade] [hand/worn/all] [amount or max level if not given] - Modifies items in the inventory.", (ConsoleEvent)obj, (ConsoleOptionsFetcher)obj2);
			AutoComplete.Register("inventory", (int index) => index switch
			{
				0 => Operations, 
				1 => Targets, 
				2 => ParameterInfo.Create("Amount", "How many levels to upgrade."), 
				_ => ParameterInfo.None, 
			});
		}
	}
	[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
	[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
	public class MappingCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static readonly <>c <>9 = new <>c();

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__1_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static ConsoleEvent <>9__4_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static ConsoleEvent <>9__4_1;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
			public static ConsoleEvent <>9__4_2;

			internal List<string> <Register>b__1_0(int index)
			{
				return index switch
				{
					0 => ParameterInfo.Create("X coordinate."), 
					1 => ParameterInfo.Create("Z coordinate."), 
					2 => ParameterInfo.Create("Radius (default 0)."), 
					_ => ParameterInfo.None, 
				};
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal void <.ctor>b__4_0(ConsoleEventArgs args)
			{
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				if (ParseArgs(args, out var x, out var z, out var radius))
				{
					Vector3 val = default(Vector3);
					((Vector3)(ref val))..ctor(x, 0f, z);
					int num = 0;
					while (Minimap.instance.RemovePin(val, radius))
					{
						num++;
					}
					Helper.AddMessage(args.Context, num + " pins removed.");
				}
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal void <.ctor>b__4_1(ConsoleEventArgs args)
			{
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				float x;
				float z;
				float radius;
				if (args.Length == 1)
				{
					Minimap.instance.ExploreAll();
				}
				else if (ParseArgs(args, out x, out z, out radius))
				{
					Vector3 p = default(Vector3);
					((Vector3)(ref p))..ctor(x, 0f, z);
					ExploreRadius(args.Context, p, radius, explore: true);
				}
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)]
			internal void <.ctor>b__4_2(ConsoleEventArgs args)
			{
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				float x;
				float z;
				float radius;
				if (args.Length == 1)
				{
					Minimap.instance.Reset();
				}
				else if (ParseArgs(args, out x, out z, out radius))
				{
					Vector3 p = default(Vector3);
					((Vector3)(ref p))..ctor(x, 0f, z);
					ExploreRadius(args.Context, p, radius, explore: false);
				}
			}
		}

		private static bool ParseArgs(ConsoleEventArgs args, out float x, out float z, out float radius)
		{
			x = 0f;
			z = 0f;
			radius = 0f;
			if (args.Length < 2)
			{
				args.Context.AddString("Error: Missing coordinate X");
				return false;
			}
			if (args.Length < 3)
			{
				args.Context.AddString("Error: Missing coordinate Z");
				return false;
			}
			x = Parse.Float(args[1], float.MinValue);
			if (x == float.MinValue)
			{
				args.Context.AddString("Error: Invalid format for X coordinate.");
				return false;
			}
			z = Parse.Float(args[2], float.MinValue);
			if (z == float.MinValue)
			{
				args.Context.AddString("Error: Invalid format for Z coordinate.");
				return false;
			}
			if (args.Length > 3)
			{
				radius = Parse.Float(args[3], float.MinValue);
				if (radius == float.MinValue)
				{
					args.Context.AddString("Error: Invalid format for radius.");
					return false;
				}
			}
			return true;
		}

		private static void Register(string command)
		{
			AutoComplete.Register(command, (int index) => index switch
			{
				0 => ParameterInfo.Create("X coordinate."), 
				1 => ParameterInfo.Create("Z coordinate."), 
				2 => ParameterInfo.Create("Radius (default 0)."), 
				_ => ParameterInfo.None, 
			});
		}

		private static void ExploreRadius(Terminal terminal, Vector3 p, float radius, bool explore)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			Minimap instance = Minimap.instance;
			int num = (int)Mathf.Ceil(radius / instance.m_pixelSize);
			int num2 = default(int);
			int num3 = default(int);
			instance.WorldToPixel(p, ref num2, ref num3);
			int num4 = 0;
			for (int i = num3 - num; i <= num3 + num; i++)
			{
				if (i < 0 || i >= instance.m_textureSize)
				{
					continue;
				}
				for (int j = num2 - num; j <= num2 + num; j++)
				{
					if (j >= 0 && j < instance.m_textureSize)
					{
						Vector2 val = new Vector2((float)(j - num2), (float)(i - num3));
						if (!(((Vector2)(ref val)).magnitude > (float)num) && ExploreSpot(j, i, explore))
						{
							num4++;
						}
					}
				}
			}
			if (num4 > 0)
			{
				instance.m_fogTexture.Apply();
			}
			Helper.AddMessage(terminal, num4 + " spots " + (explore ? "explored" : "unexplored") + ".");
		}

		private static bool ExploreSpot(int x, int y, bool explore)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			Minimap instance = Minimap.instance;
			if (explore == instance.m_explored[y * instance.m_textureSize + x])
			{
				return false;
			}
			Color pixel = instance.m_fogTexture.GetPixel(x, y);
			pixel.r = ((!explore) ? 255 : 0);
			instance.m_fogTexture.SetPixel(x, y, pixel);
			instance.m_explored[y * instance.m_textureSize + x] = explore;
			return true;
		}

		public MappingCommand()
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			Register("resetpins");
			object obj = <>c.<>9__4_0;
			if (obj == null)
			{
				ConsoleEvent val = [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ConsoleEventArgs args) =>
				{
					//IL_002d: Unknown result type (might be due to invalid IL or missing references)
					if (ParseArgs(args, out var x3, out var z3, out var radius3))
					{
						Vector3 val4 = default(Vector3);
						((Vector3)(ref val4))..ctor(x3, 0f, z3);
						int num = 0;
						while (Minimap.instance.RemovePin(val4, radius3))
						{
							num++;
						}
						Helper.AddMessage(args.Context, num + " pins removed.");
					}
				};
				<>c.<>9__4_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("resetpins", "[x] [z] [radius=0] - Removes pins from the map at a given position with a given radius.", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			Register("exploremap");
			object obj2 = <>c.<>9__4_1;
			if (obj2 == null)
			{
				ConsoleEvent val2 = [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ConsoleEventArgs args) =>
				{
					//IL_0037: Unknown result type (might be due to invalid IL or missing references)
					float x2;
					float z2;
					float radius2;
					if (args.Length == 1)
					{
						Minimap.instance.ExploreAll();
					}
					else if (ParseArgs(args, out x2, out z2, out radius2))
					{
						Vector3 p2 = default(Vector3);
						((Vector3)(ref p2))..ctor(x2, 0f, z2);
						ExploreRadius(args.Context, p2, radius2, explore: true);
					}
				};
				<>c.<>9__4_1 = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("exploremap", "[x] [z] [radius=0] - Reveals part of the map. Without parameters, reveals the whole map.", (ConsoleEvent)obj2, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			Register("resetmap");
			object obj3 = <>c.<>9__4_2;
			if (obj3 == null)
			{
				ConsoleEvent val3 = [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(0)] (ConsoleEventArgs args) =>
				{
					//IL_0037: Unknown result type (might be due to invalid IL or missing references)
					float x;
					float z;
					float radius;
					if (args.Length == 1)
					{
						Minimap.instance.Reset();
					}
					else if (ParseArgs(args, out x, out z, out radius))
					{
						Vector3 p = default(Vector3);
						((Vector3)(ref p))..ctor(x, 0f, z);
						ExploreRadius(args.Context, p, radius, explore: false);
					}
				};
				<>c.<>9__4_2 = val3;
				obj3 = (object)val3;
			}
			new ConsoleCommand("resetmap", "[x] [z] [radius=0] - Hides part of the map. Without parameters, hides the whole map.", (ConsoleEvent)obj3, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
		}
	}
	public class MoveSpawn
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<KeyValuePair<Vector2i, LocationInstance>, bool> <>9__0_2;

			public static ConsoleEvent <>9__0_0;

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, int, List<string>> <>9__0_1;

			internal void <.ctor>b__0_0(ConsoleEventArgs args)
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//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_0071: 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_007f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: 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)
				string[] array = Helper.AddPlayerPosXZY(args.Args, 1);
				if (ZNet.instance.IsServer())
				{
					ZoneSystem instance = ZoneSystem.instance;
					if (Object.op_Implicit((Object)(object)instance))
					{
						Vector3 val = Parse.VectorXZY(Parse.Split(array[1]));
						KeyValuePair<Vector2i, LocationInstance> keyValuePair = instance.m_locationInstances.First((KeyValuePair<Vector2i, LocationInstance> location) => location.Value.m_location.m_prefabName == "StartTemple");
						LocationInstance value = keyValuePair.Value;
						value.m_position = val;
						instance.m_locationInstances[keyValuePair.Key] = value;
						Helper.AddMessage(args.Context, $"Spawn moved to {val:F0}");
						instance.SendLocationIcons(ZRoutedRpc.Everybody);
					}
				}
				else
				{
					ServerExecution.Send((IEnumerable<string>)array);
				}
			}

			internal bool <.ctor>b__0_2(KeyValuePair<Vector2i, LocationInstance> location)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				return location.Value.m_location.m_prefabName == "StartTemple";
			}

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
			internal List<string> <.ctor>b__0_1(int index, int subIndex)
			{
				if (index == 0)
				{
					return ParameterInfo.XZY("Coordinates (player's current coordinates if not given).", subIndex);
				}
				return ParameterInfo.None;
			}
		}

		public MoveSpawn()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					//IL_0035: Unknown result type (might be due to invalid IL or missing references)
					//IL_003a: Unknown result type (might be due to invalid IL or missing references)
					//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_0071: 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_007f: Unknown result type (might be due to invalid IL or missing references)
					//IL_0084: 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)
					string[] array = Helper.AddPlayerPosXZY(args.Args, 1);
					if (ZNet.instance.IsServer())
					{
						ZoneSystem instance = ZoneSystem.instance;
						if (Object.op_Implicit((Object)(object)instance))
						{
							Vector3 val2 = Parse.VectorXZY(Parse.Split(array[1]));
							KeyValuePair<Vector2i, LocationInstance> keyValuePair = instance.m_locationInstances.First((KeyValuePair<Vector2i, LocationInstance> location) => location.Value.m_location.m_prefabName == "StartTemple");
							LocationInstance value = keyValuePair.Value;
							value.m_position = val2;
							instance.m_locationInstances[keyValuePair.Key] = value;
							Helper.AddMessage(args.Context, $"Spawn moved to {val2:F0}");
							instance.SendLocationIcons(ZRoutedRpc.Everybody);
						}
					}
					else
					{
						ServerExecution.Send((IEnumerable<string>)array);
					}
				};
				<>c.<>9__0_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("move_spawn", "[x,z,y] Moves the default spawn point to the given coordinates (player's current coordinates if not given).", (ConsoleEvent)obj, true, true, false, false, false, (ConsoleOptionsFetcher)null, false);
			AutoComplete.Register("move_spawn", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index, int subIndex) => (index == 0) ? ParameterInfo.XZY("Coordinates (player's current coordinates if not given).", subIndex) : ParameterInfo.None);
		}
	}
	public class NoMapCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(new byte[] { 0, 1, 1 })]
			public static Func<int, List<string>> <>9__0_0;

			public static ConsoleEvent <>9__0_1;

			[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
			internal List<string> <.ctor>b__0_0(int index)
			{
				if (index != 0)
				{
					return ParameterInfo.None;
				}
				return ParameterInfo.Create("1 = disable map, 0 = enable map, no value = toggle");
			}

			internal void <.ctor>b__0_1(ConsoleEventArgs args)
			{
				bool flag = false;
				bool flag2 = Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer();
				Player localPlayer = Player.m_localPlayer;
				if (!Object.op_Implicit((Object)(object)localPlayer) && !flag2)
				{
					return;
				}
				if (args.Length < 2)
				{
					if (flag2)
					{
						flag = !ZoneSystem.instance.GetGlobalKey((GlobalKeys)25);
					}
					else if (Object.op_Implicit((Object)(object)localPlayer))
					{
						flag = PlayerPrefs.GetFloat("mapenabled_" + Player.m_localPlayer.GetPlayerName(), 1f) == 1f;
					}
				}
				else
				{
					flag = args[1] == "1";
				}
				if (flag2)
				{
					if (flag)
					{
						ZoneSystem.instance.SetGlobalKey((GlobalKeys)25);
					}
					else
					{
						ZoneSystem.instance.RemoveGlobalKey((GlobalKeys)25);
					}
				}
				if (Object.op_Implicit((Object)(object)localPlayer))
				{
					PlayerPrefs.SetFloat("mapenabled_" + Player.m_localPlayer.GetPlayerName(), flag ? 0f : 1f);
				}
				string text = "client and server";
				if (Object.op_Implicit((Object)(object)localPlayer) && !flag2)
				{
					text = "client";
				}
				if (!Object.op_Implicit((Object)(object)localPlayer) && flag2)
				{
					text = "server";
				}
				Helper.AddMessage(args.Context, "Map " + (flag ? "disabled" : "enabled") + " for the " + text + ".");
			}
		}

		public NoMapCommand()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			AutoComplete.Register("nomap", [<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)] (int index) => (index != 0) ? ParameterInfo.None : ParameterInfo.Create("1 = disable map, 0 = enable map, no value = toggle"));
			object obj = <>c.<>9__0_1;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					bool flag = false;
					bool flag2 = Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer();
					Player localPlayer = Player.m_localPlayer;
					if (Object.op_Implicit((Object)(object)localPlayer) || flag2)
					{
						if (args.Length < 2)
						{
							if (flag2)
							{
								flag = !ZoneSystem.instance.GetGlobalKey((GlobalKeys)25);
							}
							else if (Object.op_Implicit((Object)(object)localPlayer))
							{
								flag = PlayerPrefs.GetFloat("mapenabled_" + Player.m_localPlayer.GetPlayerName(), 1f) == 1f;
							}
						}
						else
						{
							flag = args[1] == "1";
						}
						if (flag2)
						{
							if (flag)
							{
								ZoneSystem.instance.SetGlobalKey((GlobalKeys)25);
							}
							else
							{
								ZoneSystem.instance.RemoveGlobalKey((GlobalKeys)25);
							}
						}
						if (Object.op_Implicit((Object)(object)localPlayer))
						{
							PlayerPrefs.SetFloat("mapenabled_" + Player.m_localPlayer.GetPlayerName(), flag ? 0f : 1f);
						}
						string text = "client and server";
						if (Object.op_Implicit((Object)(object)localPlayer) && !flag2)
						{
							text = "client";
						}
						if (!Object.op_Implicit((Object)(object)localPlayer) && flag2)
						{
							text = "server";
						}
						Helper.AddMessage(args.Context, "Map " + (flag ? "disabled" : "enabled") + " for the " + text + ".");
					}
				};
				<>c.<>9__0_1 = val;
				obj = (object)val;
			}
			new ConsoleCommand("nomap", "[set] - Toggles or sets the nomap mode. Can be executed on the server.", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
		}
	}
	[<b6a06676-42fe-4f78-b9f0-7095836d16b1>NullableContext(1)]
	[<79ee238e-4936-43cd-ab4d-2c0eb2499f37>Nullable(0)]
	public class PlayerListCommand
	{
		private string Format(ZNetPeer player)
		{
			return string.Format(Settings.Format(Settings.PlayerListFormat), player.m_playerName, player.m_socket.GetHostName(), ((ZDOID)(ref player.m_characterID)).UserID, player.m_refPos.x, player.m_refPos.y, player.m_refPos.z);
		}

		private string Format()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065:

BepInEx/plugins/JereKuusela-World_Edit_Commands/WorldEditCommands.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ServerDevcommands;
using Service;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("WorldEditCommands")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("WorldEditCommands")]
[assembly: AssemblyTitle("WorldEditCommands")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public static class Hash
{
	public static int Damage = StringExtensionMethods.GetStableHashCode("RandomSkillFactor");

	public static int Ammo = StringExtensionMethods.GetStableHashCode("ammo");

	public static int AmmoType = StringExtensionMethods.GetStableHashCode("ammoType");

	public static int PlantTime = StringExtensionMethods.GetStableHashCode("plantTime");

	public static int Status = StringExtensionMethods.GetStableHashCode("override_status");

	public static int Weather = StringExtensionMethods.GetStableHashCode("override_weather");

	public static int DungeonWeather = StringExtensionMethods.GetStableHashCode("override_dungeon_weather");

	public static int DungeonEnterText = StringExtensionMethods.GetStableHashCode("override_dungeon_enter_text");

	public static int DungeonEnterHover = StringExtensionMethods.GetStableHashCode("override_dungeon_enter_hover");

	public static int DungeonExitText = StringExtensionMethods.GetStableHashCode("override_dungeon_exit_text");

	public static int DungeonExitHover = StringExtensionMethods.GetStableHashCode("override_dungeon_exit_hover");

	public static int Water = StringExtensionMethods.GetStableHashCode("override_water");

	public static int Event = StringExtensionMethods.GetStableHashCode("override_event");

	public static int Effect = StringExtensionMethods.GetStableHashCode("override_effect");

	public static int Respawn = StringExtensionMethods.GetStableHashCode("override_respawn");

	public static int RespawnSpawnArea = StringExtensionMethods.GetStableHashCode("override_spawnarea_respawn");

	public static int RespawnPickable = StringExtensionMethods.GetStableHashCode("override_pickable_respawn");

	public static int SpawnHealth = StringExtensionMethods.GetStableHashCode("override_health");

	public static int TriggerNoise = StringExtensionMethods.GetStableHashCode("override_trigger_noise");

	public static int Spawn = StringExtensionMethods.GetStableHashCode("override_spawn");

	public static int SpawnSpawnArea = StringExtensionMethods.GetStableHashCode("override_spawnarea_spawn");

	public static int SpawnPickable = StringExtensionMethods.GetStableHashCode("override_pickable_spawn");

	public static int Biome = StringExtensionMethods.GetStableHashCode("override_biome");

	public static int Data = StringExtensionMethods.GetStableHashCode("override_data");

	public static int OverrideItem = StringExtensionMethods.GetStableHashCode("override_item");

	public static int OverrideItems = StringExtensionMethods.GetStableHashCode("override_items");

	public static int Items = StringExtensionMethods.GetStableHashCode("items");

	public static int SpawnEffect = StringExtensionMethods.GetStableHashCode("override_spawn_effect");

	public static int DestroyEffect = StringExtensionMethods.GetStableHashCode("override_destroy_effect");

	public static int UseEffect = StringExtensionMethods.GetStableHashCode("override_use_effect");

	public static int StartEffect = StringExtensionMethods.GetStableHashCode("override_start_effect");

	public static int SpawnItem = StringExtensionMethods.GetStableHashCode("override_spawn_item");

	public static int Faction = StringExtensionMethods.GetStableHashCode("override_faction");

	public static int Command = StringExtensionMethods.GetStableHashCode("override_command");

	public static int Resistances = StringExtensionMethods.GetStableHashCode("override_resistances");

	public static int Attacks = StringExtensionMethods.GetStableHashCode("override_attacks");

	public static int SpawnOffset = StringExtensionMethods.GetStableHashCode("override_spawn_offset");

	public static int Component = StringExtensionMethods.GetStableHashCode("override_component");

	public static int MinAmount = StringExtensionMethods.GetStableHashCode("override_minimum_amount");

	public static int MaxAmount = StringExtensionMethods.GetStableHashCode("override_maximum_amount");

	public static int MinLevel = StringExtensionMethods.GetStableHashCode("override_minimum_level");

	public static int MaxLevel = StringExtensionMethods.GetStableHashCode("override_maximum_level");

	public static int Conversion = StringExtensionMethods.GetStableHashCode("override_conversion");

	public static int MaxFuel = StringExtensionMethods.GetStableHashCode("override_maximum_fuel");

	public static int FuelUsage = StringExtensionMethods.GetStableHashCode("override_fuel_usage");

	public static int Speed = StringExtensionMethods.GetStableHashCode("override_speed");

	public static int MaxCover = StringExtensionMethods.GetStableHashCode("override_maximum_cover");

	public static int InputEffect = StringExtensionMethods.GetStableHashCode("override_input_effect");

	public static int FuelEffect = StringExtensionMethods.GetStableHashCode("override_fuel_effect");

	public static int OutputEffect = StringExtensionMethods.GetStableHashCode("override_output_effect");

	public static int MaxNear = StringExtensionMethods.GetStableHashCode("override_max_near");

	public static int MaxTotal = StringExtensionMethods.GetStableHashCode("override_max_total");

	public static int LevelChance = StringExtensionMethods.GetStableHashCode("override_level_chance");

	public static int TriggerDistance = StringExtensionMethods.GetStableHashCode("override_trigger_distance");

	public static int OverrideText = StringExtensionMethods.GetStableHashCode("override_text");

	public static int Compendium = StringExtensionMethods.GetStableHashCode("override_compendium");

	public static int Topic = StringExtensionMethods.GetStableHashCode("override_topic");

	public static int Discover = StringExtensionMethods.GetStableHashCode("override_discover");

	public static int Delay = StringExtensionMethods.GetStableHashCode("override_delay");

	public static int ItemOffset = StringExtensionMethods.GetStableHashCode("override_item_offset");

	public static int CoverOffset = StringExtensionMethods.GetStableHashCode("override_cover_offset");

	public static int SpawnMaxY = StringExtensionMethods.GetStableHashCode("override_spawn_max_y");

	public static int Destroy = StringExtensionMethods.GetStableHashCode("override_destroy");

	public static int ItemStandPrefix = StringExtensionMethods.GetStableHashCode("override_item_stand_prefix");

	public static int ItemStandRange = StringExtensionMethods.GetStableHashCode("override_item_stand_range");

	public static int GlobalKey = StringExtensionMethods.GetStableHashCode("override_globalkey");

	public static int SpawnRadius = StringExtensionMethods.GetStableHashCode("override_spawn_radius");

	public static int NearRadius = StringExtensionMethods.GetStableHashCode("override_near_radius");

	public static int FarRadius = StringExtensionMethods.GetStableHashCode("override_far_radius");

	public static int OverrideName = StringExtensionMethods.GetStableHashCode("override_name");

	public static int TextBiome = StringExtensionMethods.GetStableHashCode("override_text_biome");

	public static int TextSpace = StringExtensionMethods.GetStableHashCode("override_text_space");

	public static int TextSleep = StringExtensionMethods.GetStableHashCode("override_text_sleep");

	public static int TextHappy = StringExtensionMethods.GetStableHashCode("override_text_happy");

	public static int TextCheck = StringExtensionMethods.GetStableHashCode("override_text_check");

	public static int TextExtract = StringExtensionMethods.GetStableHashCode("override_text_extract");

	public static int SpawnCondition = StringExtensionMethods.GetStableHashCode("override_spawn_condition");

	public static int Amount = StringExtensionMethods.GetStableHashCode("override_amount");

	public static int Wear = StringExtensionMethods.GetStableHashCode("override_wear");

	public static int Fall = StringExtensionMethods.GetStableHashCode("override_fall");

	public static int Growth = StringExtensionMethods.GetStableHashCode("override_growth");

	public static int NoInteract = StringExtensionMethods.GetStableHashCode("override_interact");

	public static int NoRender = StringExtensionMethods.GetStableHashCode("override_render");

	public static int NoCollision = StringExtensionMethods.GetStableHashCode("override_collision");

	public static int NoRestrict = StringExtensionMethods.GetStableHashCode("override_restrict");

	public static int Boss = StringExtensionMethods.GetStableHashCode("override_boss");

	public static int Smoke = StringExtensionMethods.GetStableHashCode("override_smoke");

	public static int CLLC_Affix = StringExtensionMethods.GetStableHashCode("CL&LC effect");

	public static int Unlock = StringExtensionMethods.GetStableHashCode("override_unlock");

	public static int Health = StringExtensionMethods.GetStableHashCode("health");

	public static int Level = StringExtensionMethods.GetStableHashCode("level");

	public static int Text = StringExtensionMethods.GetStableHashCode("text");

	public static int Pose = StringExtensionMethods.GetStableHashCode("pose");

	public static int Item = StringExtensionMethods.GetStableHashCode("item");

	public static int Variant = StringExtensionMethods.GetStableHashCode("variant");

	public static int Tamed = StringExtensionMethods.GetStableHashCode("tamed");

	public static int HuntPlayer = StringExtensionMethods.GetStableHashCode("huntplayer");

	public static int Quality = StringExtensionMethods.GetStableHashCode("quality");

	public static int Creator = StringExtensionMethods.GetStableHashCode("creator");

	public static int Stack = StringExtensionMethods.GetStableHashCode("stack");

	public static int AliveTime = StringExtensionMethods.GetStableHashCode("alive_time");

	public static int CrafterID = StringExtensionMethods.GetStableHashCode("crafterID");

	public static int CrafterName = StringExtensionMethods.GetStableHashCode("crafterName");

	public static int AddedDefaultItems = StringExtensionMethods.GetStableHashCode("addedDefaultItems");

	public static int OverrideFuel = StringExtensionMethods.GetStableHashCode("override_fuel");

	public static int Fuel = StringExtensionMethods.GetStableHashCode("fuel");

	public static int Durability = StringExtensionMethods.GetStableHashCode("durability");

	public static int Sleeping = StringExtensionMethods.GetStableHashCode("sleeping");

	public static int SpawnTime = StringExtensionMethods.GetStableHashCode("spawntime");

	public static int TamedName = StringExtensionMethods.GetStableHashCode("TamedName");

	public static int Tag = StringExtensionMethods.GetStableHashCode("tag");

	public static int Seed = StringExtensionMethods.GetStableHashCode("seed");

	public static int Location = StringExtensionMethods.GetStableHashCode("location");

	public static int SpawnPoint = StringExtensionMethods.GetStableHashCode("spawnpoint");

	public static int Scale = StringExtensionMethods.GetStableHashCode("scale");
}
namespace Service
{
	public class DataHelper
	{
		public static void Init(GameObject obj, Vector3 pos, Quaternion rot, Vector3 scale, ZPackage? data)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = default(ZNetView);
			if ((data != null || !(scale == Vector3.one)) && obj.TryGetComponent<ZNetView>(ref val))
			{
				int stableHashCode = StringExtensionMethods.GetStableHashCode(Utils.GetPrefabName(obj));
				ZNetView.m_initZDO = ZDOMan.instance.CreateNewZDO(pos, stableHashCode);
				if (data != null)
				{
					Load(data, ZNetView.m_initZDO);
				}
				ZNetView.m_initZDO.m_rotation = ((Quaternion)(ref rot)).eulerAngles;
				ZNetView.m_initZDO.Type = val.m_type;
				ZNetView.m_initZDO.Distant = val.m_distant;
				ZNetView.m_initZDO.Persistent = val.m_persistent;
				ZNetView.m_initZDO.m_prefab = stableHashCode;
				if (val.m_syncInitialScale)
				{
					ZNetView.m_initZDO.Set(ZDOVars.s_scaleHash, scale);
				}
				ZNetView.m_initZDO.DataRevision = 1u;
			}
		}

		public static void CleanUp()
		{
			ZNetView.m_initZDO = null;
		}

		public static ZPackage? Deserialize(string data)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			if (!(data == ""))
			{
				return new ZPackage(data);
			}
			return null;
		}

		public static void Serialize(ZDO zdo, ZPackage pkg, string filter)
		{
			//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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0517: Unknown result type (might be due to invalid IL or missing references)
			ZDOID uid = zdo.m_uid;
			Dictionary<int, Vector3> dictionary = (ZDOExtraData.s_vec3.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, Vector3>>)ZDOExtraData.s_vec3[uid]).ToDictionary((KeyValuePair<int, Vector3> kvp) => kvp.Key, (KeyValuePair<int, Vector3> kvp) => kvp.Value) : new Dictionary<int, Vector3>());
			Dictionary<int, int> dictionary2 = (ZDOExtraData.s_ints.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, int>>)ZDOExtraData.s_ints[uid]).ToDictionary((KeyValuePair<int, int> kvp) => kvp.Key, (KeyValuePair<int, int> kvp) => kvp.Value) : new Dictionary<int, int>());
			Dictionary<int, float> dictionary3 = (ZDOExtraData.s_floats.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, float>>)ZDOExtraData.s_floats[uid]).ToDictionary((KeyValuePair<int, float> kvp) => kvp.Key, (KeyValuePair<int, float> kvp) => kvp.Value) : new Dictionary<int, float>());
			Dictionary<int, Quaternion> dictionary4 = (ZDOExtraData.s_quats.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, Quaternion>>)ZDOExtraData.s_quats[uid]).ToDictionary((KeyValuePair<int, Quaternion> kvp) => kvp.Key, (KeyValuePair<int, Quaternion> kvp) => kvp.Value) : new Dictionary<int, Quaternion>());
			Dictionary<int, string> dictionary5 = (ZDOExtraData.s_strings.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, string>>)ZDOExtraData.s_strings[uid]).ToDictionary((KeyValuePair<int, string> kvp) => kvp.Key, (KeyValuePair<int, string> kvp) => kvp.Value) : new Dictionary<int, string>());
			Dictionary<int, long> dictionary6 = (ZDOExtraData.s_longs.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, long>>)ZDOExtraData.s_longs[uid]).ToDictionary((KeyValuePair<int, long> kvp) => kvp.Key, (KeyValuePair<int, long> kvp) => kvp.Value) : new Dictionary<int, long>());
			Dictionary<int, byte[]> dictionary7 = (ZDOExtraData.s_byteArrays.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, byte[]>>)ZDOExtraData.s_byteArrays[uid]).ToDictionary((KeyValuePair<int, byte[]> kvp) => kvp.Key, (KeyValuePair<int, byte[]> kvp) => kvp.Value) : new Dictionary<int, byte[]>());
			if (filter == "")
			{
				dictionary.Remove(Hash.Scale);
				dictionary.Remove(Hash.SpawnPoint);
				dictionary2.Remove(Hash.Seed);
				dictionary2.Remove(Hash.Location);
				if (dictionary5.ContainsKey(Hash.OverrideItems))
				{
					dictionary2.Remove(Hash.AddedDefaultItems);
					dictionary5.Remove(Hash.Items);
				}
			}
			else if (filter != "all")
			{
				HashSet<int> filters = (from s in Parse.Split(filter, ',')
					select StringExtensionMethods.GetStableHashCode(s)).ToHashSet();
				dictionary = FilterZdo(dictionary, filters);
				dictionary4 = FilterZdo(dictionary4, filters);
				dictionary3 = FilterZdo(dictionary3, filters);
				dictionary2 = FilterZdo(dictionary2, filters);
				dictionary6 = FilterZdo(dictionary6, filters);
				dictionary7 = FilterZdo(dictionary7, filters);
			}
			int num = 0;
			if (dictionary3.Count() > 0)
			{
				num |= 1;
			}
			if (dictionary.Count() > 0)
			{
				num |= 2;
			}
			if (dictionary4.Count() > 0)
			{
				num |= 4;
			}
			if (dictionary2.Count() > 0)
			{
				num |= 8;
			}
			if (dictionary5.Count() > 0)
			{
				num |= 0x10;
			}
			if (dictionary6.Count() > 0)
			{
				num |= 0x40;
			}
			if (dictionary7.Count() > 0)
			{
				num |= 0x80;
			}
			pkg.Write(num);
			if (dictionary3.Count() > 0)
			{
				pkg.Write((byte)dictionary3.Count());
				foreach (KeyValuePair<int, float> item in dictionary3)
				{
					pkg.Write(item.Key);
					pkg.Write(item.Value);
				}
			}
			if (dictionary.Count() > 0)
			{
				pkg.Write((byte)dictionary.Count());
				foreach (KeyValuePair<int, Vector3> item2 in dictionary)
				{
					pkg.Write(item2.Key);
					pkg.Write(item2.Value);
				}
			}
			if (dictionary4.Count() > 0)
			{
				pkg.Write((byte)dictionary4.Count());
				foreach (KeyValuePair<int, Quaternion> item3 in dictionary4)
				{
					pkg.Write(item3.Key);
					pkg.Write(item3.Value);
				}
			}
			if (dictionary2.Count() > 0)
			{
				pkg.Write((byte)dictionary2.Count());
				foreach (KeyValuePair<int, int> item4 in dictionary2)
				{
					pkg.Write(item4.Key);
					pkg.Write(item4.Value);
				}
			}
			if (dictionary6.Count() > 0)
			{
				pkg.Write((byte)dictionary6.Count());
				foreach (KeyValuePair<int, long> item5 in dictionary6)
				{
					pkg.Write(item5.Key);
					pkg.Write(item5.Value);
				}
			}
			if (dictionary5.Count() > 0)
			{
				pkg.Write((byte)dictionary5.Count());
				foreach (KeyValuePair<int, string> item6 in dictionary5)
				{
					pkg.Write(item6.Key);
					pkg.Write(item6.Value);
				}
			}
			if (dictionary7.Count() <= 0)
			{
				return;
			}
			pkg.Write((byte)dictionary7.Count());
			foreach (KeyValuePair<int, byte[]> item7 in dictionary7)
			{
				pkg.Write(item7.Key);
				pkg.Write(item7.Value);
			}
		}

		private static void Load(ZPackage pkg, ZDO zdo)
		{
			//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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			ZDOID uid = zdo.m_uid;
			int num = pkg.ReadInt();
			if (((uint)num & (true ? 1u : 0u)) != 0)
			{
				byte b = pkg.ReadByte();
				for (int i = 0; i < b; i++)
				{
					ZDOExtraData.Set(uid, pkg.ReadInt(), pkg.ReadSingle());
				}
			}
			if (((uint)num & 2u) != 0)
			{
				byte b2 = pkg.ReadByte();
				for (int j = 0; j < b2; j++)
				{
					ZDOExtraData.Set(uid, pkg.ReadInt(), pkg.ReadVector3());
				}
			}
			if (((uint)num & 4u) != 0)
			{
				byte b3 = pkg.ReadByte();
				for (int k = 0; k < b3; k++)
				{
					ZDOExtraData.Set(uid, pkg.ReadInt(), pkg.ReadQuaternion());
				}
			}
			if (((uint)num & 8u) != 0)
			{
				byte b4 = pkg.ReadByte();
				for (int l = 0; l < b4; l++)
				{
					ZDOExtraData.Set(uid, pkg.ReadInt(), pkg.ReadInt());
				}
			}
			if (((uint)num & 0x10u) != 0)
			{
				byte b5 = pkg.ReadByte();
				for (int m = 0; m < b5; m++)
				{
					ZDOExtraData.Set(uid, pkg.ReadInt(), pkg.ReadString());
				}
			}
			if (((uint)num & 0x40u) != 0)
			{
				byte b6 = pkg.ReadByte();
				for (int n = 0; n < b6; n++)
				{
					ZDOExtraData.Set(uid, pkg.ReadInt(), pkg.ReadLong());
				}
			}
			if (((uint)num & 0x80u) != 0)
			{
				byte b7 = pkg.ReadByte();
				for (int num2 = 0; num2 < b7; num2++)
				{
					ZDOExtraData.Set(uid, pkg.ReadInt(), pkg.ReadByteArray());
				}
			}
		}

		private static Dictionary<int, T> FilterZdo<T>(Dictionary<int, T> dict, HashSet<int> filters)
		{
			HashSet<int> filters2 = filters;
			return dict.Where<KeyValuePair<int, T>>((KeyValuePair<int, T> kvp) => filters2.Contains(kvp.Key)).ToDictionary((KeyValuePair<int, T> kvp) => kvp.Key, (KeyValuePair<int, T> pair) => pair.Value);
		}
	}
	public enum ObjectType
	{
		All,
		Character,
		Structure,
		Fireplace,
		Item,
		Chest,
		Spawner,
		SpawnPoint
	}
	public class Hovered
	{
		public ZNetView Obj;

		public int Index;

		public Hovered(ZNetView obj, int index)
		{
			Obj = obj;
			Index = index;
		}
	}
	public static class Selector
	{
		private static KeyValuePair<int, int> RaftParent = ZDO.GetHashZDOID("MBParent");

		public static bool IsValid(ZNetView view)
		{
			if (Object.op_Implicit((Object)(object)view))
			{
				return IsValid(view.GetZDO());
			}
			return false;
		}

		public static bool IsValid(ZDO zdo)
		{
			if (zdo != null)
			{
				return zdo.IsValid();
			}
			return false;
		}

		public static ZNetView? GetHovered(float range, string[] excluded)
		{
			return GetHovered(Player.m_localPlayer, range, excluded)?.Obj;
		}

		public static int GetPrefabFromHit(RaycastHit hit)
		{
			return ((Component)((RaycastHit)(ref hit)).collider).GetComponentInParent<ZNetView>().GetZDO().GetPrefab();
		}

		public static Hovered? GetHovered(Player obj, float maxDistance, string[] excluded, bool allowOtherPlayers = false)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			HashSet<int> excludedPrefabs = GetExcludedPrefabs(excluded);
			float num = Math.Max(maxDistance + 5f, 50f);
			int mask = LayerMask.GetMask(new string[11]
			{
				"item", "piece", "piece_nonsolid", "Default", "static_solid", "Default_small", "character", "character_net", "terrain", "vehicle",
				"character_trigger"
			});
			RaycastHit[] array = Physics.RaycastAll(((Component)GameCamera.instance).transform.position, ((Component)GameCamera.instance).transform.forward, num, mask);
			Array.Sort(array, (RaycastHit x, RaycastHit y) => ((RaycastHit)(ref x)).distance.CompareTo(((RaycastHit)(ref y)).distance));
			RaycastHit[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				RaycastHit val = array2[i];
				if (Vector3.Distance(((RaycastHit)(ref val)).point, ((Character)obj).m_eye.position) >= maxDistance)
				{
					continue;
				}
				ZNetView componentInParent = ((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<ZNetView>();
				if (!IsValid(componentInParent) || excludedPrefabs.Contains(componentInParent.GetZDO().GetPrefab()) || Object.op_Implicit((Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponent<EffectArea>()))
				{
					continue;
				}
				Player componentInChildren = ((Component)componentInParent).GetComponentInChildren<Player>();
				if (!((Object)(object)componentInChildren == (Object)(object)obj) && (allowOtherPlayers || !Object.op_Implicit((Object)(object)componentInChildren)))
				{
					MineRock5 component = ((Component)componentInParent).GetComponent<MineRock5>();
					int index = 0;
					if (Object.op_Implicit((Object)(object)component))
					{
						index = component.GetAreaIndex(((RaycastHit)(ref val)).collider);
					}
					return new Hovered(componentInParent, index);
				}
			}
			return null;
		}

		private static float GetX(float x, float y, float angle)
		{
			return Mathf.Cos(angle) * x - Mathf.Sin(angle) * y;
		}

		private static float GetY(float x, float y, float angle)
		{
			return Mathf.Sin(angle) * x + Mathf.Cos(angle) * y;
		}

		public static bool Within(Vector3 position, Vector3 center, float angle, Range<float> width, Range<float> depth, float height)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			float x = position.x - center.x;
			float y = position.z - center.z;
			float x2 = GetX(x, y, angle);
			float y2 = GetY(x, y, angle);
			if (center.y - position.y > 1000f)
			{
				return false;
			}
			if (position.y - center.y > ((height == 0f) ? 1000f : height))
			{
				return false;
			}
			return Helper.Within(width, depth, Mathf.Abs(x2), Mathf.Abs(y2));
		}

		public static bool Within(Vector3 position, Vector3 center, Range<float> radius, float height)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (Helper.Within(radius, Utils.DistanceXZ(position, center)) && center.y - position.y < 1000f)
			{
				return position.y - center.y <= ((height == 0f) ? 1000f : height);
			}
			return false;
		}

		private static bool IsIncluded(string id, string name)
		{
			if (id.StartsWith("*", StringComparison.Ordinal) && id.EndsWith("*", StringComparison.Ordinal))
			{
				return name.Contains(id.Substring(1, id.Length - 3));
			}
			if (id.StartsWith("*", StringComparison.Ordinal))
			{
				return name.EndsWith(id.Substring(1), StringComparison.Ordinal);
			}
			if (id.EndsWith("*", StringComparison.Ordinal))
			{
				return name.StartsWith(id.Substring(0, id.Length - 2), StringComparison.Ordinal);
			}
			return id == name;
		}

		public static HashSet<int> GetExcludedPrefabs(string[] ids)
		{
			HashSet<int> hashSet = new HashSet<int>();
			foreach (string id in ids)
			{
				hashSet.UnionWith(GetExcludedPrefabs(id));
			}
			return hashSet;
		}

		private static HashSet<int> GetExcludedPrefabs(string id)
		{
			string id2 = id;
			if (id2 == "")
			{
				return new HashSet<int>();
			}
			id2 = id2.ToLower();
			return (from prefab in ZNetScene.instance.m_namedPrefabs.Values
				where IsIncluded(id2, ((Object)prefab).name.ToLower())
				select StringExtensionMethods.GetStableHashCode(((Object)prefab).name)).ToHashSet();
		}

		public static HashSet<int> GetPrefabs(string[] ids)
		{
			if (ids.Length == 0)
			{
				return GetPrefabs("*");
			}
			HashSet<int> hashSet = new HashSet<int>();
			foreach (string id in ids)
			{
				hashSet.UnionWith(GetPrefabs(id));
			}
			return hashSet;
		}

		private static HashSet<int> GetPrefabs(string id)
		{
			string id2 = id;
			id2 = id2.ToLower();
			IEnumerable<GameObject> values = ZNetScene.instance.m_namedPrefabs.Values;
			values = values.Where((GameObject prefab) => ((Object)prefab).name != "Player");
			values = ((id2 == "*" || id2 == "") ? values.Where((GameObject prefab) => !((Object)prefab).name.StartsWith("_", StringComparison.Ordinal)) : ((!id2.Contains("*")) ? values.Where((GameObject prefab) => ((Object)prefab).name.ToLower() == id2) : values.Where((GameObject prefab) => IsIncluded(id2, ((Object)prefab).name.ToLower()))));
			return values.Select((GameObject prefab) => StringExtensionMethods.GetStableHashCode(((Object)prefab).name)).ToHashSet();
		}

		public static ZNetView[] GetNearby(string[] included, ObjectType type, string[] excluded, Vector3 center, Range<float> radius, float height)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			Range<float> radius2 = radius;
			HashSet<int> prefabs = GetPrefabs(included);
			HashSet<int> excludedPrefabs = GetExcludedPrefabs(excluded);
			Func<Vector3, bool> checker = (Vector3 pos) => Within(pos, center, radius2, height);
			return GetNearby(prefabs, type, excludedPrefabs, checker);
		}

		public static ZNetView[] GetNearby(string[] included, ObjectType type, string[] excluded, Vector3 center, float angle, Range<float> width, Range<float> depth, float height)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			Range<float> width2 = width;
			Range<float> depth2 = depth;
			HashSet<int> prefabs = GetPrefabs(included);
			HashSet<int> excludedPrefabs = GetExcludedPrefabs(excluded);
			Func<Vector3, bool> checker = (Vector3 pos) => Within(pos, center, angle, width2, depth2, height);
			return GetNearby(prefabs, type, excludedPrefabs, checker);
		}

		public static ZNetView[] GetNearby(HashSet<int> included, ObjectType type, HashSet<int> excluded, Func<Vector3, bool> checker)
		{
			HashSet<int> included2 = included;
			HashSet<int> excluded2 = excluded;
			Func<Vector3, bool> checker2 = checker;
			_ = ZNetScene.instance;
			IEnumerable<ZNetView> source = ZNetScene.instance.m_instances.Values.Where(IsValid);
			if (included2.Count > 0)
			{
				source = source.Where((ZNetView view) => included2.Contains(view.GetZDO().GetPrefab()));
			}
			if (excluded2.Count > 0)
			{
				source = source.Where((ZNetView view) => !excluded2.Contains(view.GetZDO().GetPrefab()));
			}
			source = source.Where((ZNetView view) => checker2(view.GetZDO().GetPosition()));
			if (type == ObjectType.Structure)
			{
				source = source.Where((ZNetView view) => Object.op_Implicit((Object)(object)((Component)view).GetComponent<Piece>()));
			}
			if (type == ObjectType.Character)
			{
				source = source.Where((ZNetView view) => Object.op_Implicit((Object)(object)((Component)view).GetComponent<Character>()));
			}
			if (type == ObjectType.Fireplace)
			{
				source = source.Where((ZNetView view) => Object.op_Implicit((Object)(object)((Component)view).GetComponent<Fireplace>()));
			}
			if (type == ObjectType.Item)
			{
				source = source.Where((ZNetView view) => Object.op_Implicit((Object)(object)((Component)view).GetComponent<ItemDrop>()));
			}
			if (type == ObjectType.Chest)
			{
				source = source.Where((ZNetView view) => Object.op_Implicit((Object)(object)((Component)view).GetComponent<Container>()));
			}
			if (type == ObjectType.Spawner)
			{
				source = source.Where((ZNetView view) => Object.op_Implicit((Object)(object)((Component)view).GetComponent<SpawnArea>()));
			}
			if (type == ObjectType.SpawnPoint)
			{
				source = source.Where((ZNetView view) => Object.op_Implicit((Object)(object)((Component)view).GetComponent<CreatureSpawner>()));
			}
			ZNetView[] array = source.ToArray();
			if (array.Length == 0)
			{
				throw new InvalidOperationException("Nothing is nearby.");
			}
			return array;
		}

		public static ZNetView[] GetConnectedRaft(ZNetView baseView, HashSet<int> excluded)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			HashSet<int> excluded2 = excluded;
			ZDOID id = baseView.GetZDO().GetZDOID(RaftParent);
			return (from view in ZNetScene.instance.m_instances.Values.Where(IsValid)
				where !excluded2.Contains(view.GetZDO().m_prefab)
				where view.GetZDO().m_uid == id || view.GetZDO().GetZDOID(RaftParent) == id
				select view).ToArray();
		}

		public static ZNetView[] GetConnected(ZNetView baseView, string[] excluded)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			HashSet<int> excludedPrefabs = GetExcludedPrefabs(excluded);
			if (baseView.GetZDO().GetZDOID(RaftParent) != ZDOID.None)
			{
				return GetConnectedRaft(baseView, excludedPrefabs);
			}
			WearNTear item = ((Component)baseView).GetComponent<WearNTear>() ?? throw new InvalidOperationException("Connected doesn't work for this object.");
			HashSet<ZNetView> hashSet = new HashSet<ZNetView> { baseView };
			Queue<WearNTear> queue = new Queue<WearNTear>();
			queue.Enqueue(item);
			while (queue.Count > 0)
			{
				WearNTear val = queue.Dequeue();
				if (val.m_colliders == null)
				{
					val.SetupColliders();
				}
				foreach (BoundData bound in val.m_bounds)
				{
					int num = Physics.OverlapBoxNonAlloc(bound.m_pos, bound.m_size, WearNTear.s_tempColliders, bound.m_rot, WearNTear.s_rayMask);
					for (int i = 0; i < num; i++)
					{
						Collider val2 = WearNTear.s_tempColliders[i];
						if (!val2.isTrigger && !((Object)(object)val2.attachedRigidbody != (Object)null) && !val.m_colliders.Contains(val2))
						{
							WearNTear componentInParent = ((Component)val2).GetComponentInParent<WearNTear>();
							if (Object.op_Implicit((Object)(object)componentInParent) && IsValid(componentInParent.m_nview) && !excludedPrefabs.Contains(componentInParent.m_nview.GetZDO().GetPrefab()) && !hashSet.Contains(componentInParent.m_nview))
							{
								hashSet.Add(componentInParent.m_nview);
								queue.Enqueue(componentInParent);
							}
						}
					}
				}
			}
			return hashSet.ToArray();
		}
	}
	public class FakeZDO
	{
		private readonly ZDOData Data;

		public readonly ZDO Source;

		public int Prefab => Source.m_prefab;

		public Vector3 Position => Source.m_position;

		public FakeZDO(ZDO zdo)
		{
			Data = new ZDOData(zdo);
			Source = zdo.Clone();
		}

		public ZDO Create()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			ZDO val = ZDOMan.instance.CreateNewZDO(Position, Prefab);
			Copy(val);
			return val;
		}

		public void Copy(ZDO zdo)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_003a: Unknown result type (might be due to invalid IL or missing references)
			zdo.m_prefab = Source.m_prefab;
			zdo.m_position = Source.m_position;
			zdo.m_rotation = Source.m_rotation;
			zdo.Type = Source.Type;
			zdo.Distant = Source.Distant;
			zdo.Persistent = Source.Persistent;
			Data.Copy(zdo);
		}

		public void Destroy()
		{
			if (!Source.IsOwner())
			{
				Source.SetOwner(ZDOMan.instance.m_sessionID);
			}
			ZDOMan.instance.DestroyZDO(Source);
		}
	}
	public class ZDOData
	{
		public Dictionary<int, string> Strings = new Dictionary<int, string>();

		public Dictionary<int, float> Floats = new Dictionary<int, float>();

		public Dictionary<int, int> Ints = new Dictionary<int, int>();

		public Dictionary<int, long> Longs = new Dictionary<int, long>();

		public Dictionary<int, Vector3> Vecs = new Dictionary<int, Vector3>();

		public Dictionary<int, Quaternion> Quats = new Dictionary<int, Quaternion>();

		public Dictionary<int, byte[]> ByteArrays = new Dictionary<int, byte[]>();

		public ZDOData()
		{
		}

		public ZDOData(ZDO zdo)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			ZDOID uid = zdo.m_uid;
			Floats = (ZDOExtraData.s_floats.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, float>>)ZDOExtraData.s_floats[uid]).ToDictionary((KeyValuePair<int, float> kvp) => kvp.Key, (KeyValuePair<int, float> kvp) => kvp.Value) : new Dictionary<int, float>());
			Ints = (ZDOExtraData.s_ints.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, int>>)ZDOExtraData.s_ints[uid]).ToDictionary((KeyValuePair<int, int> kvp) => kvp.Key, (KeyValuePair<int, int> kvp) => kvp.Value) : new Dictionary<int, int>());
			Longs = (ZDOExtraData.s_longs.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, long>>)ZDOExtraData.s_longs[uid]).ToDictionary((KeyValuePair<int, long> kvp) => kvp.Key, (KeyValuePair<int, long> kvp) => kvp.Value) : new Dictionary<int, long>());
			Strings = (ZDOExtraData.s_strings.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, string>>)ZDOExtraData.s_strings[uid]).ToDictionary((KeyValuePair<int, string> kvp) => kvp.Key, (KeyValuePair<int, string> kvp) => kvp.Value) : new Dictionary<int, string>());
			Vecs = (ZDOExtraData.s_vec3.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, Vector3>>)ZDOExtraData.s_vec3[uid]).ToDictionary((KeyValuePair<int, Vector3> kvp) => kvp.Key, (KeyValuePair<int, Vector3> kvp) => kvp.Value) : new Dictionary<int, Vector3>());
			Quats = (ZDOExtraData.s_quats.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, Quaternion>>)ZDOExtraData.s_quats[uid]).ToDictionary((KeyValuePair<int, Quaternion> kvp) => kvp.Key, (KeyValuePair<int, Quaternion> kvp) => kvp.Value) : new Dictionary<int, Quaternion>());
			ByteArrays = (ZDOExtraData.s_byteArrays.ContainsKey(uid) ? ((IEnumerable<KeyValuePair<int, byte[]>>)ZDOExtraData.s_byteArrays[uid]).ToDictionary((KeyValuePair<int, byte[]> kvp) => kvp.Key, (KeyValuePair<int, byte[]> kvp) => kvp.Value) : new Dictionary<int, byte[]>());
		}

		public ZDOData(ZPackage? pkg)
		{
			if (pkg != null)
			{
				Load(pkg);
			}
		}

		public void Copy(ZDO zdo)
		{
			//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_001a: 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_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			ZDOID uid = zdo.m_uid;
			if (Floats.Count > 0)
			{
				ZDOHelper.Release<float>(ZDOExtraData.s_floats, uid);
				foreach (KeyValuePair<int, float> @float in Floats)
				{
					ZDOExtraData.Set(uid, @float.Key, @float.Value);
				}
			}
			if (Ints.Count > 0)
			{
				ZDOHelper.Release<int>(ZDOExtraData.s_ints, uid);
				foreach (KeyValuePair<int, int> @int in Ints)
				{
					ZDOExtraData.Set(uid, @int.Key, @int.Value);
				}
			}
			if (Longs.Count > 0)
			{
				ZDOHelper.Release<long>(ZDOExtraData.s_longs, uid);
				foreach (KeyValuePair<int, long> @long in Longs)
				{
					ZDOExtraData.Set(uid, @long.Key, @long.Value);
				}
			}
			if (Strings.Count > 0)
			{
				ZDOHelper.Release<string>(ZDOExtraData.s_strings, uid);
				foreach (KeyValuePair<int, string> @string in Strings)
				{
					ZDOExtraData.Set(uid, @string.Key, @string.Value);
				}
			}
			if (Vecs.Count > 0)
			{
				ZDOHelper.Release<Vector3>(ZDOExtraData.s_vec3, uid);
				foreach (KeyValuePair<int, Vector3> vec in Vecs)
				{
					ZDOExtraData.Set(uid, vec.Key, vec.Value);
				}
			}
			if (Quats.Count > 0)
			{
				ZDOHelper.Release<Quaternion>(ZDOExtraData.s_quats, uid);
				foreach (KeyValuePair<int, Quaternion> quat in Quats)
				{
					ZDOExtraData.Set(uid, quat.Key, quat.Value);
				}
			}
			if (ByteArrays.Count > 0)
			{
				ZDOHelper.Release<byte[]>(ZDOExtraData.s_byteArrays, uid);
				foreach (KeyValuePair<int, byte[]> byteArray in ByteArrays)
				{
					ZDOExtraData.Set(uid, byteArray.Key, byteArray.Value);
				}
			}
			zdo.IncreaseDataRevision();
		}

		public string GetString(int hash, string defautlValue = "")
		{
			if (!Strings.TryGetValue(hash, out string value))
			{
				return defautlValue;
			}
			return value;
		}

		public string GetString(string key, string defautlValue = "")
		{
			return GetString(StringExtensionMethods.GetStableHashCode(key), defautlValue);
		}

		public void Set(int hash, string value)
		{
			Strings[hash] = value;
		}

		public void Set(string key, string value)
		{
			Set(StringExtensionMethods.GetStableHashCode(key), value);
		}

		public float GetFloat(int hash, float defautlValue = 0f)
		{
			if (!Floats.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public void Set(int hash, float value)
		{
			Floats[hash] = value;
		}

		public int GetInt(int hash, int defautlValue = 0)
		{
			if (!Ints.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public int GetInt(string key, int defautlValue = 0)
		{
			return GetInt(StringExtensionMethods.GetStableHashCode(key), defautlValue);
		}

		public void Set(int hash, int value)
		{
			Ints[hash] = value;
		}

		public void Set(string key, int value)
		{
			Set(StringExtensionMethods.GetStableHashCode(key), value);
		}

		public void Set(int hash, bool value)
		{
			Ints[hash] = (value ? 1 : 0);
		}

		public long GetLong(int hash, long defautlValue = 0L)
		{
			if (!Longs.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public ZDOID GetZDOID(KeyValuePair<int, int> hashPair)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			long @long = GetLong(hashPair.Key, 0L);
			uint num = (uint)GetLong(hashPair.Value, 0L);
			if (@long == 0L || num == 0)
			{
				return ZDOID.None;
			}
			return new ZDOID(@long, num);
		}

		public void Set(int hash, long value)
		{
			Longs[hash] = value;
		}

		public void Set(KeyValuePair<int, int> hashPair, ZDOID id)
		{
			Set(hashPair.Key, ((ZDOID)(ref id)).UserID);
			Set(hashPair.Value, (long)((ZDOID)(ref id)).ID);
		}

		public Vector3 GetVector(int hash, Vector3 defautlValue)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (!Vecs.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public void Set(int hash, Vector3 value)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Vecs[hash] = value;
		}

		public Quaternion GetQuaternion(int hash, Quaternion defautlValue)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (!Quats.TryGetValue(hash, out var value))
			{
				return defautlValue;
			}
			return value;
		}

		public void Set(int hash, Quaternion value)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			Quats[hash] = value;
		}

		public byte[] GetByteArray(int hash, byte[] defautlValue)
		{
			if (!ByteArrays.TryGetValue(hash, out byte[] value))
			{
				return defautlValue;
			}
			return value;
		}

		public void Set(int hash, byte[] value)
		{
			ByteArrays[hash] = value;
		}

		public ZPackage Save()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			Vecs.Remove(Hash.Scale);
			Vecs.Remove(Hash.SpawnPoint);
			if (Strings.ContainsKey(Hash.OverrideItems))
			{
				Ints.Remove(Hash.AddedDefaultItems);
				Strings.Remove(Hash.Items);
			}
			int num = 0;
			if (Floats.Count > 0)
			{
				num |= 1;
			}
			if (Vecs.Count > 0)
			{
				num |= 2;
			}
			if (Quats.Count > 0)
			{
				num |= 4;
			}
			if (Ints.Count > 0)
			{
				num |= 8;
			}
			if (Strings.Count > 0)
			{
				num |= 0x10;
			}
			if (Longs.Count > 0)
			{
				num |= 0x40;
			}
			if (ByteArrays.Count > 0)
			{
				num |= 0x80;
			}
			val.Write(num);
			if (Floats.Count > 0)
			{
				val.Write((byte)Floats.Count);
				foreach (KeyValuePair<int, float> @float in Floats)
				{
					val.Write(@float.Key);
					val.Write(@float.Value);
				}
			}
			if (Vecs.Count > 0)
			{
				val.Write((byte)Vecs.Count);
				foreach (KeyValuePair<int, Vector3> vec in Vecs)
				{
					val.Write(vec.Key);
					val.Write(vec.Value);
				}
			}
			if (Quats.Count > 0)
			{
				val.Write((byte)Quats.Count);
				foreach (KeyValuePair<int, Quaternion> quat in Quats)
				{
					val.Write(quat.Key);
					val.Write(quat.Value);
				}
			}
			if (Ints.Count > 0)
			{
				val.Write((byte)Ints.Count);
				foreach (KeyValuePair<int, int> @int in Ints)
				{
					val.Write(@int.Key);
					val.Write(@int.Value);
				}
			}
			if (Longs.Count > 0)
			{
				val.Write((byte)Longs.Count);
				foreach (KeyValuePair<int, long> @long in Longs)
				{
					val.Write(@long.Key);
					val.Write(@long.Value);
				}
			}
			if (Strings.Count > 0)
			{
				val.Write((byte)Strings.Count);
				foreach (KeyValuePair<int, string> @string in Strings)
				{
					val.Write(@string.Key);
					val.Write(@string.Value);
				}
			}
			if (ByteArrays.Count > 0)
			{
				val.Write((byte)ByteArrays.Count);
				foreach (KeyValuePair<int, byte[]> byteArray in ByteArrays)
				{
					val.Write(byteArray.Key);
					val.Write(byteArray.Value);
				}
			}
			return val;
		}

		public void Load(ZPackage pkg)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			pkg.SetPos(0);
			int num = pkg.ReadInt();
			if (((uint)num & (true ? 1u : 0u)) != 0)
			{
				byte b = pkg.ReadByte();
				for (int i = 0; i < b; i++)
				{
					Floats[pkg.ReadInt()] = pkg.ReadSingle();
				}
			}
			if (((uint)num & 2u) != 0)
			{
				byte b2 = pkg.ReadByte();
				for (int j = 0; j < b2; j++)
				{
					Vecs[pkg.ReadInt()] = pkg.ReadVector3();
				}
			}
			if (((uint)num & 4u) != 0)
			{
				byte b3 = pkg.ReadByte();
				for (int k = 0; k < b3; k++)
				{
					Quats[pkg.ReadInt()] = pkg.ReadQuaternion();
				}
			}
			if (((uint)num & 8u) != 0)
			{
				byte b4 = pkg.ReadByte();
				for (int l = 0; l < b4; l++)
				{
					Ints[pkg.ReadInt()] = pkg.ReadInt();
				}
			}
			if (((uint)num & 0x40u) != 0)
			{
				byte b5 = pkg.ReadByte();
				for (int m = 0; m < b5; m++)
				{
					Longs[pkg.ReadInt()] = pkg.ReadLong();
				}
			}
			if (((uint)num & 0x10u) != 0)
			{
				byte b6 = pkg.ReadByte();
				for (int n = 0; n < b6; n++)
				{
					Strings[pkg.ReadInt()] = pkg.ReadString();
				}
			}
			if (((uint)num & 0x80u) != 0)
			{
				byte b7 = pkg.ReadByte();
				for (int num2 = 0; num2 < b7; num2++)
				{
					ByteArrays[pkg.ReadInt()] = pkg.ReadByteArray();
				}
			}
		}
	}
}
namespace WorldEditCommands
{
	public static class Actions
	{
		private static Dictionary<string, int> IdToHash = new Dictionary<string, int>();

		private static Dictionary<string, int> LowerIdToHash = new Dictionary<string, int>();

		private const string DEFAULT = "default";

		public static bool? ToggleBool(ZNetView obj, bool? value, int hash)
		{
			bool @bool = obj.GetZDO().GetBool(hash, false);
			bool flag = value ?? (!@bool);
			obj.GetZDO().Set(hash, flag);
			return flag;
		}

		public static GameObject Refresh(ZDO zdo)
		{
			GameObject gameObject = ((Component)ZNetScene.instance.m_instances[zdo]).gameObject;
			if (!Object.op_Implicit((Object)(object)gameObject))
			{
				return gameObject;
			}
			Object.Destroy((Object)(object)gameObject);
			GameObject val = ZNetScene.instance.CreateObject(zdo);
			ZNetScene.instance.m_instances[zdo] = val.GetComponent<ZNetView>();
			return val;
		}

		public static GameObject Refresh(ZNetView view)
		{
			return Refresh(view.GetZDO());
		}

		public static void SetFloat(ZNetView obj, float? value, int hash, bool refresh = false)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.GetZDO().Set(hash, value ?? (-1f));
				if (refresh)
				{
					Refresh(obj);
				}
			}
		}

		public static void SetInt(ZNetView obj, int? value, int hash, bool refresh = false)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.GetZDO().Set(hash, value ?? (-1), false);
				if (refresh)
				{
					Refresh(obj);
				}
			}
		}

		public static void SetLong(ZNetView obj, long? value, int hash, bool refresh = false)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.GetZDO().Set(hash, value ?? (-1));
				if (refresh)
				{
					Refresh(obj);
				}
			}
		}

		public static int GetId(string id)
		{
			if (IdToHash.Count == 0)
			{
				IdToHash = ZNetScene.instance.m_namedPrefabs.ToDictionary((KeyValuePair<int, GameObject> kvp) => ((Object)kvp.Value).name, (KeyValuePair<int, GameObject> kvp) => kvp.Key);
			}
			if (LowerIdToHash.Count == 0)
			{
				LowerIdToHash = ZNetScene.instance.m_namedPrefabs.ToLookup((KeyValuePair<int, GameObject> kvp) => ((Object)kvp.Value).name.ToLower(), (KeyValuePair<int, GameObject> kvp) => kvp.Key).ToDictionary((IGrouping<string, int> kvp) => kvp.Key, (IGrouping<string, int> kvp) => kvp.FirstOrDefault());
			}
			if (IdToHash.TryGetValue(id, out var value))
			{
				return value;
			}
			if (LowerIdToHash.TryGetValue(id.ToLower(), out var value2))
			{
				return value2;
			}
			return StringExtensionMethods.GetStableHashCode(id);
		}

		public static void SetPrefab(ZNetView obj, string? value, int hash, bool refresh = false)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.GetZDO().Set(hash, (value == null) ? "" : value);
				if (refresh)
				{
					Refresh(obj);
				}
			}
		}

		public static void SetString(ZNetView obj, string? value, int hash, bool refresh = false)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.GetZDO().Set(hash, value ?? "");
				if (refresh)
				{
					Refresh(obj);
				}
			}
		}

		public static void SetTame(GameObject obj, bool tame)
		{
			SetTame(obj.GetComponent<Character>(), tame);
		}

		public static void SetTame(Character obj, bool tame)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return;
			}
			obj.SetTamed(tame);
			BaseAI component = ((Component)obj).GetComponent<BaseAI>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			component.SetAlerted(false);
			if (tame)
			{
				SetHunt(component, hunt: false);
				component.SetPatrolPoint();
			}
			component.SetTargetInfo(ZDOID.None);
			MonsterAI component2 = ((Component)obj).GetComponent<MonsterAI>();
			if (Object.op_Implicit((Object)(object)component2))
			{
				component2.m_targetCreature = null;
				component2.m_targetStatic = null;
				if (tame)
				{
					component2.SetDespawnInDay(false);
					component2.SetEventCreature(false);
				}
			}
			AnimalAI component3 = ((Component)obj).GetComponent<AnimalAI>();
			if (Object.op_Implicit((Object)(object)component3))
			{
				component3.m_target = null;
			}
		}

		public static void SetHunt(GameObject obj, bool hunt)
		{
			SetHunt(obj.GetComponent<BaseAI>(), hunt);
		}

		public static bool SetPrefab(ZNetView obj, string prefab)
		{
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return false;
			}
			ZDO zDO = obj.GetZDO();
			if (zDO == null || !zDO.IsValid())
			{
				return false;
			}
			int prefab2 = zDO.GetPrefab();
			zDO.SetPrefab(StringExtensionMethods.GetStableHashCode(prefab));
			GameObject val = ZNetScene.instance.CreateObject(zDO);
			if (!Object.op_Implicit((Object)(object)val))
			{
				zDO.SetPrefab(prefab2);
				return false;
			}
			Object.Destroy((Object)(object)((Component)obj).gameObject);
			ZNetScene.instance.m_instances[zDO] = val.GetComponent<ZNetView>();
			return true;
		}

		public static void SetHunt(BaseAI obj, bool hunt)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.m_huntPlayer = hunt;
				obj.m_nview.GetZDO().Set(Hash.HuntPlayer, hunt);
			}
		}

		public static void SetFuel(ZNetView view, float amount)
		{
			if (Object.op_Implicit((Object)(object)view))
			{
				view.GetZDO().Set(Hash.Fuel, amount);
			}
		}

		public static void SetSleeping(GameObject obj, bool sleep)
		{
			SetSleeping(obj.GetComponent<MonsterAI>(), sleep);
		}

		public static void SetSleeping(MonsterAI obj, bool sleep)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.m_sleeping = sleep;
				((BaseAI)obj).m_nview.GetZDO().Set(Hash.Sleeping, sleep);
				((BaseAI)obj).m_animator.SetBool("sleeping", sleep);
			}
		}

		public static void SetBaby(GameObject obj)
		{
			SetBaby(obj.GetComponent<Growup>());
		}

		public static void SetBaby(Growup obj)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				ZNetView component = ((Component)obj).GetComponent<ZNetView>();
				if (component != null)
				{
					ZDO zDO = component.GetZDO();
					int spawnTime = Hash.SpawnTime;
					DateTime maxValue = DateTime.MaxValue;
					zDO.Set(spawnTime, maxValue.Ticks);
				}
			}
		}

		public static void SetLevel(GameObject obj, int level)
		{
			if (level >= 1)
			{
				SetLevel(obj.GetComponent<ItemDrop>(), level);
				SetLevel(obj.GetComponent<Character>(), level);
			}
		}

		public static void SetLevel(Character obj, int level)
		{
			if (Object.op_Implicit((Object)(object)obj) && obj.GetLevel() != level)
			{
				obj.SetLevel(level);
			}
		}

		public static void SetLevel(ItemDrop obj, int level)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.m_itemData.m_quality = level;
				obj.m_nview.GetZDO().Set(Hash.Quality, level, false);
			}
		}

		public static float GetHealth(ZNetView obj)
		{
			ZDO zDO = obj.GetZDO();
			ItemDrop component = ((Component)obj).GetComponent<ItemDrop>();
			if (Object.op_Implicit((Object)(object)component))
			{
				return component.m_itemData.m_durability;
			}
			Character component2 = ((Component)obj).GetComponent<Character>();
			if (Object.op_Implicit((Object)(object)component2))
			{
				return component2.GetHealth();
			}
			WearNTear component3 = ((Component)obj).GetComponent<WearNTear>();
			if (Object.op_Implicit((Object)(object)component3))
			{
				return zDO.GetFloat(Hash.Health, component3.m_health);
			}
			Destructible component4 = ((Component)obj).GetComponent<Destructible>();
			if (Object.op_Implicit((Object)(object)component4))
			{
				return zDO.GetFloat(Hash.Health, component4.m_health);
			}
			TreeLog component5 = ((Component)obj).GetComponent<TreeLog>();
			if (Object.op_Implicit((Object)(object)component5))
			{
				return zDO.GetFloat(Hash.Health, component5.m_health);
			}
			TreeBase component6 = ((Component)obj).GetComponent<TreeBase>();
			if (Object.op_Implicit((Object)(object)component6))
			{
				return zDO.GetFloat(Hash.Health, component6.m_health);
			}
			return -1f;
		}

		public static float SetHealth(GameObject obj, float health, bool isPercentage)
		{
			ItemDrop component = obj.GetComponent<ItemDrop>();
			if (Object.op_Implicit((Object)(object)component))
			{
				return SetHealth(component, health, isPercentage);
			}
			Character component2 = obj.GetComponent<Character>();
			if (Object.op_Implicit((Object)(object)component2))
			{
				return SetHealth(component2, health, isPercentage);
			}
			WearNTear component3 = obj.GetComponent<WearNTear>();
			if (Object.op_Implicit((Object)(object)component3))
			{
				return SetHealth(component3, health, isPercentage);
			}
			TreeLog component4 = obj.GetComponent<TreeLog>();
			if (Object.op_Implicit((Object)(object)component4))
			{
				return SetHealth(component4, health, isPercentage);
			}
			TreeBase component5 = obj.GetComponent<TreeBase>();
			if (Object.op_Implicit((Object)(object)component5))
			{
				return SetHealth(component5, health, isPercentage);
			}
			Destructible component6 = obj.GetComponent<Destructible>();
			if (Object.op_Implicit((Object)(object)component6))
			{
				return SetHealth(component6, health, isPercentage);
			}
			return 0f;
		}

		public static float SetHealth(Character obj, float health, bool isPercentage)
		{
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return 0f;
			}
			if (isPercentage)
			{
				health *= obj.GetMaxHealth();
			}
			float maxHealth = obj.GetMaxHealth();
			if (health == 0f)
			{
				obj.SetupMaxHealth();
				return maxHealth;
			}
			obj.SetMaxHealth(health);
			obj.SetHealth(health * 1.000001f);
			return maxHealth;
		}

		public static float SetHealth(WearNTear obj, float health, bool isPercentage)
		{
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return 0f;
			}
			if (isPercentage)
			{
				health *= obj.m_health;
			}
			if (health == 0f)
			{
				health = obj.m_health;
			}
			float @float = obj.m_nview.GetZDO().GetFloat(Hash.Health, obj.m_health);
			obj.m_nview.GetZDO().Set(Hash.Health, health);
			return @float;
		}

		public static float SetHealth(TreeLog obj, float health, bool isPercentage)
		{
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return 0f;
			}
			if (isPercentage)
			{
				health *= obj.m_health;
			}
			if (health == 0f)
			{
				health = obj.m_health;
			}
			float @float = obj.m_nview.GetZDO().GetFloat(Hash.Health, obj.m_health);
			obj.m_nview.GetZDO().Set(Hash.Health, health);
			return @float;
		}

		public static float SetHealth(Destructible obj, float health, bool isPercentage)
		{
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return 0f;
			}
			if (isPercentage)
			{
				health *= obj.m_health;
			}
			if (health == 0f)
			{
				health = obj.m_health;
			}
			float @float = obj.m_nview.GetZDO().GetFloat(Hash.Health, obj.m_health);
			obj.m_nview.GetZDO().Set(Hash.Health, health);
			return @float;
		}

		public static float SetHealth(TreeBase obj, float health, bool isPercentage)
		{
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return 0f;
			}
			if (isPercentage)
			{
				health *= obj.m_health;
			}
			if (health == 0f)
			{
				health = obj.m_health;
			}
			float @float = obj.m_nview.GetZDO().GetFloat(Hash.Health, obj.m_health);
			obj.m_nview.GetZDO().Set(Hash.Health, health);
			return @float;
		}

		public static float SetHealth(ItemDrop obj, float health, bool isPercentage)
		{
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return 0f;
			}
			float durability = obj.m_itemData.m_durability;
			if (isPercentage)
			{
				health *= obj.m_itemData.GetMaxDurability();
			}
			if (health == 0f)
			{
				health = obj.m_itemData.GetMaxDurability();
			}
			obj.m_itemData.m_durability = health;
			obj.m_nview.GetZDO().Set(Hash.Durability, obj.m_itemData.m_durability);
			return durability;
		}

		public static float SetCreator(ZNetView obj, long creator)
		{
			Piece obj2 = default(Piece);
			if (((Component)obj).TryGetComponent<Piece>(ref obj2))
			{
				return SetCreator(obj2, creator);
			}
			return 0f;
		}

		public static long SetCreator(Piece obj, long creator)
		{
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return 0L;
			}
			long creator2 = obj.GetCreator();
			obj.m_creator = creator;
			obj.m_nview.GetZDO().Set(Hash.Creator, creator);
			return creator2;
		}

		public static void SetVariant(GameObject obj, int variant)
		{
			SetVariant(obj.GetComponent<ItemDrop>(), variant);
		}

		public static void SetVariant(ItemDrop obj, int variant)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.m_itemData.m_variant = variant;
				obj.m_nview.GetZDO().Set(Hash.Variant, variant, false);
			}
		}

		public static void SetName(GameObject obj, string name)
		{
			SetName(obj.GetComponent<Tameable>(), name);
			SetName(obj.GetComponent<ItemDrop>(), name);
		}

		public static void SetName(Tameable obj, string name)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.m_nview.GetZDO().Set(Hash.TamedName, name);
			}
		}

		public static void SetCrafterId(ItemDrop obj, long id)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.m_itemData.m_crafterID = id;
				obj.m_nview.GetZDO().Set(Hash.CrafterID, obj.m_itemData.m_crafterID);
			}
		}

		public static void SetName(ItemDrop obj, string name)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.m_itemData.m_crafterID = ((!(name == "")) ? (-1) : 0);
				obj.m_nview.GetZDO().Set(Hash.CrafterID, obj.m_itemData.m_crafterID);
				obj.m_itemData.m_crafterName = name;
				obj.m_nview.GetZDO().Set(Hash.CrafterName, name);
			}
		}

		public static int SetStack(GameObject obj, int remaining)
		{
			if (remaining <= 0)
			{
				return 0;
			}
			ItemDrop component = obj.GetComponent<ItemDrop>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return 0;
			}
			int num = Math.Min(remaining, component.m_itemData.m_shared.m_maxStackSize);
			component.m_itemData.m_stack = num;
			component.m_nview.GetZDO().Set(Hash.Stack, num, false);
			return num;
		}

		public static void SetRotation(GameObject obj, Quaternion rotation)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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)
			ZNetView component = obj.GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && rotation != Quaternion.identity)
			{
				component.GetZDO().SetRotation(rotation);
				obj.transform.rotation = rotation;
			}
		}

		public static void SetScale(GameObject obj, Vector3 scale)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			ZNetView component = obj.GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && scale != Vector3.one && component.m_syncInitialScale)
			{
				component.SetLocalScale(scale);
			}
		}

		public static void Respawn(GameObject obj)
		{
			Respawn(obj.GetComponent<Container>());
			Respawn(obj.GetComponent<Pickable>());
			Respawn(obj.GetComponent<CreatureSpawner>());
		}

		public static void Respawn(Container obj)
		{
			if (Object.op_Implicit((Object)(object)obj) && obj.m_defaultItems.m_drops.Count != 0)
			{
				Inventory inventory = obj.m_inventory;
				if (inventory != null)
				{
					inventory.RemoveAll();
				}
				obj.AddDefaultItems();
			}
		}

		public static bool CanRespawn(GameObject obj)
		{
			if (!Object.op_Implicit((Object)(object)obj.GetComponent<Pickable>()) && !Object.op_Implicit((Object)(object)obj.GetComponent<CreatureSpawner>()))
			{
				Container component = obj.GetComponent<Container>();
				if (component == null)
				{
					return false;
				}
				return component.m_defaultItems.m_drops.Count > 0;
			}
			return true;
		}

		public static void Respawn(Pickable obj)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.SetPicked(false);
			}
		}

		public static void Respawn(CreatureSpawner obj)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)obj))
			{
				return;
			}
			ZNetView nview = obj.m_nview;
			ZDO val = ((nview != null) ? nview.GetZDO() : null);
			if (val == null)
			{
				return;
			}
			ZDOID connectionZDOID = val.GetConnectionZDOID((ConnectionType)3);
			if (!((ZDOID)(ref connectionZDOID)).IsNone())
			{
				if (ZDOMan.instance.m_objectsByID.TryGetValue(connectionZDOID, out var value))
				{
					RemoveZDO(value);
				}
				ZDOExtraData.ReleaseConnection(val.m_uid);
				val.Set(ZDOVars.s_aliveTime, 0, false);
			}
		}

		public static void SetModel(GameObject obj, int index)
		{
			SetModel(obj.GetComponent<Character>(), index);
		}

		public static void SetModel(Character obj, int index)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				VisEquipment component = ((Component)obj).GetComponent<VisEquipment>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.SetModel(index);
				}
			}
		}

		public static void SetVisual(GameObject obj, Item item)
		{
			SetVisual(obj.GetComponent<ItemStand>(), item);
		}

		public static void SetVisual(GameObject obj, VisSlot slot, Item? item)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			SetVisual(obj.GetComponent<Character>(), slot, item);
		}

		public static void SetVisual(ItemStand obj, Item? item)
		{
			if (Object.op_Implicit((Object)(object)obj) && item != null)
			{
				obj.m_nview.GetZDO().Set(Hash.Item, item.Name);
				obj.m_nview.GetZDO().Set(Hash.Variant, item.Variant, false);
				obj.UpdateVisual();
			}
		}

		public static void SetVisual(Character obj, VisSlot slot, Item? item)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)obj) && item != null)
			{
				VisEquipment component = ((Component)obj).GetComponent<VisEquipment>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.SetItem(slot, item.Name, item.Variant);
				}
			}
		}

		public static void Move(ZNetView obj, Vector3 offset, string origin)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = obj.GetZDO();
			Vector3 position = ((Component)obj).transform.position;
			Quaternion val = ((Component)Player.m_localPlayer).transform.rotation;
			if (origin == "world")
			{
				val = Quaternion.identity;
			}
			if (origin == "object")
			{
				val = ((Component)obj).transform.rotation;
			}
			position += val * Vector3.right * offset.x;
			position += val * Vector3.up * offset.y;
			position += val * Vector3.forward * offset.z;
			zDO.SetPosition(position);
			((Component)obj).transform.position = position;
		}

		public static void Rotate(ZNetView obj, Vector3 relative, string origin, Vector3? center = null)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = obj.GetZDO();
			Quaternion val = ((Component)Player.m_localPlayer).transform.rotation;
			if (origin == "world")
			{
				val = Quaternion.identity;
			}
			if (origin == "object")
			{
				val = ((Component)obj).transform.rotation;
			}
			Transform transform = ((Component)obj).transform;
			Vector3 val2 = (Vector3)(((??)center) ?? transform.position);
			transform.RotateAround(val2, val * Vector3.up, relative.y);
			transform.RotateAround(val2, val * Vector3.forward, relative.x);
			transform.RotateAround(val2, val * Vector3.right, relative.z);
			zDO.SetRotation(((Component)obj).transform.rotation);
		}

		public static void Mirror(ZNetView obj, Vector3 center)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)obj).transform;
			transform.position = new Vector3(2f * center.x - transform.position.x, transform.position.y, transform.position.z);
			Vector3 eulerAngles = transform.eulerAngles;
			transform.rotation = Quaternion.Euler(eulerAngles.x, 0f - eulerAngles.y, eulerAngles.z);
			ZDO zDO = obj.GetZDO();
			zDO.SetPosition(transform.position);
			zDO.SetRotation(transform.rotation);
		}

		public static void ResetRotation(ZNetView obj)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			obj.GetZDO().SetRotation(Quaternion.identity);
			((Component)obj).transform.rotation = Quaternion.identity;
		}

		public static void Scale(ZNetView obj, Vector3 scale)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (obj.m_syncInitialScale)
			{
				obj.SetLocalScale(scale);
			}
		}

		public static void RemoveZDO(ZDO zdo)
		{
			if (zdo != null && zdo.IsValid())
			{
				if (!zdo.IsOwner())
				{
					zdo.SetOwner(ZDOMan.GetSessionID());
				}
				if (ZNetScene.instance.m_instances.TryGetValue(zdo, out var value))
				{
					ZNetScene.instance.Destroy(((Component)value).gameObject);
				}
				else
				{
					ZDOMan.instance.DestroyZDO(zdo);
				}
			}
		}

		private static string Print<T>(T? value)
		{
			if (value != null)
			{
				return value.ToString();
			}
			return "default";
		}

		public static string Damage(ZNetView view, float? value)
		{
			if (!Object.op_Implicit((Object)(object)((Component)view).GetComponent<Character>()))
			{
				return "Skipped: ¤ is not a creature.";
			}
			SetFloat(view, value ?? 1f, Hash.Damage);
			return "¤ damage set to " + Print(value) + ".";
		}

		public static string Ammo(ZNetView view, int? value)
		{
			if (!Object.op_Implicit((Object)(object)((Component)view).GetComponent<Turret>()))
			{
				return "Skipped: ¤ is not a turret.";
			}
			SetInt(view, value.GetValueOrDefault(), Hash.Ammo);
			return "¤ ammo set to " + Print(value) + ".";
		}

		public static string AmmoType(ZNetView view, string? value)
		{
			if (!Object.op_Implicit((Object)(object)((Component)view).GetComponent<Turret>()))
			{
				return "Skipped: ¤ is not a turret.";
			}
			SetString(view, value ?? "", Hash.AmmoType);
			return "¤ ammo type set to " + Print(value) + ".";
		}
	}
	public class AliasesCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__0_0;

			public static Func<int, List<string>> <>9__0_1;

			internal void <.ctor>b__0_0(ConsoleEventArgs args)
			{
				string substitution = Settings.Substitution;
				if (args.Length > 1 && args[1] == "clear")
				{
					args.Context.TryRunCommand("alias move", false, false);
					args.Context.TryRunCommand("alias rotate", false, false);
					args.Context.TryRunCommand("alias scal", false, false);
					args.Context.TryRunCommand("alias stars", false, false);
					args.Context.TryRunCommand("alias health", false, false);
					args.Context.TryRunCommand("alias remove", false, false);
					args.Context.TryRunCommand("alias change_helmet", false, false);
					args.Context.TryRunCommand("alias change_left", false, false);
					args.Context.TryRunCommand("alias change_right", false, false);
					args.Context.TryRunCommand("alias change_legs", false, false);
					args.Context.TryRunCommand("alias change_chest", false, false);
					args.Context.TryRunCommand("alias change_shoulders", false, false);
					args.Context.TryRunCommand("alias change_utility", false, false);
					args.Context.TryRunCommand("alias essential", false, false);
					args.Context.TryRunCommand("alias spawn", false, false);
					return;
				}
				args.Context.TryRunCommand("alias move object move=" + substitution + "," + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias rotate object rotate=" + substitution + "," + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias scale object scale=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias stars object stars=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias health object stars=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias remove object remove=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias change_helmet object helmet=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias change_left object left_hand=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias change_right object right_hand=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias change_legs object legs=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias change_chest object chest=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias change_shoulders object shoulders=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias change_utility object utility=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias essential object tame health=1E30 radius=" + substitution + " id=" + substitution, false, false);
				args.Context.TryRunCommand("alias spawn spawn_object " + substitution + " amount=" + substitution + " level=" + substitution, false, false);
			}

			internal List<string> <.ctor>b__0_1(int index)
			{
				if (index == 0)
				{
					return new List<string> { "set", "clear" };
				}
				return ParameterInfo.None;
			}
		}

		public AliasesCommand()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					string substitution = Settings.Substitution;
					if (args.Length > 1 && args[1] == "clear")
					{
						args.Context.TryRunCommand("alias move", false, false);
						args.Context.TryRunCommand("alias rotate", false, false);
						args.Context.TryRunCommand("alias scal", false, false);
						args.Context.TryRunCommand("alias stars", false, false);
						args.Context.TryRunCommand("alias health", false, false);
						args.Context.TryRunCommand("alias remove", false, false);
						args.Context.TryRunCommand("alias change_helmet", false, false);
						args.Context.TryRunCommand("alias change_left", false, false);
						args.Context.TryRunCommand("alias change_right", false, false);
						args.Context.TryRunCommand("alias change_legs", false, false);
						args.Context.TryRunCommand("alias change_chest", false, false);
						args.Context.TryRunCommand("alias change_shoulders", false, false);
						args.Context.TryRunCommand("alias change_utility", false, false);
						args.Context.TryRunCommand("alias essential", false, false);
						args.Context.TryRunCommand("alias spawn", false, false);
					}
					else
					{
						args.Context.TryRunCommand("alias move object move=" + substitution + "," + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias rotate object rotate=" + substitution + "," + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias scale object scale=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias stars object stars=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias health object stars=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias remove object remove=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias change_helmet object helmet=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias change_left object left_hand=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias change_right object right_hand=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias change_legs object legs=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias change_chest object chest=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias change_shoulders object shoulders=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias change_utility object utility=" + substitution + " radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias essential object tame health=1E30 radius=" + substitution + " id=" + substitution, false, false);
						args.Context.TryRunCommand("alias spawn spawn_object " + substitution + " amount=" + substitution + " level=" + substitution, false, false);
					}
				};
				<>c.<>9__0_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("world_edit_aliases", "[set/clear] - Sets some useful aliases.", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			AutoComplete.Register("world_edit_aliases", (Func<int, List<string>>)((int index) => (index == 0) ? new List<string> { "set", "clear" } : ParameterInfo.None));
		}
	}
	public class DungeonCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<ZNetView, bool> <>9__1_2;

			public static ConsoleEvent <>9__1_0;

			internal void <.ctor>b__1_0(ConsoleEventArgs args)
			{
				<>c__DisplayClass1_1 CS$<>8__locals0 = new <>c__DisplayClass1_1
				{
					player = Helper.GetPlayer()
				};
				ZNetView val = (from view in ZNetScene.instance.m_instances.Values
					where Object.op_Implicit((Object)(object)((Component)view).GetComponent<DungeonGenerator>())
					orderby Vector3.Distance(((Component)CS$<>8__locals0.player).transform.position, ((Component)view).transform.position)
					select view).FirstOrDefault();
				if ((Object)(object)val == (Object)null)
				{
					Helper.AddError(args.Context, "No dungeon found.");
				}
				else if (args.Length < 2)
				{
					PrintRooms(val);
				}
			}

			internal bool <.ctor>b__1_2(ZNetView view)
			{
				return Object.op_Implicit((Object)(object)((Component)view).GetComponent<DungeonGenerator>());
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass1_1
		{
			public Player player;

			internal float <.ctor>b__3(ZNetView view)
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				return Vector3.Distance(((Component)player).transform.position, ((Component)view).transform.position);
			}
		}

		public const string Name = "dungeon";

		public DungeonCommand()
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			ObjectAutoComplete autoComplete = new ObjectAutoComplete();
			string text = CommandInfo.Create("Modifies the nearest dungeon.", (IEnumerable<string>)null, (IEnumerable<string>)autoComplete.NamedParameters);
			object obj = <>c.<>9__1_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					Player player = Helper.GetPlayer();
					ZNetView val2 = (from view in ZNetScene.instance.m_instances.Values
						where Object.op_Implicit((Object)(object)((Component)view).GetComponent<DungeonGenerator>())
						orderby Vector3.Distance(((Component)player).transform.position, ((Component)view).transform.position)
						select view).FirstOrDefault();
					if ((Object)(object)val2 == (Object)null)
					{
						Helper.AddError(args.Context, "No dungeon found.");
					}
					else if (args.Length < 2)
					{
						PrintRooms(val2);
					}
				};
				<>c.<>9__1_0 = val;
				obj = (object)val;
			}
			Helper.Command("dungeon", text, (ConsoleEvent)obj, (ConsoleOptionsFetcher)(() => autoComplete.NamedParameters));
		}

		private static RoomData FindRoom(string type)
		{
			string type2 = type;
			return ((IEnumerable<RoomData>)DungeonDB.instance.m_rooms).FirstOrDefault((Func<RoomData, bool>)((RoomData r) => ((Object)r.m_room).name.ToLower() == type2.ToLower())) ?? throw new InvalidOperationException("Can't find room " + type2 + ".");
		}

		private static string EditRoom(ZNetView obj, int i, string type, Vector3 pos, Quaternion rot)
		{
			//IL_002e: 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)
			string text = "room" + i;
			RoomData val = FindRoom(type);
			ZDO zDO = obj.GetZDO();
			zDO.Set(text, ((object)val).GetHashCode());
			zDO.Set(text, pos);
			zDO.Set(text, rot);
			return "";
		}

		private static string PrintRooms(ZNetView obj)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = new List<string>();
			ZDO zDO = obj.GetZDO();
			DungeonGenerator component = ((Component)obj).GetComponent<DungeonGenerator>();
			list.Add($"Dungeon {obj.GetPrefabName()} {component.m_generatedSeed} {Helper.PrintVectorXZY(((Component)obj).transform.position)} {Helper.PrintAngleYXZ(((Component)obj).transform.rotation)}");
			int @int = zDO.GetInt("rooms", 0);
			for (int i = 0; i < @int; i++)
			{
				string text = "room" + i;
				int int2 = zDO.GetInt(text, 0);
				Vector3 vec = zDO.GetVec3(text + "_pos", Vector3.zero);
				Quaternion quaternion = zDO.GetQuaternion(text + "_rot", Quaternion.identity);
				list.Add($"Room {i}: {((Object)DungeonDB.instance.GetRoom(int2).m_room).name} {Helper.PrintVectorXZY(vec)} {Helper.PrintAngleYXZ(quaternion)}");
			}
			return string.Join(", ", list);
		}
	}
	public class ObjectAutoComplete : SharedObjectAutoComplete
	{
		public List<string> NamedParameters;

		public static List<string> ObjectTypes = new List<string> { "creature", "chest", "fireplace", "item", "structure", "spawner", "spawnpoint" };

		public ObjectAutoComplete()
		{
			NamedParameters = SharedObjectAutoComplete.WithSharedParameters(new List<string>
			{
				"wild", "copy", "info", "data", "sleep", "id", "ignore", "move", "rotate", "remove",
				"origin", "visual", "fuel", "prefab", "center", "respawn", "from", "rect", "angle", "creator",
				"chance", "type", "connect", "status"
			});
			AutoComplete.Register("object", (Func<int, List<string>>)((int index) => NamedParameters), SharedObjectAutoComplete.WithSharedFetchers(new Dictionary<string, Func<int, List<string>>>
			{
				{
					"status",
					(int index) => index switch
					{
						0 => ParameterInfo.StatusEffects, 
						1 => ParameterInfo.Create("status=name,<color=yellow>duration</color>,intensity", "Duration in seconds."), 
						2 => ParameterInfo.Create("status=name,duration,<color=yellow>intensity</color>", "Strength of the effect."), 
						_ => ParameterInfo.None, 
					}
				},
				{
					"type",
					(int index) => (index != 0) ? ParameterInfo.None : ObjectTypes
				},
				{
					"connect",
					(int index) => ParameterInfo.Flag("Connect")
				},
				{
					"mirror",
					(int index) => ParameterInfo.Flag("Mirror")
				},
				{
					"respawn",
					(int index) => ParameterInfo.Flag("Respawn")
				},
				{
					"wild",
					(int index) => ParameterInfo.Flag("Wild")
				},
				{
					"remove",
					(int index) => ParameterInfo.Flag("Remove")
				},
				{
					"sleep",
					(int index) => ParameterInfo.Flag("Sleep")
				},
				{
					"info",
					(int index) => ParameterInfo.Flag("info")
				},
				{
					"data",
					(int index) => index switch
					{
						0 => ParameterInfo.Create("data=<color=yellow>key</color> or data=<color=yellow>key,value</color>", "Prints data information. If value is given, sets the data."), 
						1 => ParameterInfo.Create("data=key,<color=yellow>value</color>", "Value to set the data."), 
						_ => ParameterInfo.None, 
					}
				},
				{
					"copy",
					(int index) => (index == 0) ? ParameterInfo.Create("copy or copy=<color=yellow>all</color> or copy=<color=yellow>key1,key2,...</color>", "Prints and copies object data to clipboard. By default excludes some data for better results.") : ParameterInfo.None
				},
				{
					"id",
					(int index) => ParameterInfo.Ids
				},
				{
					"ignore",
					(int index) => ParameterInfo.Ids
				},
				{
					"prefab",
					(int index) => (index != 0) ? ParameterInfo.None : ParameterInfo.ObjectIds
				},
				{
					"fuel",
					(int index) => (index != 0) ? ParameterInfo.None : ParameterInfo.Create("fuel", "number", "Sets or gets the fuel amount.")
				},
				{
					"move",
					(int index) => ParameterInfo.FRU("move", "Movement offset based on the player rotation (unless origin is given)", index)
				},
				{
					"rotate",
					delegate(int index)
					{
						string text = "Rotation based on the player rotation (unless origin is given)";
						return (index == 0) ? ParameterInfo.Create("rotate=<color=yellow>reset</color> or " + ParameterInfo.YawRollPitch("rotate", text, index)[0].Substring(1)) : ParameterInfo.YawRollPitch("rotate", text, index);
					}
				},
				{
					"center",
					(int index) => ParameterInfo.XZY("center", "Overrides the player position. For <color=yellow>rotate</color> sets also the rotation center point.", index)
				},
				{
					"from",
					(int index) => ParameterInfo.XZY("center", "Overrides the player position. For <color=yellow>rotate</color> sets also the rotation center point.", index)
				},
				{
					"visual",
					(int index) => SharedObjectAutoComplete.VisualAutoComplete("visual", index)
				},
				{
					"origin",
					(int index) => (index != 0) ? ParameterInfo.None : ParameterInfo.Origin
				},
				{
					"rect",
					(int index) => index switch
					{
						0 => ParameterInfo.Create("rect=<color=yellow>size</color> or rect=<color=yellow>width</color>,depth", "Area of affected objects."), 
						1 => ParameterInfo.Create("rect=width,<color=yellow>depth</color>", "Area of affected objects."), 
						_ => ParameterInfo.None, 
					}
				},
				{
					"angle",
					(int index) => (index != 0) ? ParameterInfo.None : ParameterInfo.Create("angle=<color=yellow>degrees</color>", "Direction of the rectangle when used with <color=yellow>rect</color>.")
				},
				{
					"circle",
					(int index) => (index != 0) ? ParameterInfo.None : ParameterInfo.Create("circle=<color=yellow>number</color>", "Radius of affected objects.")
				},
				{
					"radius",
					(int index) => (index != 0) ? ParameterInfo.None : ParameterInfo.Create("radius=<color=yellow>number</color>", "Radius of affected objects.")
				},
				{
					"creator",
					(int index) => (index != 0) ? ParameterInfo.None : ParameterInfo.Create("creator=<color=yellow>player ID</color>", "Sets creator of objects (0 for no creator).")
				},
				{
					"chance",
					(int index) => (index != 0) ? ParameterInfo.None : ParameterInfo.Create("chance=<color=yellow>number</color>", "Chance to affect the object (from 0.0 to 1.0).")
				}
			}));
		}
	}
	public class ObjectCommand
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<KeyValuePair<ZDOID, EditData>, EditData> <>9__5_1;

			public static ConsoleEvent <>9__6_0;

			internal EditData <Execute>b__5_1(KeyValuePair<ZDOID, EditData> info)
			{
				return info.Value;
			}

			internal void <.ctor>b__6_0(ConsoleEventArgs args)
			{
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bf: Unknown re

BepInEx/plugins/LVH-IT-UseEquipmentInWater/UseEquipmentInWater.dll

Decompiled 8 months ago
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Use Equipment in Water")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Use Equipment in Water")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("d8653240-2378-4c73-b4af-8f4f12b94862")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Use_Equipment_in_Water;

internal class Items
{
	public List<string> allowAxes = new List<string>(new string[7] { "$item_axe_blackmetal", "$item_axe_bronze", "$item_axe_flint", "$item_axe_iron", "$item_axe_stone", "$item_battleaxe", "$item_battleaxe_crystal" });

	public List<string> allowBows = new List<string>(new string[4] { "$item_bow", "$item_bow_draugrfang", "$item_bow_finewood", "$item_bow_huntsman" });

	public List<string> allowAtgeirs = new List<string>(new string[3] { "$item_atgeir_blackmetal", "$item_atgeir_bronze", "$item_atgeir_iron" });

	public List<string> allowKnives = new List<string>(new string[6] { "$item_knife_blackmetal", "$item_knife_butcher", "$item_knife_chitin", "$item_knife_copper", "$item_knife_flint", "$item_knife_silver" });

	public List<string> allowMaces = new List<string>(new string[4] { "$item_mace_bronze", "$item_mace_iron", "$item_mace_silver", "$item_mace_needle" });

	public List<string> allowShields = new List<string>(new string[12]
	{
		"$item_shield_banded", "$item_shield_blackmetal", "$item_shield_blackmetal_tower", "$item_shield_bronzebuckler", "$item_shield_iron_square", "$item_shield_iron_tower", "$item_shield_serpentscale", "$item_shield_silver", "$item_shield_wood", "$item_shield_woodtower",
		"$item_shield_bonetower", "$item_shield_ironbuckler"
	});

	public List<string> allowSledge = new List<string>(new string[1] { "$item_sledge_iron" });

	public List<string> allowSpears = new List<string>(new string[5] { "$item_spear_bronze", "$item_spear_chitin", "$item_spear_ancientbark", "$item_spear_flint", "$item_spear_wolffang" });

	public List<string> allowSwords = new List<string>(new string[5] { "$item_sword_blackmetal", "$item_sword_bronze", "$item_sword_iron", "$item_sword_fire", "$item_sword_silver" });

	public List<string> allowClub = new List<string>(new string[1] { "$item_club" });

	public List<string> allowTorch = new List<string>(new string[1] { "$item_torch" });

	public List<string> allowPickaxes = new List<string>(new string[4] { "$item_pickaxe_antler", "$item_pickaxe_bronze", "$item_pickaxe_iron", "$item_pickaxe_stone" });

	public List<string> allowCultivator = new List<string>(new string[1] { "$item_cultivator" });

	public List<string> allowFishingRod = new List<string>(new string[1] { "$item_fishingrod" });

	public List<string> allowHammer = new List<string>(new string[1] { "$item_hammer" });

	public List<string> allowHoe = new List<string>(new string[1] { "$item_hoe" });
}
[BepInPlugin("com.lvh-it.valheim.useequipmentinwater", "Use Equipment in Water", "0.2.4")]
[BepInProcess("valheim.exe")]
[BepInProcess("valheim.x86_64")]
internal class UseEquipmentInWater : BaseUnityPlugin
{
	private List<ConfigEntry<bool>> configEntries = new List<ConfigEntry<bool>>();

	private static List<string> deniedItems = new List<string>();

	private Items itemList = new Items();

	private void Awake()
	{
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowAxes", true, "Allow axes to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowBows", true, "Allow bows to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowAtgeirs", true, "Allow atgeirs to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowKnives", true, "Allow knives to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowMaces", true, "Allow maces to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowShields", true, "Allow shields to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowSledge", true, "Allow sledge to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowSpears", true, "Allow spears to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowSwords", true, "Allow swords to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowClub", true, "Allow club to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowTorch", true, "Allow torch to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowPickaxes", true, "Allow pickaxes to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowCultivator", true, "Allow cultivator to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowFishingRod", true, "Allow fishing rod to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowHammer", true, "Allow hammer to be used in Water"));
		configEntries.Add(((BaseUnityPlugin)this).Config.Bind<bool>("ItemsToAllow", "allowHoe", true, "Allow hoe to be used in Water"));
		foreach (ConfigEntry<bool> configEntry in configEntries)
		{
			if (configEntry.Value)
			{
				continue;
			}
			foreach (string item in itemList.GetType().GetField(((ConfigEntryBase)configEntry).Definition.Key).GetValue(itemList) as List<string>)
			{
				deniedItems.Add(item);
			}
		}
		Harmony.CreateAndPatchAll(typeof(UseEquipmentInWater), (string)null);
	}

	[HarmonyPatch(typeof(Character), "IsSwimming")]
	[HarmonyPrefix]
	private static bool patchIsSwim(ref bool __result, Humanoid __instance, float ___m_swimTimer)
	{
		if (___m_swimTimer < 0.5f)
		{
			StackTrace stackTrace = new StackTrace();
			string text = "";
			for (int i = 2; i < stackTrace.FrameCount && i < 10; i++)
			{
				text = text + GeneralExtensions.FullDescription(stackTrace.GetFrame(i).GetMethod()) + "-";
			}
			if (((Character)__instance).IsPlayer() && (text.Contains("UpdateEquipment") || text.Contains("EquipItem")))
			{
				__result = false;
				return false;
			}
		}
		return true;
	}

	[HarmonyPatch(typeof(Humanoid), "EquipItem")]
	[HarmonyPrefix]
	private static void patchEquipItem()
	{
	}

	[HarmonyPatch(typeof(Humanoid), "UpdateEquipment")]
	[HarmonyPrefix]
	private static void patchUpdateEquipment()
	{
	}
}

BepInEx/plugins/makail-ItemDrawers/itemdrawers.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using AuthoritativeConfig;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using SimpleJSON;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Serialization;
using UnityEngine.UI;
using itemdrawers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
public class AssetManager
{
	public static AssetBundle AssetBundle;

	public static Object[] AssetBundleObjects;

	public static UnityAction<ZNetScene> OnSceneAwake;

	public static UnityAction<ObjectDB> OnObjectDBAwake;

	public static void Create(Harmony harmony, string assetBundle)
	{
		harmony.PatchAll(typeof(AssetManager));
		LoadAssetsFromBundle(assetBundle);
	}

	public static void LoadAssetsFromBundle(string bundleName)
	{
		AssetBundle = GetAssetBundleFromResources(bundleName);
		AssetBundleObjects = AssetBundle.LoadAllAssets();
	}

	public static AssetBundle GetAssetBundleFromResources(string fileName)
	{
		Assembly executingAssembly = Assembly.GetExecutingAssembly();
		string name = executingAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith(fileName));
		using Stream stream = executingAssembly.GetManifestResourceStream(name);
		return AssetBundle.LoadFromStream(stream);
	}

	public static IEnumerable<T> GetGameObjects<T>() where T : Component
	{
		Object[] assetBundleObjects = AssetBundleObjects;
		foreach (Object obj in assetBundleObjects)
		{
			GameObject val = (GameObject)(object)((obj is GameObject) ? obj : null);
			if (val != null)
			{
				T component = val.GetComponent<T>();
				if (component != null)
				{
					yield return component;
				}
			}
		}
	}

	public static T GetGameObject<T>(string id) where T : Component
	{
		Object[] assetBundleObjects = AssetBundleObjects;
		foreach (Object obj in assetBundleObjects)
		{
			GameObject val = (GameObject)(object)((obj is GameObject) ? obj : null);
			if (val != null && ((Object)val).name == id)
			{
				T component = val.GetComponent<T>();
				if (component != null)
				{
					return component;
				}
			}
		}
		return default(T);
	}

	public static GameObject GetGameObject(string id)
	{
		Object[] assetBundleObjects = AssetBundleObjects;
		foreach (Object obj in assetBundleObjects)
		{
			GameObject val = (GameObject)(object)((obj is GameObject) ? obj : null);
			if (val != null && ((Object)val).name == id)
			{
				return val;
			}
		}
		return null;
	}

	public static IEnumerable<T> GetAssets<T>()
	{
		Object[] assetBundleObjects = AssetBundleObjects;
		foreach (Object val in assetBundleObjects)
		{
			if (val is T)
			{
				yield return (T)(object)((val is T) ? val : null);
			}
		}
	}

	public static T GetAsset<T>(string name)
	{
		Object[] assetBundleObjects = AssetBundleObjects;
		foreach (Object val in assetBundleObjects)
		{
			if (val.name == name && val is T)
			{
				return (T)(object)((val is T) ? val : null);
			}
		}
		return default(T);
	}

	public static T LoadAsset<T>(string name) where T : Object
	{
		return AssetBundle.LoadAsset<T>(name);
	}

	public static void LoadItems(ObjectDB db)
	{
		IEnumerable<ItemDrop> gameObjects = AssetManager.GetGameObjects<ItemDrop>();
		db.m_items.AddRange(gameObjects.Select((ItemDrop x) => ((Component)x).gameObject));
		db.UpdateItemHashes();
	}

	public static void RegisterRecipes(ObjectDB db)
	{
		db.m_recipes.AddRange(from x in GetAssets<SkyheimRecipe>()
			select x.Convert());
		db.m_recipes.AddRange(GetAssets<Recipe>());
	}

	public static void RegisterStatusEffects(ObjectDB db)
	{
		db.m_StatusEffects.AddRange(GetAssets<StatusEffect>());
	}

	public static void RegisterPieces()
	{
		foreach (SkyheimPieceData gameObject in AssetManager.GetGameObjects<SkyheimPieceData>())
		{
			ItemDrop tool = gameObject.Tool;
			if (tool != null)
			{
				List<GameObject> pieces = tool.m_itemData.m_shared.m_buildPieces.m_pieces;
				if (!pieces.Contains(((Component)gameObject).gameObject))
				{
					gameObject.Convert();
					pieces.Add(((Component)gameObject).gameObject);
				}
			}
		}
	}

	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	[HarmonyPostfix]
	public static void ObjectDB_Awake_Postfix(ObjectDB __instance)
	{
		if ((Object)(object)ZNetScene.instance != (Object)null)
		{
			OnObjectDBAwake?.Invoke(__instance);
			LoadItems(__instance);
			RegisterRecipes(__instance);
			RegisterStatusEffects(__instance);
		}
	}

	[HarmonyPatch(typeof(FejdStartup), "SetupObjectDB")]
	[HarmonyPostfix]
	public static void FejdStartup_SetupObjectDB_Postfix(FejdStartup __instance)
	{
		LoadItems(((Component)__instance).GetComponent<ObjectDB>());
	}

	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	[HarmonyPostfix]
	public static void ZNetScene_Awake_Postfix(ZNetScene __instance)
	{
		foreach (ZNetView gameObject in AssetManager.GetGameObjects<ZNetView>())
		{
			__instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)gameObject).name), ((Component)gameObject).gameObject);
		}
		RegisterPieces();
		OnSceneAwake?.Invoke(__instance);
	}
}
public class AssetType : PropertyAttribute
{
	public Type Type { get; protected set; }

	public AssetType(Type type)
	{
		Type = type;
	}
}
public static class CommonUtils
{
	[Serializable]
	public class SerializableWrapper<T>
	{
		public T Value;

		public SerializableWrapper(T v)
		{
			Value = v;
		}
	}

	public struct DistanceSort : IComparer<Collider>
	{
		private Vector3 _target;

		public DistanceSort(Vector3 target)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			_target = target;
		}

		public int Compare(Collider a, Collider b)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = ((Component)a).transform.position;
			Vector3 position2 = ((Component)b).transform.position;
			return Vector3.Distance(position, _target).CompareTo(Vector3.Distance(position2, _target));
		}
	}

	public static long PlayerID => Game.instance.GetPlayerProfile().GetPlayerID();

	[Conditional("DEBUG")]
	public static void Log(string str)
	{
		Debug.Log((object)str);
	}

	[Conditional("DEBUG")]
	public static void LogFields(object obj)
	{
		FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
		foreach (FieldInfo obj2 in fields)
		{
			_ = obj2.Name;
			obj2.GetValue(obj);
		}
	}

	public static T ConvertPrefabReference<T>(string prefabReference) where T : Component
	{
		if (Object.op_Implicit((Object)(object)ZNetScene.instance) && !string.IsNullOrEmpty(prefabReference))
		{
			GameObject prefab = ZNetScene.instance.GetPrefab(prefabReference);
			if ((Object)(object)prefab != (Object)null)
			{
				return prefab.GetComponent<T>();
			}
		}
		return default(T);
	}

	public static GameObject ConvertPrefabReference(string prefabReference)
	{
		if (Object.op_Implicit((Object)(object)ZNetScene.instance) && !string.IsNullOrEmpty(prefabReference))
		{
			return ZNetScene.instance.GetPrefab(prefabReference);
		}
		return null;
	}

	public static T GetItemComponent<T>(ItemData item) where T : Component
	{
		if (item == null || !Object.op_Implicit((Object)(object)item.m_dropPrefab))
		{
			return default(T);
		}
		return item.m_dropPrefab.GetComponent<T>();
	}

	public static T Clone<T>(T obj)
	{
		return (T)obj.GetType().GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(obj, null);
	}

	public static T Get<T>(this IDictionary dict, string key, T defaultValue = default(T))
	{
		if (dict.Contains(key))
		{
			return (T)Convert.ChangeType(dict[key], typeof(T));
		}
		return defaultValue;
	}

	public static JSONNode ToJSON<T>(T obj)
	{
		Type type = obj.GetType();
		if (obj is IList)
		{
			JSONArray jSONArray = new JSONArray();
			{
				foreach (object item in obj as IList)
				{
					jSONArray.Add(ToJSON(item));
				}
				return jSONArray;
			}
		}
		if (type.IsClass && !(obj is string))
		{
			Type type2 = obj.GetType();
			JSONObject jSONObject = new JSONObject();
			FieldInfo[] fields = type2.GetFields(BindingFlags.Instance | BindingFlags.Public);
			foreach (FieldInfo fieldInfo in fields)
			{
				jSONObject.Add(fieldInfo.Name, ToJSON(fieldInfo.GetValue(obj)));
			}
			return jSONObject;
		}
		return (JSONNode)typeof(JSONNode).GetMethod("op_Implicit", new Type[1] { obj.GetType() }).Invoke(null, new object[1] { obj });
	}
}
public class NameAttribute : PropertyAttribute
{
	public string Name { get; private set; }

	public NameAttribute(string name)
	{
		Name = name;
	}
}
public class PrefabReferenceType : PropertyAttribute
{
	public Type ComponentType { get; protected set; }

	public PrefabReferenceType(Type componentType)
	{
		ComponentType = componentType;
	}
}
public class SkyheimPieceData : MonoBehaviour, ISerializationCallbackReceiver
{
	[Header("Requirements")]
	[SerializeField]
	[PrefabReferenceType(typeof(CraftingStation))]
	[FormerlySerializedAs("m_craftingStation")]
	private string _craftingStation;

	[SerializeField]
	[PrefabReferenceType(typeof(ItemDrop))]
	[FormerlySerializedAs("m_craftingTool")]
	private string _craftingTool;

	[SerializeField]
	[PrefabReferenceType(typeof(Piece))]
	[FormerlySerializedAs("m_template")]
	private string _template;

	[SerializeField]
	[FormerlySerializedAs("m_resources")]
	private List<SkyheimRecipe.SkyheimRequirement> _resources;

	[SerializeField]
	[HideInInspector]
	[FormerlySerializedAs("m_resources_internal")]
	private string _resourcesInternal;

	public ItemDrop Tool => CommonUtils.ConvertPrefabReference<ItemDrop>(_craftingTool);

	public void Convert()
	{
		RuntimeDeserialize();
		Piece component = ((Component)this).GetComponent<Piece>();
		component.m_craftingStation = CommonUtils.ConvertPrefabReference<CraftingStation>(_craftingStation);
		component.m_resources = ((IEnumerable<SkyheimRecipe.SkyheimRequirement>)_resources).Select((Func<SkyheimRecipe.SkyheimRequirement, Requirement>)((SkyheimRecipe.SkyheimRequirement x) => x)).ToArray();
		Piece val = (string.IsNullOrEmpty(_template) ? null : CommonUtils.ConvertPrefabReference<Piece>(_template));
		if (!((Object)(object)val != (Object)null))
		{
			return;
		}
		component.m_placeEffect = val.m_placeEffect;
		WearNTear component2 = ((Component)component).GetComponent<WearNTear>();
		if (Object.op_Implicit((Object)(object)component2))
		{
			WearNTear component3 = ((Component)val).GetComponent<WearNTear>();
			if (component3 != null)
			{
				component2.m_hitEffect = component3.m_hitEffect;
				component2.m_destroyedEffect = component3.m_destroyedEffect;
				component2.m_switchEffect = component3.m_switchEffect;
			}
		}
	}

	public void RuntimeDeserialize()
	{
		_resources = new List<SkyheimRecipe.SkyheimRequirement>();
		JSONNode.Enumerator enumerator = JSONNode.Parse(_resourcesInternal).AsArray.GetEnumerator();
		while (enumerator.MoveNext())
		{
			KeyValuePair<string, JSONNode> current = enumerator.Current;
			_resources.Add(new SkyheimRecipe.SkyheimRequirement(current.Value));
		}
	}

	public void OnBeforeSerialize()
	{
		JSONNode jSONNode = CommonUtils.ToJSON(_resources);
		_resourcesInternal = jSONNode.ToString();
	}

	public void OnAfterDeserialize()
	{
	}
}
[CreateAssetMenu(menuName = "Skyheim/Recipe")]
public class SkyheimRecipe : ScriptableObject, ISerializationCallbackReceiver
{
	[Serializable]
	public class SkyheimRequirement
	{
		[PrefabReferenceType(typeof(ItemDrop))]
		[FormerlySerializedAs("ResItem")]
		public string ResourceItem;

		[FormerlySerializedAs("m_amount")]
		public int Amount = 1;

		[FormerlySerializedAs("m_amountPerLevel")]
		public int AmountPerLevel = 1;

		[FormerlySerializedAs("m_recover")]
		public bool Recover = true;

		public SkyheimRequirement()
		{
		}

		public SkyheimRequirement(JSONNode j)
		{
			ResourceItem = j["ResourceItem"];
			Amount = j["Amount"];
			AmountPerLevel = j["AmountPerLevel"];
			Recover = j["Recover"];
		}

		public static implicit operator Requirement(SkyheimRequirement r)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			return new Requirement
			{
				m_resItem = CommonUtils.ConvertPrefabReference<ItemDrop>(r.ResourceItem),
				m_amount = r.Amount,
				m_amountPerLevel = r.AmountPerLevel,
				m_recover = r.Recover
			};
		}
	}

	[SerializeField]
	[PrefabReferenceType(typeof(ItemDrop))]
	[FormerlySerializedAs("m_item")]
	private string _item;

	[SerializeField]
	[FormerlySerializedAs("m_amount")]
	private int _amount = 1;

	[SerializeField]
	[FormerlySerializedAs("m_enabled")]
	private bool _enabled = true;

	[Header("Requirements")]
	[SerializeField]
	[PrefabReferenceType(typeof(CraftingStation))]
	[FormerlySerializedAs("m_craftingStation")]
	private string _craftingStation;

	[SerializeField]
	[PrefabReferenceType(typeof(CraftingStation))]
	[FormerlySerializedAs("m_repairStation")]
	private string _repairStation;

	[SerializeField]
	[FormerlySerializedAs("m_minStationLevel")]
	private int _minStationLevel = 1;

	[SerializeField]
	[FormerlySerializedAs("m_resources")]
	private List<SkyheimRequirement> _resources;

	[SerializeField]
	[HideInInspector]
	[FormerlySerializedAs("m_resources_internal")]
	private string _resourcesInternal;

	public Recipe Convert()
	{
		RuntimeDeserialize();
		Recipe obj = ScriptableObject.CreateInstance<Recipe>();
		((Object)obj).name = ((Object)this).name;
		obj.m_item = CommonUtils.ConvertPrefabReference<ItemDrop>(_item);
		obj.m_craftingStation = CommonUtils.ConvertPrefabReference<CraftingStation>(_craftingStation);
		obj.m_repairStation = CommonUtils.ConvertPrefabReference<CraftingStation>(_repairStation);
		obj.m_resources = ((IEnumerable<SkyheimRequirement>)_resources).Select((Func<SkyheimRequirement, Requirement>)((SkyheimRequirement x) => x)).ToArray();
		obj.m_amount = _amount;
		obj.m_enabled = _enabled;
		obj.m_minStationLevel = _minStationLevel;
		return obj;
	}

	public void RuntimeDeserialize()
	{
		JSONNode jSONNode = JSONNode.Parse(_resourcesInternal);
		_resources = new List<SkyheimRequirement>();
		JSONNode.Enumerator enumerator = jSONNode.AsArray.GetEnumerator();
		while (enumerator.MoveNext())
		{
			KeyValuePair<string, JSONNode> current = enumerator.Current;
			_resources.Add(new SkyheimRequirement(current.Value));
		}
	}

	public void OnBeforeSerialize()
	{
		JSONNode jSONNode = CommonUtils.ToJSON(_resources);
		_resourcesInternal = jSONNode.ToString();
	}

	public void OnAfterDeserialize()
	{
	}
}
public class DrawerContainer : Container, Hoverable, Interactable
{
	public Image _image;

	public Text _text;

	private const int CurrentVersion = 0;

	private uint? _lastRevision;

	private ZNetView _nview;

	private Piece _piece;

	private ItemData _item;

	private int _quantity;

	private bool _loading;

	private int _pickupDelay = 10;

	private int _pickupMask;

	public void Awake_Drawer()
	{
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Expected O, but got Unknown
		_pickupMask = LayerMask.GetMask(new string[1] { "item" });
		_nview = ((Component)this).GetComponent<ZNetView>();
		_piece = ((Component)this).GetComponent<Piece>();
		((Component)_image).gameObject.SetActive(false);
		if ((Object)(object)_nview != (Object)null && _nview.GetZDO() != null)
		{
			((Object)this).name = $"Container_{_nview.GetZDO().m_uid}";
			base.m_name = "piece_chest_drawer";
			base.m_nview = _nview;
			base.m_inventory = new Inventory(((Object)this).name, (Sprite)null, 1, 1);
			base.m_inventory.m_onChanged = (Action)Delegate.Combine(base.m_inventory.m_onChanged, new Action(OnInventoryChanged));
			_nview.Register<int>("Drop", (Action<long, int>)RPC_Drop);
			_nview.Register<ZDOID>("DropResponse", (Action<long, ZDOID>)RPC_DropResponse);
			_nview.Register("Clear", (Action<long>)RPC_Clear);
			_nview.Register<string, int>("AddItem", (Action<long, string, int>)RPC_AddItem);
			_nview.Register<string, int>("AddItemResponse", (Action<long, string, int>)RPC_AddItemResponse);
			Load();
		}
		WearNTear component = ((Component)this).GetComponent<WearNTear>();
		if (component != null)
		{
			component.m_onDestroyed = (Action)Delegate.Combine(component.m_onDestroyed, new Action(base.OnDestroyed));
		}
		((MonoBehaviour)this).InvokeRepeating("CheckForChanges", 0f, 1f);
	}

	public void SetFontColor(Color fontColor, Color outlineColor, bool outlineEnabled)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		((Graphic)_text).color = fontColor;
		Outline component = ((Component)_text).GetComponent<Outline>();
		((Behaviour)component).enabled = outlineEnabled;
		if (((Behaviour)component).enabled)
		{
			((Shadow)component).effectColor = outlineColor;
		}
	}

	private void RetreiveItems()
	{
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		if (!ItemDrawerPlugin.RetreiveEnabled || _item == null || !Object.op_Implicit((Object)(object)_nview) || !_nview.IsOwner())
		{
			return;
		}
		if (_pickupDelay > 0)
		{
			_pickupDelay--;
			return;
		}
		Collider[] array = Physics.OverlapSphere(((Component)this).transform.position + Vector3.up, ItemDrawerPlugin.RetreiveRadius, _pickupMask);
		foreach (Collider val in array)
		{
			if (!Object.op_Implicit((Object)(object)val.attachedRigidbody))
			{
				continue;
			}
			ItemDrop component = ((Component)val.attachedRigidbody).GetComponent<ItemDrop>();
			if ((Object)(object)component == (Object)null || (Object)(object)component.m_itemData.m_dropPrefab != (Object)(object)_item.m_dropPrefab)
			{
				continue;
			}
			ZNetView component2 = ((Component)component).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component2) && component2.IsValid())
			{
				if (!component.CanPickup(true))
				{
					component.RequestOwn();
					continue;
				}
				AddItem(((Object)component.m_itemData.m_dropPrefab).name, component.m_itemData.m_stack);
				ZNetScene.instance.Destroy(((Component)component).gameObject);
			}
		}
	}

	private void CheckForChanges()
	{
		if (Object.op_Implicit((Object)(object)_nview) && _nview.IsValid())
		{
			Load();
			RetreiveItems();
			UpdateVisuals();
		}
	}

	public string GetHoverName()
	{
		if (!Object.op_Implicit((Object)(object)_piece))
		{
			return string.Empty;
		}
		return Localization.instance.Localize(_piece.m_name);
	}

	public string GetHoverText()
	{
		string text = ((_item != null) ? $"<color=#00FFFF>{_item.m_shared.m_name}</color> x {_quantity}" : "$piece_container_empty");
		if (!ZInput.IsGamepadActive())
		{
			string boundKeyString = ZInput.instance.GetBoundKeyString("drawer_mod_deposit_all", false);
			if (_quantity > 0)
			{
				text += "\n[<color=yellow><b>$KEY_Use</b></color>] Take Stack";
				string boundKeyString2 = ZInput.instance.GetBoundKeyString("drawer_mod_withdraw_one", false);
				text = text + "\n[<color=yellow><b>" + boundKeyString2 + "+$KEY_Use</b></color>] Take One";
			}
			else
			{
				string boundKeyString3 = ZInput.instance.GetBoundKeyString("drawer_mod_clear", false);
				text = text + "\n[<color=yellow><b>" + boundKeyString3 + "+$KEY_Use</b></color>] Clear Item";
			}
			text = text + "\n[<color=yellow><b>" + boundKeyString + "+$KEY_Use</b></color>] Deposit All";
		}
		return Localization.instance.Localize(text);
	}

	public bool Interact(Humanoid user, bool hold, bool alt)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		if (_item == null || (Object)(object)user != (Object)(object)Player.m_localPlayer || !PrivateArea.CheckAccess(((Component)this).transform.position, 0f, true, false))
		{
			return false;
		}
		if (!ZInput.IsGamepadActive())
		{
			return OnKeyboardInteract(Player.m_localPlayer);
		}
		return OnGamepadInteract(Player.m_localPlayer);
	}

	private bool OnGamepadInteract(Player player)
	{
		bool blocking = ((Character)player).m_blocking;
		bool crouchToggled = player.m_crouchToggled;
		return ProcessInputInternal(player, blocking, crouchToggled);
	}

	private bool OnKeyboardInteract(Player player)
	{
		bool button = ZInput.GetButton("drawer_mod_deposit_all");
		bool button2 = ZInput.GetButton((_quantity > 0) ? "drawer_mod_withdraw_one" : "drawer_mod_clear");
		return ProcessInputInternal(player, button, button2);
	}

	private bool ProcessInputInternal(Player player, bool mod0, bool mod1)
	{
		if (mod0)
		{
			return UseItem((Humanoid)(object)player, _item);
		}
		if (mod1 && _quantity <= 0)
		{
			_nview.InvokeRPC("Clear", Array.Empty<object>());
		}
		else if (_quantity > 0)
		{
			_nview.InvokeRPC("Drop", new object[1] { mod1 ? 1 : _item.m_shared.m_maxStackSize });
		}
		return true;
	}

	public bool UseItem(Humanoid user, ItemData item)
	{
		if (item.m_shared.m_maxStackSize <= 1)
		{
			return false;
		}
		if (_item == null || (Object)(object)_item.m_dropPrefab == (Object)(object)item.m_dropPrefab)
		{
			int num = user.GetInventory().CountItems(item.m_shared.m_name, -1, true);
			if (num > 0)
			{
				_nview.InvokeRPC("AddItem", new object[2]
				{
					((Object)item.m_dropPrefab).name,
					num
				});
				return true;
			}
		}
		return false;
	}

	private void UpdateInventory()
	{
		if (base.m_inventory.m_inventory.Count > 0)
		{
			ItemData val = base.m_inventory.m_inventory[0];
			if (val.m_shared.m_name == _item.m_shared.m_name)
			{
				val.m_stack = _quantity;
				val.m_shared.m_maxStackSize = ItemDrawerPlugin.MaxItems;
			}
			else
			{
				_addItem();
			}
		}
		else
		{
			_addItem();
		}
		void _addItem()
		{
			base.m_inventory.m_inventory.Clear();
			ItemData val2 = _item.Clone();
			val2.m_stack = _quantity;
			val2.m_shared = CommonUtils.Clone<SharedData>(val2.m_shared);
			val2.m_shared.m_maxStackSize = ItemDrawerPlugin.MaxItems;
			base.m_inventory.m_inventory.Add(val2);
		}
	}

	private ItemDrop Drop(int quantity)
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		if (_quantity > 0)
		{
			GameObject dropPrefab = _item.m_dropPrefab;
			int num = Mathf.Min(quantity, _quantity);
			_quantity -= num;
			_pickupDelay = 5;
			UpdateInventory();
			Vector3 val = ((Component)this).transform.position + ((Component)this).transform.forward * -0.5f;
			GameObject obj = Object.Instantiate<GameObject>(dropPrefab, val, Quaternion.identity);
			obj.GetComponent<Rigidbody>().velocity = Vector3.up * 4f + ((Component)this).transform.forward * 4f;
			ItemDrop component = obj.GetComponent<ItemDrop>();
			component.SetStack(num);
			return component;
		}
		return null;
	}

	public int AddItem(string name, int stack)
	{
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(name);
		if ((Object)(object)itemPrefab == (Object)null)
		{
			ZLog.Log((object)("Failed to find item prefab " + name));
			return 0;
		}
		ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
		if ((Object)(object)component == (Object)null)
		{
			ZLog.Log((object)("Invalid item " + name));
			return 0;
		}
		if (_item != null && (Object)(object)_item.m_dropPrefab != (Object)(object)itemPrefab)
		{
			ZLog.Log((object)("Cannot add to container " + name));
			return 0;
		}
		stack = Math.Min(stack, ItemDrawerPlugin.MaxItems - _quantity);
		_item = component.m_itemData;
		_item.m_dropPrefab = itemPrefab;
		_item.m_gridPos = Vector2i.zero;
		_quantity += stack;
		UpdateInventory();
		OnContainerChanged();
		return stack;
	}

	private void OnContainerChanged()
	{
		if (!_loading && _nview.IsOwner())
		{
			Save();
		}
	}

	private void OnInventoryChanged()
	{
		if (base.m_inventory.m_inventory.Count > 0)
		{
			ItemData val = base.m_inventory.m_inventory[0];
			int num = _quantity - val.m_stack;
			_quantity = Math.Max(0, _quantity - num);
		}
		else
		{
			_quantity = 0;
		}
		OnContainerChanged();
		UpdateVisuals();
	}

	private void RPC_AddItem(long playerId, string prefabName, int quantity)
	{
		if (_nview.IsOwner())
		{
			int num = AddItem(prefabName, quantity);
			if (num > 0)
			{
				_nview.InvokeRPC(playerId, "AddItemResponse", new object[2] { prefabName, num });
			}
		}
	}

	private void RPC_AddItemResponse(long _, string prefabName, int quantity)
	{
		if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && quantity > 0)
		{
			ItemDrop component = ObjectDB.instance.GetItemPrefab(prefabName).GetComponent<ItemDrop>();
			if (component != null)
			{
				string name = component.m_itemData.m_shared.m_name;
				((Humanoid)Player.m_localPlayer).GetInventory().RemoveItem(name, quantity, -1, true);
			}
		}
	}

	private void RPC_Clear(long _)
	{
		if (_nview.IsOwner() && _item != null)
		{
			Clear();
			OnContainerChanged();
		}
	}

	private void RPC_Drop(long playerId, int quantity)
	{
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		if (_nview.IsOwner() && _item != null)
		{
			ItemDrop val = Drop(quantity);
			if (val != null)
			{
				OnContainerChanged();
				ZDOID uid = val.m_nview.GetZDO().m_uid;
				_nview.InvokeRPC(playerId, "DropResponse", new object[1] { uid });
			}
		}
	}

	private void RPC_DropResponse(long _, ZDOID drop)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = ZNetScene.instance.FindInstance(drop);
		if ((Object)(object)val != (Object)null)
		{
			ItemDrop component = val.GetComponent<ItemDrop>();
			if (!((Object)(object)component == (Object)null) && ((Humanoid)Player.m_localPlayer).GetInventory().AddItem(component.m_itemData))
			{
				((Character)Player.m_localPlayer).ShowPickupMessage(component.m_itemData, component.m_itemData.m_stack);
				ZNetScene.instance.Destroy(val);
			}
		}
	}

	private void UpdateVisuals()
	{
		if ((Object)(object)_image != (Object)null)
		{
			bool flag = _item != null && _item.m_shared.m_icons.Count() > 0;
			((Component)_image).gameObject.SetActive(flag);
			if (flag)
			{
				_image.sprite = _item.m_shared.m_icons[0];
			}
		}
		if ((Object)(object)_text != (Object)null)
		{
			_text.text = ((_quantity > 0) ? _quantity.ToString() : string.Empty);
		}
	}

	private void Clear()
	{
		_quantity = 0;
		_item = null;
		base.m_inventory.m_inventory.Clear();
		UpdateVisuals();
	}

	private void Save()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		ZPackage val = new ZPackage();
		val.Write(0);
		if (_item != null)
		{
			val.Write(((Object)(object)_item.m_dropPrefab == (Object)null) ? "" : ((Object)_item.m_dropPrefab).name);
			val.Write(_quantity);
		}
		else
		{
			val.Write("");
		}
		string @base = val.GetBase64();
		_nview.GetZDO().Set("items", @base);
		_lastRevision = _nview.GetZDO().DataRevision;
		ZDOMan.instance.ForceSendZDO(_nview.GetZDO().m_uid);
	}

	private void Load()
	{
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Expected O, but got Unknown
		if (_nview.GetZDO().DataRevision == _lastRevision && _lastRevision.HasValue)
		{
			return;
		}
		Clear();
		string @string = _nview.GetZDO().GetString("items", "");
		if (!string.IsNullOrEmpty(@string))
		{
			ZPackage val = new ZPackage(@string);
			val.ReadInt();
			string text = val.ReadString();
			if (!string.IsNullOrEmpty(text))
			{
				int stack = val.ReadInt();
				_loading = true;
				AddItem(text, stack);
				_loading = false;
				_lastRevision = _nview.GetZDO().DataRevision;
			}
		}
	}

	public void OnDestroyed_Drawer()
	{
		if (_nview.IsOwner() && _item != null)
		{
			while (_quantity > 0 && Object.op_Implicit((Object)(object)Drop(_item.m_shared.m_maxStackSize)))
			{
			}
		}
	}
}
namespace itemdrawers
{
	[BepInPlugin("mkz.itemdrawers", "Item Drawers", "0.5.6")]
	public class ItemDrawerPlugin : BaseUnityPlugin
	{
		public static ItemDrawerPlugin Instance;

		private Harmony _harmony;

		private static ConfigEntry<bool> _retreiveEnabled;

		private static ConfigEntry<float> _retreiveRadius;

		private static ConfigEntry<bool> _enabled;

		private static ConfigEntry<int> _maxItems;

		private static ConfigEntry<Color> _configFontColor;

		private static ConfigEntry<Color> _configOutlineColor;

		private static ConfigEntry<bool> _configOutlineEnabled;

		private static ConfigEntry<string> _configKeyDepositAll;

		private static ConfigEntry<string> _configKeyWithdrawOne;

		private static ConfigEntry<string> _configKeyClear;

		public const string KeyDepositAll = "drawer_mod_deposit_all";

		public const string KeyWithdrawOne = "drawer_mod_withdraw_one";

		public const string KeyClear = "drawer_mod_clear";

		public static float RetreiveRadius => _retreiveRadius.Value;

		public static bool RetreiveEnabled => _retreiveEnabled.Value;

		public static bool Enabled => _enabled.Value;

		public static int MaxItems => _maxItems.Value;

		public static bool OutlineEnabled => _configOutlineEnabled.Value;

		public static Color OutlineColor => _configOutlineColor.Value;

		public static Color FontColor => _configFontColor.Value;

		private Config AuthoritativeConfig => Config.Instance;

		public void Awake()
		{
			Instance = this;
			_harmony = Harmony.CreateAndPatchAll(typeof(ItemDrawerPlugin), (string)null);
			AssetManager.Create(_harmony, "itemdrawers");
			LoadConfig();
		}

		public void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchAll((string)null);
			}
		}

		[HarmonyPatch(typeof(Container), "Awake")]
		[HarmonyPrefix]
		private static bool Container_Awake_Prefix(Container __instance)
		{
			if (__instance is DrawerContainer drawerContainer)
			{
				drawerContainer.Awake_Drawer();
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(Container), "OnDestroyed")]
		[HarmonyPrefix]
		private static bool Container_OnDestroyed_Prefix(Container __instance)
		{
			if (__instance is DrawerContainer drawerContainer)
			{
				drawerContainer.OnDestroyed_Drawer();
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(Container), "Save")]
		[HarmonyPrefix]
		private static bool Container_Save_Prefix(Container __instance)
		{
			return !(__instance is DrawerContainer);
		}

		[HarmonyPatch(typeof(Container), "Load")]
		[HarmonyPrefix]
		private static bool Container_Load_Prefix(Container __instance)
		{
			return !(__instance is DrawerContainer);
		}

		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		[HarmonyPostfix]
		private static void ZNetScene_Awake_Postfix()
		{
			Instance.ApplyConfig();
		}

		[HarmonyPatch(typeof(Player), "IsOverlappingOtherPiece")]
		[HarmonyPostfix]
		private static void Player_IsOverlappingOtherPiece_PostFix(string pieceName, ref bool __result)
		{
			if (pieceName == "piece_drawer")
			{
				__result = false;
			}
		}

		[HarmonyPatch(typeof(ZInput), "Load")]
		[HarmonyPostfix]
		private static void ZInput_Load_PostFix(ZInput __instance)
		{
			//IL_0010: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			__instance.AddButton("drawer_mod_deposit_all", parseKeyConfig(_configKeyDepositAll, (KeyCode)304), 0f, 0f, true, false);
			__instance.AddButton("drawer_mod_withdraw_one", parseKeyConfig(_configKeyWithdrawOne, (KeyCode)308), 0f, 0f, true, false);
			__instance.AddButton("drawer_mod_clear", parseKeyConfig(_configKeyClear, (KeyCode)308), 0f, 0f, true, false);
			static KeyCode parseKeyConfig(ConfigEntry<string> configString, KeyCode @default)
			{
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				if (Enum.TryParse<KeyCode>(configString.Value, out KeyCode result))
				{
					return result;
				}
				return @default;
			}
		}

		private void LoadConfig()
		{
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Expected O, but got Unknown
			AuthoritativeConfig.Init((BaseUnityPlugin)(object)this, defaultBindServerAuthority: true);
			_enabled = AuthoritativeConfig.Bind("General", "Enabled", defaultValue: true, "Enable creation of Item Drawers");
			_maxItems = AuthoritativeConfig.Bind("General", "MaxItems", 9999, "The maximum number of items that can be stored in a drawer");
			_retreiveEnabled = AuthoritativeConfig.Bind("Item Retreival", "Enabled", defaultValue: true, "Drawers will retreive dropped items matching their item");
			_retreiveRadius = AuthoritativeConfig.Bind("Item Retreival", "Radius", 5f, "The distance drawers will check for dropped items");
			_configKeyDepositAll = AuthoritativeConfig.Bind("Hotkeys", "Deposit All", "LeftShift", "Hold while interacting to deposit all", false);
			_configKeyWithdrawOne = AuthoritativeConfig.Bind("Hotkeys", "Withdraw One", "LeftAlt", "Hold while interacting to withdraw one", false);
			_configKeyClear = AuthoritativeConfig.Bind("Hotkeys", "Clear", "LeftAlt", "Hold while interacting to clear contents (only if 0 quantity)", false);
			_configFontColor = AuthoritativeConfig.Bind<Color>("Font", "Color", new Color(1f, 0.5f, 0f), "Drawer font color", false);
			_configOutlineColor = AuthoritativeConfig.Bind<Color>("Font", "Outline Color", new Color(0f, 0f, 0f), "Drawer outline color", false);
			_configOutlineEnabled = AuthoritativeConfig.Bind("Font", "Outline Enabled", defaultValue: true, "Enabled font outline on drawers", false);
			AuthoritativeConfig.OnConfigReceived.AddListener(new UnityAction(ApplyConfig));
		}

		private void ApplyConfig()
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			Piece gameObject = AssetManager.GetGameObject<Piece>("piece_drawer");
			if (gameObject != null)
			{
				gameObject.m_enabled = Enabled;
				DrawerContainer component = ((Component)gameObject).GetComponent<DrawerContainer>();
				component._text.text = MaxItems.ToString();
				component.SetFontColor(_configFontColor.Value, _configOutlineColor.Value, _configOutlineEnabled.Value);
			}
		}
	}
}
namespace SimpleJSON
{
	public enum JSONNodeType
	{
		Array = 1,
		Object = 2,
		String = 3,
		Number = 4,
		NullValue = 5,
		Boolean = 6,
		None = 7,
		Custom = 255
	}
	public enum JSONTextMode
	{
		Compact,
		Indent
	}
	public abstract class JSONNode
	{
		public struct Enumerator
		{
			private enum Type
			{
				None,
				Array,
				Object
			}

			private Type type;

			private Dictionary<string, JSONNode>.Enumerator m_Object;

			private List<JSONNode>.Enumerator m_Array;

			public bool IsValid => type != Type.None;

			public KeyValuePair<string, JSONNode> Current
			{
				get
				{
					if (type == Type.Array)
					{
						return new KeyValuePair<string, JSONNode>(string.Empty, m_Array.Current);
					}
					if (type == Type.Object)
					{
						return m_Object.Current;
					}
					return new KeyValuePair<string, JSONNode>(string.Empty, null);
				}
			}

			public Enumerator(List<JSONNode>.Enumerator aArrayEnum)
			{
				type = Type.Array;
				m_Object = default(Dictionary<string, JSONNode>.Enumerator);
				m_Array = aArrayEnum;
			}

			public Enumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum)
			{
				type = Type.Object;
				m_Object = aDictEnum;
				m_Array = default(List<JSONNode>.Enumerator);
			}

			public bool MoveNext()
			{
				if (type == Type.Array)
				{
					return m_Array.MoveNext();
				}
				if (type == Type.Object)
				{
					return m_Object.MoveNext();
				}
				return false;
			}
		}

		public struct ValueEnumerator
		{
			private Enumerator m_Enumerator;

			public JSONNode Current => m_Enumerator.Current.Value;

			public ValueEnumerator(List<JSONNode>.Enumerator aArrayEnum)
				: this(new Enumerator(aArrayEnum))
			{
			}

			public ValueEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum)
				: this(new Enumerator(aDictEnum))
			{
			}

			public ValueEnumerator(Enumerator aEnumerator)
			{
				m_Enumerator = aEnumerator;
			}

			public bool MoveNext()
			{
				return m_Enumerator.MoveNext();
			}

			public ValueEnumerator GetEnumerator()
			{
				return this;
			}
		}

		public struct KeyEnumerator
		{
			private Enumerator m_Enumerator;

			public string Current => m_Enumerator.Current.Key;

			public KeyEnumerator(List<JSONNode>.Enumerator aArrayEnum)
				: this(new Enumerator(aArrayEnum))
			{
			}

			public KeyEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum)
				: this(new Enumerator(aDictEnum))
			{
			}

			public KeyEnumerator(Enumerator aEnumerator)
			{
				m_Enumerator = aEnumerator;
			}

			public bool MoveNext()
			{
				return m_Enumerator.MoveNext();
			}

			public KeyEnumerator GetEnumerator()
			{
				return this;
			}
		}

		public class LinqEnumerator : IEnumerator<KeyValuePair<string, JSONNode>>, IDisposable, IEnumerator, IEnumerable<KeyValuePair<string, JSONNode>>, IEnumerable
		{
			private JSONNode m_Node;

			private Enumerator m_Enumerator;

			public KeyValuePair<string, JSONNode> Current => m_Enumerator.Current;

			object IEnumerator.Current => m_Enumerator.Current;

			internal LinqEnumerator(JSONNode aNode)
			{
				m_Node = aNode;
				if (m_Node != null)
				{
					m_Enumerator = m_Node.GetEnumerator();
				}
			}

			public bool MoveNext()
			{
				return m_Enumerator.MoveNext();
			}

			public void Dispose()
			{
				m_Node = null;
				m_Enumerator = default(Enumerator);
			}

			public IEnumerator<KeyValuePair<string, JSONNode>> GetEnumerator()
			{
				return new LinqEnumerator(m_Node);
			}

			public void Reset()
			{
				if (m_Node != null)
				{
					m_Enumerator = m_Node.GetEnumerator();
				}
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return new LinqEnumerator(m_Node);
			}
		}

		public static bool forceASCII = false;

		public static bool longAsString = false;

		public static bool allowLineComments = true;

		[ThreadStatic]
		private static StringBuilder m_EscapeBuilder;

		public abstract JSONNodeType Tag { get; }

		public virtual JSONNode this[int aIndex]
		{
			get
			{
				return null;
			}
			set
			{
			}
		}

		public virtual JSONNode this[string aKey]
		{
			get
			{
				return null;
			}
			set
			{
			}
		}

		public virtual string Value
		{
			get
			{
				return "";
			}
			set
			{
			}
		}

		public virtual int Count => 0;

		public virtual bool IsNumber => false;

		public virtual bool IsString => false;

		public virtual bool IsBoolean => false;

		public virtual bool IsNull => false;

		public virtual bool IsArray => false;

		public virtual bool IsObject => false;

		public virtual bool Inline
		{
			get
			{
				return false;
			}
			set
			{
			}
		}

		public virtual IEnumerable<JSONNode> Children
		{
			get
			{
				yield break;
			}
		}

		public IEnumerable<JSONNode> DeepChildren
		{
			get
			{
				foreach (JSONNode child in Children)
				{
					foreach (JSONNode deepChild in child.DeepChildren)
					{
						yield return deepChild;
					}
				}
			}
		}

		public IEnumerable<KeyValuePair<string, JSONNode>> Linq => new LinqEnumerator(this);

		public KeyEnumerator Keys => new KeyEnumerator(GetEnumerator());

		public ValueEnumerator Values => new ValueEnumerator(GetEnumerator());

		public virtual double AsDouble
		{
			get
			{
				double result = 0.0;
				if (double.TryParse(Value, NumberStyles.Float, CultureInfo.InvariantCulture, out result))
				{
					return result;
				}
				return 0.0;
			}
			set
			{
				Value = value.ToString(CultureInfo.InvariantCulture);
			}
		}

		public virtual int AsInt
		{
			get
			{
				return (int)AsDouble;
			}
			set
			{
				AsDouble = value;
			}
		}

		public virtual float AsFloat
		{
			get
			{
				return (float)AsDouble;
			}
			set
			{
				AsDouble = value;
			}
		}

		public virtual bool AsBool
		{
			get
			{
				bool result = false;
				if (bool.TryParse(Value, out result))
				{
					return result;
				}
				return !string.IsNullOrEmpty(Value);
			}
			set
			{
				Value = (value ? "true" : "false");
			}
		}

		public virtual long AsLong
		{
			get
			{
				long result = 0L;
				if (long.TryParse(Value, out result))
				{
					return result;
				}
				return 0L;
			}
			set
			{
				Value = value.ToString();
			}
		}

		public virtual ulong AsULong
		{
			get
			{
				ulong result = 0uL;
				if (ulong.TryParse(Value, out result))
				{
					return result;
				}
				return 0uL;
			}
			set
			{
				Value = value.ToString();
			}
		}

		public virtual JSONArray AsArray => this as JSONArray;

		public virtual JSONObject AsObject => this as JSONObject;

		internal static StringBuilder EscapeBuilder
		{
			get
			{
				if (m_EscapeBuilder == null)
				{
					m_EscapeBuilder = new StringBuilder();
				}
				return m_EscapeBuilder;
			}
		}

		public virtual decimal AsDecimal
		{
			get
			{
				if (!decimal.TryParse(Value, out var result))
				{
					result = default(decimal);
				}
				return result;
			}
			set
			{
				Value = value.ToString();
			}
		}

		public virtual char AsChar
		{
			get
			{
				if (IsString && Value.Length > 0)
				{
					return Value[0];
				}
				if (IsNumber)
				{
					return (char)AsInt;
				}
				return '\0';
			}
			set
			{
				if (IsString)
				{
					Value = value.ToString();
				}
				else if (IsNumber)
				{
					AsInt = value;
				}
			}
		}

		public virtual uint AsUInt
		{
			get
			{
				return (uint)AsDouble;
			}
			set
			{
				AsDouble = value;
			}
		}

		public virtual byte AsByte
		{
			get
			{
				return (byte)AsInt;
			}
			set
			{
				AsInt = value;
			}
		}

		public virtual sbyte AsSByte
		{
			get
			{
				return (sbyte)AsInt;
			}
			set
			{
				AsInt = value;
			}
		}

		public virtual short AsShort
		{
			get
			{
				return (short)AsInt;
			}
			set
			{
				AsInt = value;
			}
		}

		public virtual ushort AsUShort
		{
			get
			{
				return (ushort)AsInt;
			}
			set
			{
				AsInt = value;
			}
		}

		public virtual DateTime AsDateTime
		{
			get
			{
				if (!DateTime.TryParse(Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result))
				{
					result = new DateTime(0L);
				}
				return result;
			}
			set
			{
				Value = value.ToString(CultureInfo.InvariantCulture);
			}
		}

		public virtual TimeSpan AsTimeSpan
		{
			get
			{
				if (!TimeSpan.TryParse(Value, CultureInfo.InvariantCulture, out var result))
				{
					result = new TimeSpan(0L);
				}
				return result;
			}
			set
			{
				Value = value.ToString();
			}
		}

		public virtual Guid AsGuid
		{
			get
			{
				Guid.TryParse(Value, out var result);
				return result;
			}
			set
			{
				Value = value.ToString();
			}
		}

		public virtual byte[] AsByteArray
		{
			get
			{
				if (IsNull || !IsArray)
				{
					return null;
				}
				int count = Count;
				byte[] array = new byte[count];
				for (int i = 0; i < count; i++)
				{
					array[i] = this[i].AsByte;
				}
				return array;
			}
			set
			{
				if (IsArray && value != null)
				{
					Clear();
					for (int i = 0; i < value.Length; i++)
					{
						Add(value[i]);
					}
				}
			}
		}

		public virtual List<byte> AsByteList
		{
			get
			{
				if (IsNull || !IsArray)
				{
					return null;
				}
				int count = Count;
				List<byte> list = new List<byte>(count);
				for (int i = 0; i < count; i++)
				{
					list.Add(this[i].AsByte);
				}
				return list;
			}
			set
			{
				if (IsArray && value != null)
				{
					Clear();
					for (int i = 0; i < value.Count; i++)
					{
						Add(value[i]);
					}
				}
			}
		}

		public virtual string[] AsStringArray
		{
			get
			{
				if (IsNull || !IsArray)
				{
					return null;
				}
				int count = Count;
				string[] array = new string[count];
				for (int i = 0; i < count; i++)
				{
					array[i] = this[i].Value;
				}
				return array;
			}
			set
			{
				if (IsArray && value != null)
				{
					Clear();
					for (int i = 0; i < value.Length; i++)
					{
						Add(value[i]);
					}
				}
			}
		}

		public virtual List<string> AsStringList
		{
			get
			{
				if (IsNull || !IsArray)
				{
					return null;
				}
				int count = Count;
				List<string> list = new List<string>(count);
				for (int i = 0; i < count; i++)
				{
					list.Add(this[i].Value);
				}
				return list;
			}
			set
			{
				if (IsArray && value != null)
				{
					Clear();
					for (int i = 0; i < value.Count; i++)
					{
						Add(value[i]);
					}
				}
			}
		}

		public virtual void Add(string aKey, JSONNode aItem)
		{
		}

		public virtual void Add(JSONNode aItem)
		{
			Add("", aItem);
		}

		public virtual JSONNode Remove(string aKey)
		{
			return null;
		}

		public virtual JSONNode Remove(int aIndex)
		{
			return null;
		}

		public virtual JSONNode Remove(JSONNode aNode)
		{
			return aNode;
		}

		public virtual void Clear()
		{
		}

		public virtual JSONNode Clone()
		{
			return null;
		}

		public virtual bool HasKey(string aKey)
		{
			return false;
		}

		public virtual JSONNode GetValueOrDefault(string aKey, JSONNode aDefault)
		{
			return aDefault;
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			WriteToStringBuilder(stringBuilder, 0, 0, JSONTextMode.Compact);
			return stringBuilder.ToString();
		}

		public virtual string ToString(int aIndent)
		{
			StringBuilder stringBuilder = new StringBuilder();
			WriteToStringBuilder(stringBuilder, 0, aIndent, JSONTextMode.Indent);
			return stringBuilder.ToString();
		}

		internal abstract void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode);

		public abstract Enumerator GetEnumerator();

		public static implicit operator JSONNode(string s)
		{
			if (s != null)
			{
				return new JSONString(s);
			}
			return JSONNull.CreateOrGet();
		}

		public static implicit operator string(JSONNode d)
		{
			if (!(d == null))
			{
				return d.Value;
			}
			return null;
		}

		public static implicit operator JSONNode(double n)
		{
			return new JSONNumber(n);
		}

		public static implicit operator double(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsDouble;
			}
			return 0.0;
		}

		public static implicit operator JSONNode(float n)
		{
			return new JSONNumber(n);
		}

		public static implicit operator float(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsFloat;
			}
			return 0f;
		}

		public static implicit operator JSONNode(int n)
		{
			return new JSONNumber(n);
		}

		public static implicit operator int(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsInt;
			}
			return 0;
		}

		public static implicit operator JSONNode(long n)
		{
			if (longAsString)
			{
				return new JSONString(n.ToString());
			}
			return new JSONNumber(n);
		}

		public static implicit operator long(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsLong;
			}
			return 0L;
		}

		public static implicit operator JSONNode(ulong n)
		{
			if (longAsString)
			{
				return new JSONString(n.ToString());
			}
			return new JSONNumber(n);
		}

		public static implicit operator ulong(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsULong;
			}
			return 0uL;
		}

		public static implicit operator JSONNode(bool b)
		{
			return new JSONBool(b);
		}

		public static implicit operator bool(JSONNode d)
		{
			if (!(d == null))
			{
				return d.AsBool;
			}
			return false;
		}

		public static implicit operator JSONNode(KeyValuePair<string, JSONNode> aKeyValue)
		{
			return aKeyValue.Value;
		}

		public static bool operator ==(JSONNode a, object b)
		{
			if ((object)a == b)
			{
				return true;
			}
			bool flag = a is JSONNull || (object)a == null || a is JSONLazyCreator;
			bool flag2 = b is JSONNull || b == null || b is JSONLazyCreator;
			if (flag && flag2)
			{
				return true;
			}
			if (!flag)
			{
				return a.Equals(b);
			}
			return false;
		}

		public static bool operator !=(JSONNode a, object b)
		{
			return !(a == b);
		}

		public override bool Equals(object obj)
		{
			return (object)this == obj;
		}

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

		internal static string Escape(string aText)
		{
			StringBuilder escapeBuilder = EscapeBuilder;
			escapeBuilder.Length = 0;
			if (escapeBuilder.Capacity < aText.Length + aText.Length / 10)
			{
				escapeBuilder.Capacity = aText.Length + aText.Length / 10;
			}
			foreach (char c in aText)
			{
				switch (c)
				{
				case '\\':
					escapeBuilder.Append("\\\\");
					continue;
				case '"':
					escapeBuilder.Append("\\\"");
					continue;
				case '\n':
					escapeBuilder.Append("\\n");
					continue;
				case '\r':
					escapeBuilder.Append("\\r");
					continue;
				case '\t':
					escapeBuilder.Append("\\t");
					continue;
				case '\b':
					escapeBuilder.Append("\\b");
					continue;
				case '\f':
					escapeBuilder.Append("\\f");
					continue;
				}
				if (c < ' ' || (forceASCII && c > '\u007f'))
				{
					ushort num = c;
					escapeBuilder.Append("\\u").Append(num.ToString("X4"));
				}
				else
				{
					escapeBuilder.Append(c);
				}
			}
			string result = escapeBuilder.ToString();
			escapeBuilder.Length = 0;
			return result;
		}

		private static JSONNode ParseElement(string token, bool quoted)
		{
			if (quoted)
			{
				return token;
			}
			if (token.Length <= 5)
			{
				string text = token.ToLower();
				switch (text)
				{
				case "false":
				case "true":
					return text == "true";
				case "null":
					return JSONNull.CreateOrGet();
				}
			}
			if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			return token;
		}

		public static JSONNode Parse(string aJSON)
		{
			Stack<JSONNode> stack = new Stack<JSONNode>();
			JSONNode jSONNode = null;
			int i = 0;
			StringBuilder stringBuilder = new StringBuilder();
			string aKey = "";
			bool flag = false;
			bool flag2 = false;
			bool flag3 = false;
			for (; i < aJSON.Length; i++)
			{
				switch (aJSON[i])
				{
				case '{':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					stack.Push(new JSONObject());
					if (jSONNode != null)
					{
						jSONNode.Add(aKey, stack.Peek());
					}
					aKey = "";
					stringBuilder.Length = 0;
					jSONNode = stack.Peek();
					flag3 = false;
					break;
				case '[':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					stack.Push(new JSONArray());
					if (jSONNode != null)
					{
						jSONNode.Add(aKey, stack.Peek());
					}
					aKey = "";
					stringBuilder.Length = 0;
					jSONNode = stack.Peek();
					flag3 = false;
					break;
				case ']':
				case '}':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					if (stack.Count == 0)
					{
						throw new Exception("JSON Parse: Too many closing brackets");
					}
					stack.Pop();
					if (stringBuilder.Length > 0 || flag2)
					{
						jSONNode.Add(aKey, ParseElement(stringBuilder.ToString(), flag2));
					}
					if (jSONNode != null)
					{
						jSONNode.Inline = !flag3;
					}
					flag2 = false;
					aKey = "";
					stringBuilder.Length = 0;
					if (stack.Count > 0)
					{
						jSONNode = stack.Peek();
					}
					break;
				case ':':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					aKey = stringBuilder.ToString();
					stringBuilder.Length = 0;
					flag2 = false;
					break;
				case '"':
					flag = !flag;
					flag2 = flag2 || flag;
					break;
				case ',':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
						break;
					}
					if (stringBuilder.Length > 0 || flag2)
					{
						jSONNode.Add(aKey, ParseElement(stringBuilder.ToString(), flag2));
					}
					flag2 = false;
					aKey = "";
					stringBuilder.Length = 0;
					flag2 = false;
					break;
				case '\n':
				case '\r':
					flag3 = true;
					break;
				case '\t':
				case ' ':
					if (flag)
					{
						stringBuilder.Append(aJSON[i]);
					}
					break;
				case '\\':
					i++;
					if (flag)
					{
						char c = aJSON[i];
						switch (c)
						{
						case 't':
							stringBuilder.Append('\t');
							break;
						case 'r':
							stringBuilder.Append('\r');
							break;
						case 'n':
							stringBuilder.Append('\n');
							break;
						case 'b':
							stringBuilder.Append('\b');
							break;
						case 'f':
							stringBuilder.Append('\f');
							break;
						case 'u':
						{
							string s = aJSON.Substring(i + 1, 4);
							stringBuilder.Append((char)int.Parse(s, NumberStyles.AllowHexSpecifier));
							i += 4;
							break;
						}
						default:
							stringBuilder.Append(c);
							break;
						}
					}
					break;
				case '/':
					if (allowLineComments && !flag && i + 1 < aJSON.Length && aJSON[i + 1] == '/')
					{
						while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r')
						{
						}
					}
					else
					{
						stringBuilder.Append(aJSON[i]);
					}
					break;
				default:
					stringBuilder.Append(aJSON[i]);
					break;
				case '\ufeff':
					break;
				}
			}
			if (flag)
			{
				throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
			}
			if (jSONNode == null)
			{
				return ParseElement(stringBuilder.ToString(), flag2);
			}
			return jSONNode;
		}

		public abstract void SerializeBinary(BinaryWriter aWriter);

		public void SaveToBinaryStream(Stream aData)
		{
			BinaryWriter aWriter = new BinaryWriter(aData);
			SerializeBinary(aWriter);
		}

		public void SaveToCompressedStream(Stream aData)
		{
			throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}

		public void SaveToCompressedFile(string aFileName)
		{
			throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}

		public string SaveToCompressedBase64()
		{
			throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}

		public void SaveToBinaryFile(string aFileName)
		{
			Directory.CreateDirectory(new FileInfo(aFileName).Directory.FullName);
			using FileStream aData = File.OpenWrite(aFileName);
			SaveToBinaryStream(aData);
		}

		public string SaveToBinaryBase64()
		{
			using MemoryStream memoryStream = new MemoryStream();
			SaveToBinaryStream(memoryStream);
			memoryStream.Position = 0L;
			return Convert.ToBase64String(memoryStream.ToArray());
		}

		public static JSONNode DeserializeBinary(BinaryReader aReader)
		{
			JSONNodeType jSONNodeType = (JSONNodeType)aReader.ReadByte();
			switch (jSONNodeType)
			{
			case JSONNodeType.Array:
			{
				int num2 = aReader.ReadInt32();
				JSONArray jSONArray = new JSONArray();
				for (int j = 0; j < num2; j++)
				{
					jSONArray.Add(DeserializeBinary(aReader));
				}
				return jSONArray;
			}
			case JSONNodeType.Object:
			{
				int num = aReader.ReadInt32();
				JSONObject jSONObject = new JSONObject();
				for (int i = 0; i < num; i++)
				{
					string aKey = aReader.ReadString();
					JSONNode aItem = DeserializeBinary(aReader);
					jSONObject.Add(aKey, aItem);
				}
				return jSONObject;
			}
			case JSONNodeType.String:
				return new JSONString(aReader.ReadString());
			case JSONNodeType.Number:
				return new JSONNumber(aReader.ReadDouble());
			case JSONNodeType.Boolean:
				return new JSONBool(aReader.ReadBoolean());
			case JSONNodeType.NullValue:
				return JSONNull.CreateOrGet();
			default:
				throw new Exception("Error deserializing JSON. Unknown tag: " + jSONNodeType);
			}
		}

		public static JSONNode LoadFromCompressedFile(string aFileName)
		{
			throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}

		public static JSONNode LoadFromCompressedStream(Stream aData)
		{
			throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}

		public static JSONNode LoadFromCompressedBase64(string aBase64)
		{
			throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}

		public static JSONNode LoadFromBinaryStream(Stream aData)
		{
			using BinaryReader aReader = new BinaryReader(aData);
			return DeserializeBinary(aReader);
		}

		public static JSONNode LoadFromBinaryFile(string aFileName)
		{
			using FileStream aData = File.OpenRead(aFileName);
			return LoadFromBinaryStream(aData);
		}

		public static JSONNode LoadFromBinaryBase64(string aBase64)
		{
			return LoadFromBinaryStream(new MemoryStream(Convert.FromBase64String(aBase64))
			{
				Position = 0L
			});
		}

		public static implicit operator JSONNode(decimal aDecimal)
		{
			return new JSONString(aDecimal.ToString());
		}

		public static implicit operator decimal(JSONNode aNode)
		{
			return aNode.AsDecimal;
		}

		public static implicit operator JSONNode(char aChar)
		{
			return new JSONString(aChar.ToString());
		}

		public static implicit operator char(JSONNode aNode)
		{
			return aNode.AsChar;
		}

		public static implicit operator JSONNode(uint aUInt)
		{
			return new JSONNumber(aUInt);
		}

		public static implicit operator uint(JSONNode aNode)
		{
			return aNode.AsUInt;
		}

		public static implicit operator JSONNode(byte aByte)
		{
			return new JSONNumber((int)aByte);
		}

		public static implicit operator byte(JSONNode aNode)
		{
			return aNode.AsByte;
		}

		public static implicit operator JSONNode(sbyte aSByte)
		{
			return new JSONNumber(aSByte);
		}

		public static implicit operator sbyte(JSONNode aNode)
		{
			return aNode.AsSByte;
		}

		public static implicit operator JSONNode(short aShort)
		{
			return new JSONNumber(aShort);
		}

		public static implicit operator short(JSONNode aNode)
		{
			return aNode.AsShort;
		}

		public static implicit operator JSONNode(ushort aUShort)
		{
			return new JSONNumber((int)aUShort);
		}

		public static implicit operator ushort(JSONNode aNode)
		{
			return aNode.AsUShort;
		}

		public static implicit operator JSONNode(DateTime aDateTime)
		{
			return new JSONString(aDateTime.ToString(CultureInfo.InvariantCulture));
		}

		public static implicit operator DateTime(JSONNode aNode)
		{
			return aNode.AsDateTime;
		}

		public static implicit operator JSONNode(TimeSpan aTimeSpan)
		{
			return new JSONString(aTimeSpan.ToString());
		}

		public static implicit operator TimeSpan(JSONNode aNode)
		{
			return aNode.AsTimeSpan;
		}

		public static implicit operator JSONNode(Guid aGuid)
		{
			return new JSONString(aGuid.ToString());
		}

		public static implicit operator Guid(JSONNode aNode)
		{
			return aNode.AsGuid;
		}

		public static implicit operator JSONNode(byte[] aByteArray)
		{
			return new JSONArray
			{
				AsByteArray = aByteArray
			};
		}

		public static implicit operator byte[](JSONNode aNode)
		{
			return aNode.AsByteArray;
		}

		public static implicit operator JSONNode(List<byte> aByteList)
		{
			return new JSONArray
			{
				AsByteList = aByteList
			};
		}

		public static implicit operator List<byte>(JSONNode aNode)
		{
			return aNode.AsByteList;
		}

		public static implicit operator JSONNode(string[] aStringArray)
		{
			return new JSONArray
			{
				AsStringArray = aStringArray
			};
		}

		public static implicit operator string[](JSONNode aNode)
		{
			return aNode.AsStringArray;
		}

		public static implicit operator JSONNode(List<string> aStringList)
		{
			return new JSONArray
			{
				AsStringList = aStringList
			};
		}

		public static implicit operator List<string>(JSONNode aNode)
		{
			return aNode.AsStringList;
		}

		public static implicit operator JSONNode(int? aValue)
		{
			if (!aValue.HasValue)
			{
				return JSONNull.CreateOrGet();
			}
			return new JSONNumber(aValue.Value);
		}

		public static implicit operator int?(JSONNode aNode)
		{
			if (aNode == null || aNode.IsNull)
			{
				return null;
			}
			return aNode.AsInt;
		}

		public static implicit operator JSONNode(float? aValue)
		{
			if (!aValue.HasValue)
			{
				return JSONNull.CreateOrGet();
			}
			return new JSONNumber(aValue.Value);
		}

		public static implicit operator float?(JSONNode aNode)
		{
			if (aNode == null || aNode.IsNull)
			{
				return null;
			}
			return aNode.AsFloat;
		}

		public static implicit operator JSONNode(double? aValue)
		{
			if (!aValue.HasValue)
			{
				return JSONNull.CreateOrGet();
			}
			return new JSONNumber(aValue.Value);
		}

		public static implicit operator double?(JSONNode aNode)
		{
			if (aNode == null || aNode.IsNull)
			{
				return null;
			}
			return aNode.AsDouble;
		}

		public static implicit operator JSONNode(bool? aValue)
		{
			if (!aValue.HasValue)
			{
				return JSONNull.CreateOrGet();
			}
			return new JSONBool(aValue.Value);
		}

		public static implicit operator bool?(JSONNode aNode)
		{
			if (aNode == null || aNode.IsNull)
			{
				return null;
			}
			return aNode.AsBool;
		}

		public static implicit operator JSONNode(long? aValue)
		{
			if (!aValue.HasValue)
			{
				return JSONNull.CreateOrGet();
			}
			return new JSONNumber(aValue.Value);
		}

		public static implicit operator long?(JSONNode aNode)
		{
			if (aNode == null || aNode.IsNull)
			{
				return null;
			}
			return aNode.AsLong;
		}

		public static implicit operator JSONNode(short? aValue)
		{
			if (!aValue.HasValue)
			{
				return JSONNull.CreateOrGet();
			}
			return new JSONNumber(aValue.Value);
		}

		public static implicit operator short?(JSONNode aNode)
		{
			if (aNode == null || aNode.IsNull)
			{
				return null;
			}
			return aNode.AsShort;
		}
	}
	public class JSONArray : JSONNode
	{
		private List<JSONNode> m_List = new List<JSONNode>();

		private bool inline;

		public override bool Inline
		{
			get
			{
				return inline;
			}
			set
			{
				inline = value;
			}
		}

		public override JSONNodeType Tag => JSONNodeType.Array;

		public override bool IsArray => true;

		public override JSONNode this[int aIndex]
		{
			get
			{
				if (aIndex < 0 || aIndex >= m_List.Count)
				{
					return new JSONLazyCreator(this);
				}
				return m_List[aIndex];
			}
			set
			{
				if (value == null)
				{
					value = JSONNull.CreateOrGet();
				}
				if (aIndex < 0 || aIndex >= m_List.Count)
				{
					m_List.Add(value);
				}
				else
				{
					m_List[aIndex] = value;
				}
			}
		}

		public override JSONNode this[string aKey]
		{
			get
			{
				return new JSONLazyCreator(this);
			}
			set
			{
				if (value == null)
				{
					value = JSONNull.CreateOrGet();
				}
				m_List.Add(value);
			}
		}

		public override int Count => m_List.Count;

		public override IEnumerable<JSONNode> Children
		{
			get
			{
				foreach (JSONNode item in m_List)
				{
					yield return item;
				}
			}
		}

		public override Enumerator GetEnumerator()
		{
			return new Enumerator(m_List.GetEnumerator());
		}

		public override void Add(string aKey, JSONNode aItem)
		{
			if (aItem == null)
			{
				aItem = JSONNull.CreateOrGet();
			}
			m_List.Add(aItem);
		}

		public override JSONNode Remove(int aIndex)
		{
			if (aIndex < 0 || aIndex >= m_List.Count)
			{
				return null;
			}
			JSONNode result = m_List[aIndex];
			m_List.RemoveAt(aIndex);
			return result;
		}

		public override JSONNode Remove(JSONNode aNode)
		{
			m_List.Remove(aNode);
			return aNode;
		}

		public override void Clear()
		{
			m_List.Clear();
		}

		public override JSONNode Clone()
		{
			JSONArray jSONArray = new JSONArray();
			jSONArray.m_List.Capacity = m_List.Capacity;
			foreach (JSONNode item in m_List)
			{
				if (item != null)
				{
					jSONArray.Add(item.Clone());
				}
				else
				{
					jSONArray.Add(null);
				}
			}
			return jSONArray;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append('[');
			int count = m_List.Count;
			if (inline)
			{
				aMode = JSONTextMode.Compact;
			}
			for (int i = 0; i < count; i++)
			{
				if (i > 0)
				{
					aSB.Append(',');
				}
				if (aMode == JSONTextMode.Indent)
				{
					aSB.AppendLine();
				}
				if (aMode == JSONTextMode.Indent)
				{
					aSB.Append(' ', aIndent + aIndentInc);
				}
				m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
			}
			if (aMode == JSONTextMode.Indent)
			{
				aSB.AppendLine().Append(' ', aIndent);
			}
			aSB.Append(']');
		}

		public override void SerializeBinary(BinaryWriter aWriter)
		{
			aWriter.Write((byte)1);
			aWriter.Write(m_List.Count);
			for (int i = 0; i < m_List.Count; i++)
			{
				m_List[i].SerializeBinary(aWriter);
			}
		}
	}
	public class JSONObject : JSONNode
	{
		private Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>();

		private bool inline;

		public override bool Inline
		{
			get
			{
				return inline;
			}
			set
			{
				inline = value;
			}
		}

		public override JSONNodeType Tag => JSONNodeType.Object;

		public override bool IsObject => true;

		public override JSONNode this[string aKey]
		{
			get
			{
				if (m_Dict.ContainsKey(aKey))
				{
					return m_Dict[aKey];
				}
				return new JSONLazyCreator(this, aKey);
			}
			set
			{
				if (value == null)
				{
					value = JSONNull.CreateOrGet();
				}
				if (m_Dict.ContainsKey(aKey))
				{
					m_Dict[aKey] = value;
				}
				else
				{
					m_Dict.Add(aKey, value);
				}
			}
		}

		public override JSONNode this[int aIndex]
		{
			get
			{
				if (aIndex < 0 || aIndex >= m_Dict.Count)
				{
					return null;
				}
				return m_Dict.ElementAt(aIndex).Value;
			}
			set
			{
				if (value == null)
				{
					value = JSONNull.CreateOrGet();
				}
				if (aIndex >= 0 && aIndex < m_Dict.Count)
				{
					string key = m_Dict.ElementAt(aIndex).Key;
					m_Dict[key] = value;
				}
			}
		}

		public override int Count => m_Dict.Count;

		public override IEnumerable<JSONNode> Children
		{
			get
			{
				foreach (KeyValuePair<string, JSONNode> item in m_Dict)
				{
					yield return item.Value;
				}
			}
		}

		public override Enumerator GetEnumerator()
		{
			return new Enumerator(m_Dict.GetEnumerator());
		}

		public override void Add(string aKey, JSONNode aItem)
		{
			if (aItem == null)
			{
				aItem = JSONNull.CreateOrGet();
			}
			if (aKey != null)
			{
				if (m_Dict.ContainsKey(aKey))
				{
					m_Dict[aKey] = aItem;
				}
				else
				{
					m_Dict.Add(aKey, aItem);
				}
			}
			else
			{
				m_Dict.Add(Guid.NewGuid().ToString(), aItem);
			}
		}

		public override JSONNode Remove(string aKey)
		{
			if (!m_Dict.ContainsKey(aKey))
			{
				return null;
			}
			JSONNode result = m_Dict[aKey];
			m_Dict.Remove(aKey);
			return result;
		}

		public override JSONNode Remove(int aIndex)
		{
			if (aIndex < 0 || aIndex >= m_Dict.Count)
			{
				return null;
			}
			KeyValuePair<string, JSONNode> keyValuePair = m_Dict.ElementAt(aIndex);
			m_Dict.Remove(keyValuePair.Key);
			return keyValuePair.Value;
		}

		public override JSONNode Remove(JSONNode aNode)
		{
			try
			{
				KeyValuePair<string, JSONNode> keyValuePair = m_Dict.Where((KeyValuePair<string, JSONNode> k) => k.Value == aNode).First();
				m_Dict.Remove(keyValuePair.Key);
				return aNode;
			}
			catch
			{
				return null;
			}
		}

		public override void Clear()
		{
			m_Dict.Clear();
		}

		public override JSONNode Clone()
		{
			JSONObject jSONObject = new JSONObject();
			foreach (KeyValuePair<string, JSONNode> item in m_Dict)
			{
				jSONObject.Add(item.Key, item.Value.Clone());
			}
			return jSONObject;
		}

		public override bool HasKey(string aKey)
		{
			return m_Dict.ContainsKey(aKey);
		}

		public override JSONNode GetValueOrDefault(string aKey, JSONNode aDefault)
		{
			if (m_Dict.TryGetValue(aKey, out var value))
			{
				return value;
			}
			return aDefault;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append('{');
			bool flag = true;
			if (inline)
			{
				aMode = JSONTextMode.Compact;
			}
			foreach (KeyValuePair<string, JSONNode> item in m_Dict)
			{
				if (!flag)
				{
					aSB.Append(',');
				}
				flag = false;
				if (aMode == JSONTextMode.Indent)
				{
					aSB.AppendLine();
				}
				if (aMode == JSONTextMode.Indent)
				{
					aSB.Append(' ', aIndent + aIndentInc);
				}
				aSB.Append('"').Append(JSONNode.Escape(item.Key)).Append('"');
				if (aMode == JSONTextMode.Compact)
				{
					aSB.Append(':');
				}
				else
				{
					aSB.Append(" : ");
				}
				item.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
			}
			if (aMode == JSONTextMode.Indent)
			{
				aSB.AppendLine().Append(' ', aIndent);
			}
			aSB.Append('}');
		}

		public override void SerializeBinary(BinaryWriter aWriter)
		{
			aWriter.Write((byte)2);
			aWriter.Write(m_Dict.Count);
			foreach (string key in m_Dict.Keys)
			{
				aWriter.Write(key);
				m_Dict[key].SerializeBinary(aWriter);
			}
		}
	}
	public class JSONString : JSONNode
	{
		private string m_Data;

		public override JSONNodeType Tag => JSONNodeType.String;

		public override bool IsString => true;

		public override string Value
		{
			get
			{
				return m_Data;
			}
			set
			{
				m_Data = value;
			}
		}

		public override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		public JSONString(string aData)
		{
			m_Data = aData;
		}

		public override JSONNode Clone()
		{
			return new JSONString(m_Data);
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append('"').Append(JSONNode.Escape(m_Data)).Append('"');
		}

		public override bool Equals(object obj)
		{
			if (base.Equals(obj))
			{
				return true;
			}
			if (obj is string text)
			{
				return m_Data == text;
			}
			JSONString jSONString = obj as JSONString;
			if (jSONString != null)
			{
				return m_Data == jSONString.m_Data;
			}
			return false;
		}

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

		public override void Clear()
		{
			m_Data = "";
		}

		public override void SerializeBinary(BinaryWriter aWriter)
		{
			aWriter.Write((byte)3);
			aWriter.Write(m_Data);
		}
	}
	public class JSONNumber : JSONNode
	{
		private double m_Data;

		public override JSONNodeType Tag => JSONNodeType.Number;

		public override bool IsNumber => true;

		public override string Value
		{
			get
			{
				return m_Data.ToString(CultureInfo.InvariantCulture);
			}
			set
			{
				if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					m_Data = result;
				}
			}
		}

		public override double AsDouble
		{
			get
			{
				return m_Data;
			}
			set
			{
				m_Data = value;
			}
		}

		public override long AsLong
		{
			get
			{
				return (long)m_Data;
			}
			set
			{
				m_Data = value;
			}
		}

		public override ulong AsULong
		{
			get
			{
				return (ulong)m_Data;
			}
			set
			{
				m_Data = value;
			}
		}

		public override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		public JSONNumber(double aData)
		{
			m_Data = aData;
		}

		public JSONNumber(string aData)
		{
			Value = aData;
		}

		public override JSONNode Clone()
		{
			return new JSONNumber(m_Data);
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append(Value);
		}

		private static bool IsNumeric(object value)
		{
			if (!(value is int) && !(value is uint) && !(value is float) && !(value is double) && !(value is decimal) && !(value is long) && !(value is ulong) && !(value is short) && !(value is ushort) && !(value is sbyte))
			{
				return value is byte;
			}
			return true;
		}

		public override bool Equals(object obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (base.Equals(obj))
			{
				return true;
			}
			JSONNumber jSONNumber = obj as JSONNumber;
			if (jSONNumber != null)
			{
				return m_Data == jSONNumber.m_Data;
			}
			if (IsNumeric(obj))
			{
				return Convert.ToDouble(obj) == m_Data;
			}
			return false;
		}

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

		public override void Clear()
		{
			m_Data = 0.0;
		}

		public override void SerializeBinary(BinaryWriter aWriter)
		{
			aWriter.Write((byte)4);
			aWriter.Write(m_Data);
		}
	}
	public class JSONBool : JSONNode
	{
		private bool m_Data;

		public override JSONNodeType Tag => JSONNodeType.Boolean;

		public override bool IsBoolean => true;

		public override string Value
		{
			get
			{
				return m_Data.ToString();
			}
			set
			{
				if (bool.TryParse(value, out var result))
				{
					m_Data = result;
				}
			}
		}

		public override bool AsBool
		{
			get
			{
				return m_Data;
			}
			set
			{
				m_Data = value;
			}
		}

		public override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		public JSONBool(bool aData)
		{
			m_Data = aData;
		}

		public JSONBool(string aData)
		{
			Value = aData;
		}

		public override JSONNode Clone()
		{
			return new JSONBool(m_Data);
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append(m_Data ? "true" : "false");
		}

		public override bool Equals(object obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (obj is bool)
			{
				return m_Data == (bool)obj;
			}
			return false;
		}

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

		public override void Clear()
		{
			m_Data = false;
		}

		public override void SerializeBinary(BinaryWriter aWriter)
		{
			aWriter.Write((byte)6);
			aWriter.Write(m_Data);
		}
	}
	public class JSONNull : JSONNode
	{
		private static JSONNull m_StaticInstance = new JSONNull();

		public static bool reuseSameInstance = true;

		public override JSONNodeType Tag => JSONNodeType.NullValue;

		public override bool IsNull => true;

		public override string Value
		{
			get
			{
				return "null";
			}
			set
			{
			}
		}

		public override bool AsBool
		{
			get
			{
				return false;
			}
			set
			{
			}
		}

		public static JSONNull CreateOrGet()
		{
			if (reuseSameInstance)
			{
				return m_StaticInstance;
			}
			return new JSONNull();
		}

		private JSONNull()
		{
		}

		public override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		public override JSONNode Clone()
		{
			return CreateOrGet();
		}

		public override bool Equals(object obj)
		{
			if ((object)this == obj)
			{
				return true;
			}
			return obj is JSONNull;
		}

		public override int GetHashCode()
		{
			return 0;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append("null");
		}

		public override void SerializeBinary(BinaryWriter aWriter)
		{
			aWriter.Write((byte)5);
		}
	}
	internal class JSONLazyCreator : JSONNode
	{
		private JSONNode m_Node;

		private string m_Key;

		public override JSONNodeType Tag => JSONNodeType.None;

		public override JSONNode this[int aIndex]
		{
			get
			{
				return new JSONLazyCreator(this);
			}
			set
			{
				Set(new JSONArray()).Add(value);
			}
		}

		public override JSONNode this[string aKey]
		{
			get
			{
				return new JSONLazyCreator(this, aKey);
			}
			set
			{
				Set(new JSONObject()).Add(aKey, value);
			}
		}

		public override int AsInt
		{
			get
			{
				Set(new JSONNumber(0.0));
				return 0;
			}
			set
			{
				Set(new JSONNumber(value));
			}
		}

		public override float AsFloat
		{
			get
			{
				Set(new JSONNumber(0.0));
				return 0f;
			}
			set
			{
				Set(new JSONNumber(value));
			}
		}

		public override double AsDouble
		{
			get
			{
				Set(new JSONNumber(0.0));
				return 0.0;
			}
			set
			{
				Set(new JSONNumber(value));
			}
		}

		public override long AsLong
		{
			get
			{
				if (JSONNode.longAsString)
				{
					Set(new JSONString("0"));
				}
				else
				{
					Set(new JSONNumber(0.0));
				}
				return 0L;
			}
			set
			{
				if (JSONNode.longAsString)
				{
					Set(new JSONString(value.ToString()));
				}
				else
				{
					Set(new JSONNumber(value));
				}
			}
		}

		public override ulong AsULong
		{
			get
			{
				if (JSONNode.longAsString)
				{
					Set(new JSONString("0"));
				}
				else
				{
					Set(new JSONNumber(0.0));
				}
				return 0uL;
			}
			set
			{
				if (JSONNode.longAsString)
				{
					Set(new JSONString(value.ToString()));
				}
				else
				{
					Set(new JSONNumber(value));
				}
			}
		}

		public override bool AsBool
		{
			get
			{
				Set(new JSONBool(aData: false));
				return false;
			}
			set
			{
				Set(new JSONBool(value));
			}
		}

		public override JSONArray AsArray => Set(new JSONArray());

		public override JSONObject AsObject => Set(new JSONObject());

		public override Enumerator GetEnumerator()
		{
			return default(Enumerator);
		}

		public JSONLazyCreator(JSONNode aNode)
		{
			m_Node = aNode;
			m_Key = null;
		}

		public JSONLazyCreator(JSONNode aNode, string aKey)
		{
			m_Node = aNode;
			m_Key = aKey;
		}

		private T Set<T>(T aVal) where T : JSONNode
		{
			if (m_Key == null)
			{
				m_Node.Add(aVal);
			}
			else
			{
				m_Node.Add(m_Key, aVal);
			}
			m_Node = null;
			return aVal;
		}

		public override void Add(JSONNode aItem)
		{
			Set(new JSONArray()).Add(aItem);
		}

		public override void Add(string aKey, JSONNode aItem)
		{
			Set(new JSONObject()).Add(aKey, aItem);
		}

		public static bool operator ==(JSONLazyCreator a, object b)
		{
			if (b == null)
			{
				return true;
			}
			return (object)a == b;
		}

		public static bool operator !=(JSONLazyCreator a, object b)
		{
			return !(a == b);
		}

		public override bool Equals(object obj)
		{
			if (obj == null)
			{
				return true;
			}
			return (object)this == obj;
		}

		public override int GetHashCode()
		{
			return 0;
		}

		internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
		{
			aSB.Append("null");
		}

		public override void SerializeBinary(BinaryWriter aWriter)
		{
		}
	}
	public static class JSON
	{
		public static JSONNode Parse(string aJSON)
		{
			return JSONNode.Parse(aJSON);
		}
	}
}
namespace AuthoritativeConfig
{
	public class Config
	{
		private static Config _instance;

		public Dictionary<string, ConfigBaseEntry> _configEntries;

		public BaseUnityPlugin _mod;

		private static ConfigEntry<bool> _serverIsAuthoritative;

		private static bool _defaultBindAuthority;

		public static ManualLogSource Logger;

		public UnityEvent OnConfigReceived = new UnityEvent();

		public static Config Instance => _instance ?? (_instance = new Config());

		public static ZNet ZNet => ZNet.instance;

		public static string GUID => Instance._mod.Info.Metadata.GUID;

		public static string RPC_SYNC_GUID => "AuthoritativeConfig_" + GUID;

		public static int RPC_SYNC_HASH => StringExtensionMethods.GetStableHashCode(RPC_SYNC_GUID);

		public void Init(BaseUnityPlugin mod, bool defaultBindServerAuthority = false)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			_mod = mod;
			Logger = new ManualLogSource(RPC_SYNC_GUID);
			Logger.Sources.Add((ILogSource)(object)Logger);
			_configEntries = new Dictionary<string, ConfigBaseEntry>();
			_defaultBindAuthority = defaultBindServerAuthority;
			_serverIsAuthoritative = _mod.Config.Bind<bool>("ServerAuthoritativeConfig", "ServerIsAuthoritative", true, "<Server Only> Forces Clients to use Server defined configs.");
			Harmony.CreateAndPatchAll(typeof(Config), (string)null);
			Logger.LogInfo((object)"Initialized Server Authoritative Config Manager.");
		}

		[HarmonyPatch(typeof(Game), "Start")]
		[HarmonyPostfix]
		protected static void RegisterSyncConfigRPC()
		{
			if (!ZRoutedRpc.instance.m_functions.ContainsKey(RPC_SYNC_HASH))
			{
				Logger.LogInfo((object)("Authoritative Config Registered -> " + RPC_SYNC_GUID));
				ZRoutedRpc.instance.Register<ZPackage>(RPC_SYNC_GUID, (Action<long, ZPackage>)RPC_SyncServerConfig);
			}
			foreach (ConfigBaseEntry value in Instance._configEntries.Values)
			{
				value.ClearServerValue();
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPostfix]
		protected static void RequestConfigFromServer()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			if (!ZNet.IsServer() && (int)ZNet.GetConnectionStatus() == 2)
			{
				long? num = AccessTools.Method(typeof(ZRoutedRpc), "GetServerPeerID", (Type[])null, (Type[])null).Invoke(ZRoutedRpc.instance, null) as long?;
				ZRoutedRpc.instance.InvokeRoutedRPC(num.Value, RPC_SYNC_GUID, new object[1] { (object)new ZPackage() });
				Logger.LogInfo((object)("Authoritative Config Registered -> " + RPC_SYNC_GUID));
				Debug.Log((object)(Instance._mod.Info.Metadata.Name + ": Authoritative Config Requested -> " + RPC_SYNC_GUID));
			}
			else if (!ZNet.IsServer())
			{
				Logger.LogWarning((object)"Failed to Request Configs. Bad Peer? Too Early?");
			}
		}

		public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null, bool? serverAuthoritative = null)
		{
			ConfigEntry<T> configEntry = new ConfigEntry<T>(_mod.Config.Bind<T>(section, key, defaultValue, configDescription), serverAuthoritative.HasValue ? serverAuthoritative.Value : _defaultBindAuthority);
			_configEntries[((object)configEntry.BaseEntry.Definition).ToString()] = configEntry;
			return configEntry;
		}

		public ConfigEntry<T> Bind<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null, bool? serverAuthoritative = null)
		{
			ConfigEntry<T> configEntry = new ConfigEntry<T>(_mod.Config.Bind<T>(configDefinition, defaultValue, configDescription), serverAuthoritative.HasValue ? serverAuthoritative.Value : _defaultBindAuthority);
			_configEntries[((object)configEntry.BaseEntry.Definition).ToString()] = configEntry;
			return configEntry;
		}

		public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, string description, bool? serverAuthoritative = null)
		{
			ConfigEntry<T> configEntry = new ConfigEntry<T>(_mod.Config.Bind<T>(section, key, defaultValue, description), serverAuthoritative.HasValue ? serverAuthoritative.Value : _defaultBindAuthority);
			_configEntries[((object)configEntry.BaseEntry.Definition).ToString()] = configEntry;
			return configEntry;
		}

		public static void SendConfigToClient(long sender)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			if (!ZNet.IsServer())
			{
				return;
			}
			ZPackage val = new ZPackage();
			int num = 0;
			foreach (KeyValuePair<string, ConfigBaseEntry> configEntry in Instance._configEntries)
			{
				if (configEntry.Value.ServerAuthoritative)
				{
					val.Write(configEntry.Key);
					val.Write(configEntry.Value.BaseEntry.GetSerializedValue());
					num++;
					Logger.LogInfo((object)("Sending Config " + configEntry.Key + ": " + configEntry.Value.BaseEntry.GetSerializedValue()));
				}
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(sender, RPC_SYNC_GUID, new object[1] { val });
			Logger.LogInfo((object)$"Sent {num} config pairs to client {sender}");
		}

		public static void ReadConfigPkg(ZPackage pkg)
		{
			if (ZNet.IsServer())
			{
				return;
			}
			int num = 0;
			while (pkg.GetPos() != pkg.Size())
			{
				string text = pkg.ReadString();
				string text2 = pkg.ReadString();
				num++;
				if (Instance._configEntries.ContainsKey(text))
				{
					Instance._configEntries[text].SetSerializedValue(text2);
					Logger.LogInfo((object)("Applied Server Authoritative config pair => " + text + ": " + text2));
				}
				else
				{
					Logger.LogError((object)("Recieved config key we dont have locally. Possible Version Mismatch. " + text + ": " + text2));
				}
			}
			Logger.LogInfo((object)$"Applied {num} config pairs");
			UnityEvent onConfigReceived = Instance.OnConfigReceived;
			if (onConfigReceived != null)
			{
				onConfigReceived.Invoke();
			}
		}

		public static void RPC_SyncServerConfig(long sender, ZPackage pkg)
		{
			if (ZNet.IsServer() && _serverIsAuthoritative.Value)
			{
				SendConfigToClient(sender);
			}
			else if (!ZNet.IsServer() && pkg != null && pkg.Size() > 0 && AccessTools.Method(typeof(ZRoutedRpc), "GetServerPeerID", (Type[])null, (Type[])null).Invoke(ZRoutedRpc.instance, null) as long? == sender)
			{
				ReadConfigPkg(pkg);
			}
		}
	}
	public class ConfigBaseEntry
	{
		protected object _serverValue;

		public ConfigEntryBase BaseEntry;

		public bool ServerAuthoritative;

		protected bool _didError;

		internal ConfigBaseEntry(ConfigEntryBase configEntry, bool serverAuthoritative)
		{
			BaseEntry = configEntry;
			ServerAuthoritative = serverAuthoritative;
		}

		public void SetSerializedValue(string value)
		{
			try
			{
				_serverValue = TomlTypeConverter.ConvertToValue(value, BaseEntry.SettingType);
				_didError = false;
			}
			catch (Exception ex)
			{
				Config.Logger.LogWarning((object)$"Config value of setting \"{BaseEntry.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
			}
		}

		public void ClearServerValue()
		{
			_serverValue = null;
			_didError = false;
		}
	}
	public class ConfigEntry<T> : ConfigBaseEntry
	{
		private readonly ConfigEntry<T> _configEntry;

		public T ServerValue => (T)_serverValue;

		public T Value
		{
			get
			{
				if (ServerAuthoritative && (Object)(object)Config.ZNet != (Object)null && !Config.ZNet.IsServer())
				{
					if (_serverValue != null)
					{
						return ServerValue;
					}
					if (!_didError)
					{
						Config.Logger.LogWarning((object)$"No Recieved value for Server Authoritative Config. {BaseEntry.Definition}. Falling Back to Client Config.");
						_didError = true;
					}
					return _configEntry.Value;
				}
				return _configEntry.Value;
			}
			set
			{
				_configEntry.Value = value;
			}
		}

		internal ConfigEntry(ConfigEntry<T> configEntry, bool serverAuthoritative)
			: base((ConfigEntryBase)(object)configEntry, serverAuthoritative)
		{
			_configEntry = configEntry;
		}
	}
}

BepInEx/plugins/MathiasDecrock-PlanBuild/PlanBuild/PlanBuild.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using CraftFromContainers;
using Gizmo;
using Gizmo.Patches;
using HarmonyLib;
using Jotunn;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.GUI;
using Jotunn.Managers;
using Jotunn.Utils;
using On;
using PlanBuild.Blueprints;
using PlanBuild.Blueprints.Components;
using PlanBuild.ModCompat;
using PlanBuild.Plans;
using PlanBuild.Utils;
using SimpleJson;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using ValheimRAFT;
using ValheimRAFT.Patches;
using Valheim_Build_Camera;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("PlanBuild")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PlanBuild")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")]
[assembly: AssemblyFileVersion("0.14.2.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.14.2.0")]
[module: UnverifiableCode]
namespace PlanBuild
{
	internal static class Config
	{
		public enum DefaultBuildMode
		{
			Planned,
			Direct
		}

		private const string ServerSection = "Server Settings";

		public static ConfigEntry<bool> AllowDirectBuildConfig;

		public static ConfigEntry<bool> AllowTerrainmodConfig;

		public static ConfigEntry<bool> AllowServerBlueprints;

		public static ConfigEntry<bool> AllowBlueprintRune;

		public static ConfigEntry<bool> AllowMarketHotkey;

		public static ConfigEntry<string> PlanBlacklistConfig;

		private const string RuneSection = "Blueprints";

		public static ConfigEntry<DefaultBuildMode> DefaultBuildModeConfig;

		public static ConfigEntry<bool> UnlimitedHealthConfig;

		public static ConfigEntry<float> RayDistanceConfig;

		public static ConfigEntry<float> TerrainSmoothConfig;

		public static ConfigEntry<float> CameraOffsetIncrementConfig;

		public static ConfigEntry<bool> InvertCameraOffsetScrollConfig;

		public static ConfigEntry<float> PlacementOffsetIncrementConfig;

		public static ConfigEntry<bool> InvertPlacementOffsetScrollConfig;

		public static ConfigEntry<float> SelectionIncrementConfig;

		public static ConfigEntry<bool> InvertSelectionScrollConfig;

		public static ConfigEntry<int> RotationIncrementConfig;

		public static ConfigEntry<bool> InvertRotationScrollConfig;

		public static ConfigEntry<float> SelectionConnectedMarginConfig;

		public static ConfigEntry<bool> ShowGridConfig;

		public static ConfigEntry<bool> TooltipEnabledConfig;

		public static ConfigEntry<Color> TooltipBackgroundConfig;

		public static ConfigEntry<string> BlueprintUndoQueueNameConfig;

		public static ConfigEntry<bool> AddPlayerNameConfig;

		private const string DirectorySection = "Directories";

		public static ConfigEntry<string> BlueprintSearchDirectoryConfig;

		public static ConfigEntry<string> BlueprintSaveDirectoryConfig;

		private const string KeybindSection = "Keybindings";

		public static ConfigEntry<KeyCode> MarketHotkeyConfig;

		public static ButtonConfig MarketHotkeyButton;

		public static ConfigEntry<KeyCode> ShiftModifierConfig;

		public static ButtonConfig ShiftModifierButton;

		public static ConfigEntry<KeyCode> CtrlModifierConfig;

		public static ButtonConfig CtrlModifierButton;

		public static ConfigEntry<KeyCode> ToggleConfig;

		public static ButtonConfig ToggleButton;

		public static ConfigEntry<KeyCode> AltModifierConfig;

		public static ButtonConfig AltModifierButton;

		private const string PlansSection = "Plans";

		public static ConfigEntry<bool> ShowAllPieces;

		public static ConfigEntry<float> RadiusConfig;

		public static ConfigEntry<bool> ShowParticleEffects;

		private const string VisualSection = "Visual";

		public static ConfigEntry<bool> ConfigTransparentGhostPlacement;

		public static ConfigEntry<Color> UnsupportedColorConfig;

		public static ConfigEntry<Color> SupportedPlanColorConfig;

		public static ConfigEntry<float> TransparencyConfig;

		public static ConfigEntry<Color> GlowColorConfig;

		public static bool DirectBuildDefault => DefaultBuildModeConfig.Value == DefaultBuildMode.Direct;

		internal static void Init()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Expected O, but got Unknown
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Expected O, but got Unknown
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Expected O, but got Unknown
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Expected O, but got Unknown
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Expected O, but got Unknown
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Expected O, but got Unknown
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Expected O, but got Unknown
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Expected O, but got Unknown
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Expected O, but got Unknown
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Expected O, but got Unknown
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Expected O, but got Unknown
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Expected O, but got Unknown
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Expected O, but got Unknown
			//IL_037f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			//IL_0395: Expected O, but got Unknown
			//IL_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_039f: Expected O, but got Unknown
			//IL_03cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e1: Expected O, but got Unknown
			//IL_03e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03eb: Expected O, but got Unknown
			//IL_0413: Unknown result type (might be due to invalid IL or missing references)
			//IL_0418: Unknown result type (might be due to invalid IL or missing references)
			//IL_0429: Expected O, but got Unknown
			//IL_0429: Unknown result type (might be due to invalid IL or missing references)
			//IL_0433: Expected O, but got Unknown
			//IL_045f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0464: Unknown result type (might be due to invalid IL or missing references)
			//IL_0475: Expected O, but got Unknown
			//IL_0475: Unknown result type (might be due to invalid IL or missing references)
			//IL_047f: Expected O, but got Unknown
			//IL_04a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bd: Expected O, but got Unknown
			//IL_04bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c7: Expected O, but got Unknown
			//IL_04f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0509: Expected O, but got Unknown
			//IL_0509: Unknown result type (might be due to invalid IL or missing references)
			//IL_0513: Expected O, but got Unknown
			//IL_053b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0540: Unknown result type (might be due to invalid IL or missing references)
			//IL_0551: Expected O, but got Unknown
			//IL_0551: Unknown result type (might be due to invalid IL or missing references)
			//IL_055b: Expected O, but got Unknown
			//IL_0583: Unknown result type (might be due to invalid IL or missing references)
			//IL_0588: Unknown result type (might be due to invalid IL or missing references)
			//IL_0599: Expected O, but got Unknown
			//IL_0599: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a3: Expected O, but got Unknown
			//IL_05cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e1: Expected O, but got Unknown
			//IL_05e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_05eb: Expected O, but got Unknown
			//IL_0617: Unknown result type (might be due to invalid IL or missing references)
			//IL_061c: Unknown result type (might be due to invalid IL or missing references)
			//IL_062d: Expected O, but got Unknown
			//IL_062d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0637: Expected O, but got Unknown
			//IL_065f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0664: Unknown result type (might be due to invalid IL or missing references)
			//IL_0675: Expected O, but got Unknown
			//IL_0675: Unknown result type (might be due to invalid IL or missing references)
			//IL_067f: Expected O, but got Unknown
			//IL_06a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_06bd: Expected O, but got Unknown
			//IL_06bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c7: Expected O, but got Unknown
			//IL_06f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0707: Unknown result type (might be due to invalid IL or missing references)
			//IL_070c: Unknown result type (might be due to invalid IL or missing references)
			//IL_071d: Expected O, but got Unknown
			//IL_071d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0727: Expected O, but got Unknown
			//IL_0753: Unknown result type (might be due to invalid IL or missing references)
			//IL_0758: Unknown result type (might be due to invalid IL or missing references)
			//IL_0769: Expected O, but got Unknown
			//IL_0769: Unknown result type (might be due to invalid IL or missing references)
			//IL_0773: Expected O, but got Unknown
			//IL_079b: Unknown result type (might be due to invalid IL or missing references)
			//IL_07a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_07b1: Expected O, but got Unknown
			//IL_07b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_07bb: Expected O, but got Unknown
			//IL_07e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_07fd: Expected O, but got Unknown
			//IL_07fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0807: Expected O, but got Unknown
			//IL_0833: Unknown result type (might be due to invalid IL or missing references)
			//IL_0838: Unknown result type (might be due to invalid IL or missing references)
			//IL_0849: Expected O, but got Unknown
			//IL_0849: Unknown result type (might be due to invalid IL or missing references)
			//IL_0853: Expected O, but got Unknown
			//IL_087f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0884: Unknown result type (might be due to invalid IL or missing references)
			//IL_0895: Expected O, but got Unknown
			//IL_0895: Unknown result type (might be due to invalid IL or missing references)
			//IL_089f: Expected O, but got Unknown
			//IL_08cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_08e1: Expected O, but got Unknown
			//IL_08e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_08eb: Expected O, but got Unknown
			//IL_0917: Unknown result type (might be due to invalid IL or missing references)
			//IL_091c: Unknown result type (might be due to invalid IL or missing references)
			//IL_092d: Expected O, but got Unknown
			//IL_092d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0937: Expected O, but got Unknown
			//IL_0963: Unknown result type (might be due to invalid IL or missing references)
			//IL_0968: Unknown result type (might be due to invalid IL or missing references)
			//IL_0979: Expected O, but got Unknown
			//IL_0979: Unknown result type (might be due to invalid IL or missing references)
			//IL_0983: Expected O, but got Unknown
			//IL_09ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_09b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_09c2: Expected O, but got Unknown
			//IL_09c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_09cc: Expected O, but got Unknown
			//IL_0a46: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a4b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a52: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a63: Expected O, but got Unknown
			//IL_0a63: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a6d: Expected O, but got Unknown
			//IL_0a99: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a9e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aa5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ab6: Expected O, but got Unknown
			//IL_0ab6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ac0: Expected O, but got Unknown
			//IL_0ae8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0aed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0af4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b05: Expected O, but got Unknown
			//IL_0b05: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b0f: Expected O, but got Unknown
			//IL_0b60: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b65: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b76: Expected O, but got Unknown
			//IL_0b76: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b80: Expected O, but got Unknown
			//IL_0bad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bc0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bc5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bd6: Expected O, but got Unknown
			//IL_0bd6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0be0: Expected O, but got Unknown
			//IL_0c0d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c20: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c25: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c36: Expected O, but got Unknown
			//IL_0c36: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c40: Expected O, but got Unknown
			//IL_0c7a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c7f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c90: Expected O, but got Unknown
			//IL_0c90: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c9a: Expected O, but got Unknown
			//IL_0cb3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cc6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ccb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cdc: Expected O, but got Unknown
			//IL_0cdc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ce6: Expected O, but got Unknown
			int num = 0;
			AllowBlueprintRune = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Server Settings", "Allow blueprint rune", true, new ConfigDescription("Allow usage of blueprint rune for clients connecting to the server." + Environment.NewLine + "Admins are always allowed to use it.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = (num -= 1)
			} }));
			AllowDirectBuildConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Server Settings", "Allow direct build", false, new ConfigDescription("Allow placement of blueprints without materials on this server." + Environment.NewLine + "Admins are always allowed to use it.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = (num -= 1)
			} }));
			AllowTerrainmodConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Server Settings", "Allow terrain tools", false, new ConfigDescription("Allow usage of the terrain modification tools on this server." + Environment.NewLine + "Admins are always allowed to use them.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = (num -= 1)
			} }));
			AllowServerBlueprints = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Server Settings", "Allow serverside blueprints", false, new ConfigDescription("Allow sharing of blueprints on this server.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = (num -= 1)
			} }));
			AllowMarketHotkey = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Server Settings", "Allow clients to use the GUI toggle key", true, new ConfigDescription("Allow clients to use the Hotkey to access server blueprints." + Environment.NewLine + "Admins are always allowed to use it.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = (num -= 1)
			} }));
			PlanBlacklistConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<string>("Server Settings", "Excluded plan prefabs", "AltarPrefab,FloatingIslandMO", new ConfigDescription("Comma separated list of prefab names to exclude from the planned piece table on this server" + Environment.NewLine + "Admins are always allowed to build them.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = (num -= 1),
				Browsable = false
			} }));
			DefaultBuildModeConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<DefaultBuildMode>("Blueprints", "Default build mode", DefaultBuildMode.Planned, new ConfigDescription("Default build mode when placing blueprints.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			DefaultBuildModeConfig.SettingChanged += delegate
			{
				foreach (Blueprint value in BlueprintManager.LocalBlueprints.Values)
				{
					value.CreateKeyHint();
				}
			};
			UnlimitedHealthConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Blueprints", "Unlimited health", false, new ConfigDescription("Set Piece health to its maximum value when directly building blueprints.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			RayDistanceConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<float>("Blueprints", "Place distance", 50f, new ConfigDescription("Place distance while using the Blueprint Rune.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(8f, 80f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			TerrainSmoothConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<float>("Blueprints", "Terrain smoothing", 0.5f, new ConfigDescription("Smoothing value of the terrain tool when flattening with smoothing modifier key pressed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			CameraOffsetIncrementConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<float>("Blueprints", "Camera offset increment", 2f, new ConfigDescription("Camera height change when holding the camera modifier key and scrolling.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			InvertCameraOffsetScrollConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Blueprints", "Invert camera offset scroll", false, new ConfigDescription("Invert the direction of camera offset scrolling.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			PlacementOffsetIncrementConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<float>("Blueprints", "Placement offset increment", 0.1f, new ConfigDescription("Placement height change when holding the modifier key and scrolling.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			InvertPlacementOffsetScrollConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Blueprints", "Invert placement height change scroll", false, new ConfigDescription("Invert the direction of placement offset scrolling.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			SelectionIncrementConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<float>("Blueprints", "Selection increment", 1f, new ConfigDescription("Selection radius increment when scrolling.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			InvertSelectionScrollConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Blueprints", "Invert selection scroll", false, new ConfigDescription("Invert the direction of selection scrolling.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			RotationIncrementConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<int>("Blueprints", "Rotation increment", 5, new ConfigDescription("Selection rotation increment when scrolling.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			InvertRotationScrollConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Blueprints", "Invert rotation scroll", false, new ConfigDescription("Invert the direction of rotation scrolling.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			SelectionConnectedMarginConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<float>("Blueprints", "Selection connected check margin", 0.01f, new ConfigDescription("Distance of the shell used to check for connectedness.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			ShowGridConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Blueprints", "Show the transform bound grid", false, new ConfigDescription("Shows a grid around the blueprints' bounds to visualize the blueprints' edges.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			TooltipEnabledConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Blueprints", "Tooltip enabled", true, new ConfigDescription("Show a tooltip with a bigger thumbnail for blueprint pieces.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			TooltipBackgroundConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<Color>("Blueprints", "Tooltip Color", new Color(0.13f, 0.13f, 0.13f, 0.65f), new ConfigDescription("Set the background color for the tooltip on blueprint pieces.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			BlueprintUndoQueueNameConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<string>("Blueprints", "Undo queue name", "blueprintqueue", new ConfigDescription("Global name of the blueprint undo queue used for bp.undo and bp.redo commands. Can be set to the same value as other mods' config (if supported) to combine their undo queues.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			AddPlayerNameConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Blueprints", "Add player prefix to file name", true, new ConfigDescription("Add your current player profile name to any blueprint file created with that player.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			BlueprintSearchDirectoryConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<string>("Directories", "Search directory", ".", new ConfigDescription("Base directory to scan (recursively) for blueprints and vbuild files, relative paths are relative to the valheim.exe location", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			BlueprintSaveDirectoryConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<string>("Directories", "Save directory", "BepInEx/config/PlanBuild/blueprints", new ConfigDescription("Directory to save blueprint files, relative paths are relative to the valheim.exe location", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			MarketHotkeyConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<KeyCode>("Keybindings", "Blueprint Marketplace GUI toggle key", (KeyCode)279, new ConfigDescription("Hotkey to show the blueprint marketplace GUI", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			ShiftModifierConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<KeyCode>("Keybindings", "ShiftModifier", (KeyCode)304, new ConfigDescription("First modifier key to change behaviours on various tools (defaults to LeftShift)", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			CtrlModifierConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<KeyCode>("Keybindings", "CtrlModifier", (KeyCode)306, new ConfigDescription("Second modifier key to change behaviours on various tools (defaults to LeftCtrl)", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			AltModifierConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<KeyCode>("Keybindings", "AltModifier", (KeyCode)308, new ConfigDescription("Third modifier key to change behaviours on various tools (defaults to LeftAlt)", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			ToggleConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<KeyCode>("Keybindings", "Toggle", (KeyCode)113, new ConfigDescription("Key to switch between modes on various tools", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			CtrlModifierConfig.SettingChanged += delegate
			{
				foreach (Blueprint value2 in BlueprintManager.LocalBlueprints.Values)
				{
					value2.CreateKeyHint();
				}
			};
			AltModifierConfig.SettingChanged += delegate
			{
				foreach (Blueprint value3 in BlueprintManager.LocalBlueprints.Values)
				{
					value3.CreateKeyHint();
				}
			};
			ShowAllPieces = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Plans", "Plan unknown pieces", false, new ConfigDescription("Show all plans, even for pieces you don't know yet", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = (num -= 1)
			} }));
			RadiusConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<float>("Plans", "Plan totem build radius", 30f, new ConfigDescription("Build radius of the plan totem", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = (num -= 1)
			} }));
			ShowParticleEffects = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Plans", "Plan totem particle effects", true, new ConfigDescription("Show particle effects when building pieces with the plan totem", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = (num -= 1)
			} }));
			ShowAllPieces.SettingChanged += delegate
			{
				PlanManager.UpdateKnownRecipes();
			};
			ConfigTransparentGhostPlacement = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<bool>("Visual", "Transparent Ghost Placement", true, new ConfigDescription("Apply plan shader to ghost placement (currently placing piece)", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			UnsupportedColorConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<Color>("Visual", "Unsupported color", new Color(1f, 1f, 1f, 0.1f), new ConfigDescription("Color of unsupported plan pieces", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			SupportedPlanColorConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<Color>("Visual", "Supported color", new Color(1f, 1f, 1f, 0.5f), new ConfigDescription("Color of supported plan pieces", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			TransparencyConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<float>("Visual", "Transparency", 0.3f, new ConfigDescription("Additional transparency for finer control.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			GlowColorConfig = ((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Bind<Color>("Visual", "Plan totem glow color", Color.cyan, new ConfigDescription("Color of the glowing lines on the Plan totem", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = (num -= 1)
			} }));
			ConfigTransparentGhostPlacement.SettingChanged += UpdateGhostPlanPieceTextures;
			UnsupportedColorConfig.SettingChanged += UpdateAllPlanPieceTextures;
			SupportedPlanColorConfig.SettingChanged += UpdateAllPlanPieceTextures;
			TransparencyConfig.SettingChanged += UpdateAllPlanPieceTextures;
			GlowColorConfig.SettingChanged += UpdateAllPlanTotems;
			CreateCustomButtons();
		}

		private static void CreateCustomButtons()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Expected O, but got Unknown
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			MarketHotkeyButton = new ButtonConfig
			{
				Name = "GUIToggle",
				Config = MarketHotkeyConfig,
				ActiveInCustomGUI = true
			};
			InputManager.Instance.AddButton("marcopogo.PlanBuild", MarketHotkeyButton);
			ShiftModifierButton = new ButtonConfig
			{
				Name = "ShiftModifierButton",
				Config = ShiftModifierConfig
			};
			InputManager.Instance.AddButton("marcopogo.PlanBuild", ShiftModifierButton);
			CtrlModifierButton = new ButtonConfig
			{
				Name = "CtrlModifierButton",
				Config = CtrlModifierConfig
			};
			InputManager.Instance.AddButton("marcopogo.PlanBuild", CtrlModifierButton);
			AltModifierButton = new ButtonConfig
			{
				Name = "AltModifierButton",
				Config = AltModifierConfig
			};
			InputManager.Instance.AddButton("marcopogo.PlanBuild", AltModifierButton);
			ToggleButton = new ButtonConfig
			{
				Name = "ToggleButton",
				Config = ToggleConfig
			};
			InputManager.Instance.AddButton("marcopogo.PlanBuild", ToggleButton);
		}

		private static void UpdateGhostPlanPieceTextures(object sender, EventArgs e)
		{
			PlanManager.UpdateAllPlanPieceTextures();
		}

		private static void UpdateAllPlanPieceTextures(object sender, EventArgs e)
		{
			ShaderHelper.ClearCache();
			PlanManager.UpdateAllPlanPieceTextures();
		}

		private static void UpdateAllPlanTotems(object sender, EventArgs e)
		{
			PlanManager.UpdateAllPlanTotems();
		}
	}
	internal static class Extensions
	{
		public static void Highlight(this WearNTear self, Color color, float highlightTime = 0f)
		{
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: 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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			if (self.m_oldMaterials == null)
			{
				self.m_oldMaterials = new List<OldMeshData>();
				foreach (Renderer highlightRenderer in self.GetHighlightRenderers())
				{
					OldMeshData val = default(OldMeshData);
					val.m_materials = highlightRenderer.sharedMaterials;
					val.m_color = (Color[])(object)new Color[val.m_materials.Length];
					val.m_emissiveColor = (Color[])(object)new Color[val.m_materials.Length];
					for (int i = 0; i < val.m_materials.Length; i++)
					{
						if (val.m_materials[i].HasProperty("_Color"))
						{
							val.m_color[i] = val.m_materials[i].GetColor("_Color");
						}
						if (val.m_materials[i].HasProperty("_EmissionColor"))
						{
							val.m_emissiveColor[i] = val.m_materials[i].GetColor("_EmissionColor");
						}
					}
					val.m_renderer = highlightRenderer;
					self.m_oldMaterials.Add(val);
				}
			}
			foreach (OldMeshData oldMaterial in self.m_oldMaterials)
			{
				if (Object.op_Implicit((Object)(object)oldMaterial.m_renderer))
				{
					Material[] materials = oldMaterial.m_renderer.materials;
					Material[] array = materials;
					foreach (Material val2 in array)
					{
						val2.SetColor("_EmissionColor", color * 0.3f);
						val2.color = color;
					}
				}
			}
			((MonoBehaviour)self).CancelInvoke("ResetHighlight");
			if (highlightTime > 0f)
			{
				((MonoBehaviour)self).Invoke("ResetHighlight", highlightTime);
			}
		}

		public static ZDOID? GetZDOID(this Piece piece)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (piece == null)
			{
				return null;
			}
			ZNetView nview = piece.m_nview;
			if (nview == null)
			{
				return null;
			}
			return nview.GetZDO()?.m_uid;
		}

		public static ZDOID? GetZDOID(this WearNTear wearNTear)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (wearNTear == null)
			{
				return null;
			}
			ZNetView nview = wearNTear.m_nview;
			if (nview == null)
			{
				return null;
			}
			return nview.GetZDO()?.m_uid;
		}
	}
	internal class Patches
	{
		public const string BuildCameraGUID = "org.gittywithexcitement.plugins.valheim.buildCamera";

		public const string CraftFromContainersGUID = "aedenthorn.CraftFromContainers";

		public const string GizmoGUID = "com.rolopogo.gizmo.comfy";

		public const string ValheimRaftGUID = "BepIn.Sarcen.ValheimRAFT";

		public const string ItemDrawersGUID = "mkz.itemdrawers";

		private static Harmony Harmony;

		internal static void Apply()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			Harmony = new Harmony("marcopogo.PlanBuild");
			Harmony.PatchAll(typeof(PlanPiece));
			if (Chainloader.PluginInfos.ContainsKey("org.gittywithexcitement.plugins.valheim.buildCamera"))
			{
				Logger.LogInfo((object)"Applying BuildCamera patches");
				Harmony.PatchAll(typeof(PatcherBuildCamera));
			}
			if (Chainloader.PluginInfos.ContainsKey("aedenthorn.CraftFromContainers"))
			{
				Logger.LogInfo((object)"Applying CraftFromContainers patches");
				Harmony.PatchAll(typeof(PatcherCraftFromContainers));
			}
			if (Chainloader.PluginInfos.ContainsKey("com.rolopogo.gizmo.comfy"))
			{
				Logger.LogInfo((object)"Applying Gizmo patches");
				Harmony.PatchAll(typeof(PatcherGizmo));
			}
			if (Chainloader.PluginInfos.ContainsKey("BepIn.Sarcen.ValheimRAFT"))
			{
				Logger.LogInfo((object)"Applying ValheimRAFT patches");
				Harmony.PatchAll(typeof(PatcherValheimRaft));
			}
		}
	}
	[BepInPlugin("marcopogo.PlanBuild", "PlanBuild", "0.14.2")]
	[BepInDependency("com.jotunn.jotunn", "2.12.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	internal class PlanBuildPlugin : BaseUnityPlugin
	{
		public const string PluginGUID = "marcopogo.PlanBuild";

		public const string PluginName = "PlanBuild";

		public const string PluginVersion = "0.14.2";

		public static PlanBuildPlugin Instance;

		public void Awake()
		{
			Instance = this;
			Assembly assembly = typeof(PlanBuildPlugin).Assembly;
			Config.Init();
			AssetBundle val = AssetUtils.LoadAssetBundleFromResources("blueprints", assembly);
			BlueprintAssets.Load(val);
			val.Unload(false);
			BlueprintManager.Init();
			AssetBundle val2 = AssetUtils.LoadAssetBundleFromResources("planbuild", assembly);
			PlanTotemPrefab.Create(val2);
			PlanCrystalPrefab.Create(val2);
			PlanHammerPrefab.Create(val2);
			val2.Unload(false);
			PlanManager.Init();
			ShaderHelper.PlanShader = Shader.Find("Lux Lit Particles/ Bumped");
			Patches.Apply();
		}

		public void Update()
		{
			if (ZInput.instance != null && (!Object.op_Implicit((Object)(object)Settings.instance) || !((Behaviour)Settings.instance).isActiveAndEnabled))
			{
				if (BlueprintGUI.IsAvailable() && !SelectionSaveGUI.IsVisible() && !TerrainModGUI.IsVisible() && !SelectionGUI.IsVisible() && (Config.AllowMarketHotkey.Value || SynchronizationManager.Instance.PlayerIsAdmin) && ZInput.GetButtonDown(Config.MarketHotkeyButton.Name))
				{
					BlueprintGUI.Instance.Toggle();
				}
				if (BlueprintGUI.IsVisible() && !BlueprintGUI.TextFieldHasFocus() && ZInput.GetButtonDown("Use"))
				{
					BlueprintGUI.Instance.Toggle(shutWindow: true);
					ZInput.ResetButtonStatus("Use");
				}
			}
		}
	}
}
namespace PlanBuild.ModCompat
{
	internal class PatcherBuildCamera
	{
		internal static bool UpdateCamera = true;

		[HarmonyPatch(typeof(Valheim_Build_Camera), "IsTool")]
		[HarmonyPrefix]
		private static bool ValheimBuildCamera_IsTool_Prefix(ItemData itemData, ref bool __result)
		{
			if (itemData?.m_shared.m_name == "$item_blueprintrune" || itemData?.m_shared.m_name == "$item_plan_hammer")
			{
				__result = true;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(Valheim_Build_Camera), "EnableBuildMode")]
		[HarmonyPostfix]
		internal static void ValheimBuildCamera_EnableBuildMode_Postfix()
		{
			UpdateCamera = false;
		}

		[HarmonyPatch(typeof(Valheim_Build_Camera), "DisableBuildMode")]
		[HarmonyPostfix]
		internal static void ValheimBuildCamera_DisableBuildMode_Postfix()
		{
			UpdateCamera = true;
		}
	}
	internal class PatcherCraftFromContainers
	{
		[HarmonyPatch(typeof(PlanPiece), "PlayerHaveResource")]
		[HarmonyPostfix]
		private static void PlanPiece_PlayerHaveResource_Postfix(Humanoid player, string resourceName, ref bool __result)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (!BepInExPlugin.modEnabled.Value || __result)
			{
				return;
			}
			foreach (Container nearbyContainer in BepInExPlugin.GetNearbyContainers(((Component)player).transform.position))
			{
				if (nearbyContainer.GetInventory().HaveItem(resourceName, true))
				{
					__result = true;
					break;
				}
			}
		}

		[HarmonyPatch(typeof(PlanPiece), "PlayerGetResourceCount")]
		[HarmonyPostfix]
		private static void PlanPiece_PlayerGetResourceCount_Postfix(Humanoid player, string resourceName, ref int __result)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (!BepInExPlugin.modEnabled.Value)
			{
				return;
			}
			foreach (Container nearbyContainer in BepInExPlugin.GetNearbyContainers(((Component)player).transform.position))
			{
				__result += nearbyContainer.GetInventory().CountItems(resourceName, -1, true);
			}
		}

		[HarmonyPatch(typeof(PlanPiece), "PlayerRemoveResource")]
		[HarmonyPrefix]
		private static bool PlanPiece_PlayerRemoveResource_Prefix(Humanoid player, string resourceName, int amount)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			if (!BepInExPlugin.modEnabled.Value)
			{
				return true;
			}
			int val = player.GetInventory().CountItems(resourceName, -1, true);
			int num = Math.Min(amount, val);
			player.GetInventory().RemoveItem(resourceName, num, -1, true);
			int num2 = amount - num;
			if (num2 > 0)
			{
				foreach (Container nearbyContainer in BepInExPlugin.GetNearbyContainers(((Component)player).transform.position))
				{
					int val2 = nearbyContainer.GetInventory().CountItems(resourceName, -1, true);
					num = Math.Min(num2, val2);
					nearbyContainer.GetInventory().RemoveItem(resourceName, num, -1, true);
					num2 -= num;
					if (num2 < 0)
					{
						break;
					}
				}
			}
			return false;
		}
	}
	internal class PatcherValheimRaft
	{
		private PatcherValheimRaft()
		{
		}

		[HarmonyPatch(typeof(PlanPiece), "CalculateSupported")]
		[HarmonyPrefix]
		private static bool PlanPiece_CalculateSupported_Prefix(PlanPiece __instance, ref bool __result)
		{
			if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponentInParent<MoveableBaseRootComponent>()))
			{
				__result = true;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlanPiece), "OnPieceReplaced")]
		[HarmonyPrefix]
		private static void PlanPiece_OnPieceReplaced_Postfix(GameObject originatingPiece, GameObject placedPiece)
		{
			MoveableBaseRootComponent componentInParent = originatingPiece.GetComponentInParent<MoveableBaseRootComponent>();
			if (Object.op_Implicit((Object)(object)componentInParent))
			{
				componentInParent.AddNewPiece(placedPiece.GetComponent<Piece>());
			}
		}

		[HarmonyPatch(typeof(PlacementComponent), "OnPiecePlaced")]
		[HarmonyPrefix]
		private static void BlueprintManager_OnPiecePlaced_Postfix(GameObject placedPiece)
		{
			ValheimRAFT_Patch.PlacedPiece(Player.m_localPlayer, placedPiece);
		}
	}
	internal class PatcherGizmo
	{
		[HarmonyPatch(typeof(PlayerPatch), "UpdatePlacementPostfix")]
		[HarmonyPrefix]
		private static bool ComfyGizmo_UpdatePlacementPostfix_Prefix()
		{
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer) || !Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces) || !Object.op_Implicit((Object)(object)Player.m_localPlayer.m_placementGhost) || !Object.op_Implicit((Object)(object)ComfyGizmo.GizmoRoot))
			{
				return true;
			}
			ToolComponentBase toolComponentBase = default(ToolComponentBase);
			if (Player.m_localPlayer.m_placementGhost.TryGetComponent<ToolComponentBase>(ref toolComponentBase) && toolComponentBase.SuppressGizmo)
			{
				((Component)ComfyGizmo.GizmoRoot).gameObject.SetActive(false);
				return false;
			}
			if (((Object)Player.m_localPlayer.m_buildPieces).name.StartsWith("_PlanHammerPieceTable", StringComparison.Ordinal) && ((Object)Player.m_localPlayer.m_placementGhost).name.StartsWith("piece_plan_delete", StringComparison.Ordinal))
			{
				((Component)ComfyGizmo.GizmoRoot).gameObject.SetActive(false);
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(ComfyGizmo), "Rotate")]
		[HarmonyPrefix]
		private static bool ComfyGizmo_Rotate_Prefix()
		{
			return CheckPlanBuildTool();
		}

		[HarmonyPatch(typeof(ComfyGizmo), "RotateLocalFrame")]
		[HarmonyPrefix]
		private static bool ComfyGizmo_RotateLocalFrame_Prefix()
		{
			return CheckPlanBuildTool();
		}

		private static bool CheckPlanBuildTool()
		{
			if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces) && ((Object)Player.m_localPlayer.m_buildPieces).name.StartsWith("_BlueprintPieceTable", StringComparison.Ordinal) && (ZInput.GetButton(Config.ShiftModifierButton.Name) || ZInput.GetButton(Config.AltModifierButton.Name) || ZInput.GetButton(Config.CtrlModifierButton.Name)))
			{
				return false;
			}
			return true;
		}
	}
}
namespace PlanBuild.Utils
{
	internal class ShapedProjector : MonoBehaviour
	{
		internal enum ProjectorShape
		{
			Circle,
			Square
		}

		private static GameObject _segment;

		private ProjectorShape Shape;

		private float Radius = 10f;

		private int Rotation;

		private CircleProjector Circle;

		private SquareProjector Square;

		private static GameObject SelectionSegment
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)_segment))
				{
					GameObject prefab = PrefabManager.Instance.GetPrefab("piece_workbench");
					_segment = Object.Instantiate<GameObject>(prefab.GetComponentInChildren<CircleProjector>().m_prefab);
					_segment.SetActive(false);
				}
				return _segment;
			}
		}

		public void Enable()
		{
			if (Shape == ProjectorShape.Circle && (Object)(object)Circle == (Object)null)
			{
				Circle = ((Component)this).gameObject.AddComponent<CircleProjector>();
				Circle.m_prefab = SelectionSegment;
				Circle.m_prefab.SetActive(true);
				Circle.m_radius = Radius;
				Circle.m_nrOfSegments = (int)Radius * 4;
			}
			if (Shape == ProjectorShape.Square && (Object)(object)Square == (Object)null)
			{
				Square = ((Component)this).gameObject.AddComponent<SquareProjector>();
				Square.prefab = SelectionSegment;
				Square.radius = Radius;
				Square.rotation = Rotation;
			}
		}

		public void Disable()
		{
			if ((Object)(object)Circle != (Object)null)
			{
				foreach (GameObject segment in Circle.m_segments)
				{
					Object.DestroyImmediate((Object)(object)segment);
				}
				Object.DestroyImmediate((Object)(object)Circle);
			}
			if ((Object)(object)Square != (Object)null)
			{
				Square.StopProjecting();
				Object.DestroyImmediate((Object)(object)Square);
			}
		}

		public bool IsEnabled()
		{
			if (Shape == ProjectorShape.Circle && (Object)(object)Circle != (Object)null)
			{
				return true;
			}
			if (Shape == ProjectorShape.Square && (Object)(object)Square != (Object)null)
			{
				return true;
			}
			return false;
		}

		public void ToggleEnabled()
		{
			if (IsEnabled())
			{
				Disable();
			}
			else
			{
				Enable();
			}
		}

		public void SwitchShape()
		{
			if (Shape == ProjectorShape.Circle)
			{
				SetShape(ProjectorShape.Square);
			}
			else if (Shape == ProjectorShape.Square)
			{
				SetShape(ProjectorShape.Circle);
			}
		}

		public void SetShape(ProjectorShape newShape)
		{
			if (Shape != newShape)
			{
				Disable();
				Shape = newShape;
				Enable();
			}
		}

		public ProjectorShape GetShape()
		{
			return Shape;
		}

		public Vector3 GetPosition()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return ((Component)this).transform.position;
		}

		public void SetRadius(float newRadius)
		{
			Radius = newRadius;
			if (Shape == ProjectorShape.Circle && (Object)(object)Circle != (Object)null)
			{
				Circle.m_radius = Radius;
				Circle.m_nrOfSegments = (int)Radius * 4;
			}
			if (Shape == ProjectorShape.Square && (Object)(object)Square != (Object)null)
			{
				Square.radius = Radius;
			}
		}

		public float GetRadius()
		{
			return Radius;
		}

		public void SetRotation(int newRotation)
		{
			Rotation = newRotation;
			if (Shape == ProjectorShape.Square && (Object)(object)Square != (Object)null)
			{
				Square.rotation = Rotation;
			}
		}

		public int GetRotation()
		{
			return Rotation;
		}

		public void EnableMask()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			if (Shape == ProjectorShape.Circle && (Object)(object)Circle != (Object)null && LayerMask.op_Implicit(Circle.m_mask) != 2048)
			{
				Circle.m_mask = LayerMask.op_Implicit(2048);
			}
			if (Shape == ProjectorShape.Square && (Object)(object)Square != (Object)null && LayerMask.op_Implicit(Square.mask) != 2048)
			{
				Square.mask = LayerMask.op_Implicit(2048);
			}
		}

		public void DisableMask()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			if (Shape == ProjectorShape.Circle && (Object)(object)Circle != (Object)null && LayerMask.op_Implicit(Circle.m_mask) != 0)
			{
				Circle.m_mask = LayerMask.op_Implicit(0);
			}
			if (Shape == ProjectorShape.Square && (Object)(object)Square != (Object)null && LayerMask.op_Implicit(Square.mask) != 0)
			{
				Square.mask = LayerMask.op_Implicit(0);
			}
		}
	}
	internal class SquareProjector : MonoBehaviour
	{
		public float cubesSpeed = 1f;

		public float radius = 2f;

		public int rotation;

		public GameObject prefab;

		private GameObject cube;

		private float cubesThickness = 0.15f;

		private float cubesHeight = 0.1f;

		private float cubesLength = 1f;

		public LayerMask mask = LayerMask.op_Implicit(0);

		private float updatesPerSecond = 60f;

		private int cubesPerSide;

		private float sideLength;

		private float cubesLength100;

		private float sideLengthHalved;

		private Quaternion translatedRotation;

		private bool isRunning;

		private Transform center;

		private Transform parentNorth;

		private Transform parentEast;

		private Transform parentSouth;

		private Transform parentWest;

		private List<Transform> cubesNorth = new List<Transform>();

		private List<Transform> cubesEast = new List<Transform>();

		private List<Transform> cubesSouth = new List<Transform>();

		private List<Transform> cubesWest = new List<Transform>();

		public void Start()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			cube = new GameObject("cube");
			GameObject val = Object.Instantiate<GameObject>(prefab);
			val.transform.SetParent(cube.transform);
			val.transform.localScale = new Vector3(1f, 1f, 1f);
			val.transform.localPosition = new Vector3(0f, 0f, -0.5f);
			cube.transform.localScale = new Vector3(cubesThickness, cubesHeight, cubesLength);
			cube.SetActive(false);
			RefreshStuff();
			StartProjecting();
		}

		private void OnEnable()
		{
			if (!isRunning && !((Object)(object)parentNorth == (Object)null))
			{
				isRunning = true;
				((MonoBehaviour)this).StartCoroutine(AnimateElements(parentNorth, cubesNorth));
				((MonoBehaviour)this).StartCoroutine(AnimateElements(parentEast, cubesEast));
				((MonoBehaviour)this).StartCoroutine(AnimateElements(parentSouth, cubesSouth));
				((MonoBehaviour)this).StartCoroutine(AnimateElements(parentWest, cubesWest));
			}
		}

		private void OnDisable()
		{
			isRunning = false;
		}

		public void StartProjecting()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			if (!isRunning)
			{
				isRunning = true;
				center = new GameObject("center").transform;
				center.SetParent(((Component)this).transform);
				center.position = ((Component)this).transform.position;
				center.rotation = Quaternion.Euler(0f, (float)rotation, 0f);
				parentNorth = CreateElements(rotation, cubesNorth);
				parentEast = CreateElements(rotation + 90, cubesEast);
				parentSouth = CreateElements(rotation + 180, cubesSouth);
				parentWest = CreateElements(rotation + 270, cubesWest);
				((MonoBehaviour)this).StartCoroutine(AnimateElements(parentNorth, cubesNorth));
				((MonoBehaviour)this).StartCoroutine(AnimateElements(parentEast, cubesEast));
				((MonoBehaviour)this).StartCoroutine(AnimateElements(parentSouth, cubesSouth));
				((MonoBehaviour)this).StartCoroutine(AnimateElements(parentWest, cubesWest));
			}
		}

		public void StopProjecting()
		{
			if (isRunning)
			{
				isRunning = false;
				((MonoBehaviour)this).StopAllCoroutines();
				Object.Destroy((Object)(object)((Component)center).gameObject);
				cubesNorth.Clear();
				cubesEast.Clear();
				cubesSouth.Clear();
				cubesWest.Clear();
			}
		}

		private void RefreshStuff()
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			cubesPerSide = Mathf.FloorToInt(radius);
			sideLength = radius * 2f;
			cubesLength100 = sideLength / (float)cubesPerSide;
			sideLengthHalved = sideLength / 2f;
			translatedRotation = Quaternion.Euler(0f, (float)rotation, 0f);
			if (isRunning)
			{
				if (cubesPerSide + 1 != cubesNorth.Count)
				{
					StopProjecting();
					StartProjecting();
				}
				if (translatedRotation != center.rotation)
				{
					center.rotation = translatedRotation;
				}
			}
		}

		private Transform CreateElements(int localRotation, List<Transform> cubes)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = new GameObject(localRotation.ToString()).transform;
			((Component)transform).transform.position = center.position;
			((Component)transform).transform.RotateAround(center.position, Vector3.up, (float)localRotation);
			transform.SetParent(center);
			for (int i = 0; i < cubesPerSide + 1; i++)
			{
				cubes.Add(Object.Instantiate<GameObject>(cube, ((Component)this).transform.position, Quaternion.identity, transform).transform);
			}
			Transform transform2 = new GameObject("Start").transform;
			Transform transform3 = new GameObject("End").transform;
			transform2.SetParent(transform);
			transform3.SetParent(transform);
			for (int j = 0; j < cubes.Count; j++)
			{
				cubes[j].forward = transform.right;
			}
			return transform;
		}

		private IEnumerator AnimateElements(Transform cubeParent, List<Transform> cubes)
		{
			Transform a = cubeParent.Find("Start");
			Transform b = cubeParent.Find("End");
			Vector3 localScale = default(Vector3);
			RaycastHit val4 = default(RaycastHit);
			while (true)
			{
				RefreshStuff();
				a.position = cubeParent.forward * (sideLengthHalved - cubesThickness / 2f) - cubeParent.right * sideLengthHalved + cubeParent.position;
				b.position = cubeParent.forward * (sideLengthHalved - cubesThickness / 2f) + cubeParent.right * sideLengthHalved + cubeParent.position;
				Vector3 val = b.position - a.position;
				for (int i = 0; i < cubes.Count; i++)
				{
					Transform val2 = cubes[i];
					((Component)val2).gameObject.SetActive(true);
					float num = (Time.time * cubesSpeed + sideLength / (float)cubesPerSide * (float)i) % (sideLength + cubesLength100);
					Vector3 val3;
					if (num < cubesLength)
					{
						val3 = ((Vector3)(ref val)).normalized * num + a.position;
						((Vector3)(ref localScale))..ctor(val2.localScale.x, val2.localScale.y, cubesLength - (cubesLength - num));
					}
					else if (num >= sideLength && num <= sideLength + cubesLength)
					{
						val3 = ((Vector3)(ref val)).normalized * sideLength + a.position;
						((Vector3)(ref localScale))..ctor(val2.localScale.x, val2.localScale.y, cubesLength - (num - sideLength));
					}
					else
					{
						if (num >= sideLength && num >= sideLength + cubesLength)
						{
							((Component)val2).gameObject.SetActive(false);
							continue;
						}
						val3 = ((Vector3)(ref val)).normalized * num + a.position;
						((Vector3)(ref localScale))..ctor(val2.localScale.x, val2.localScale.y, cubesLength);
					}
					if (Physics.Raycast(val3 + Vector3.up * 500f, Vector3.down, ref val4, 1000f, ((LayerMask)(ref mask)).value))
					{
						val3.y = ((RaycastHit)(ref val4)).point.y;
					}
					val2.position = val3;
					val2.localScale = localScale;
				}
				yield return (object)new WaitForSecondsRealtime(1f / updatesPerSecond);
			}
		}
	}
	internal class DebugUtils
	{
		public static void InitLaserGrid(GameObject gameObject, Bounds bounds)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = gameObject.transform;
			Material material = Resources.FindObjectsOfTypeAll<Material>().First((Material k) => ((Object)k).name == "Default-Line");
			int num = 0;
			for (int i = -1; i <= 1; i++)
			{
				for (int j = -1; j <= 1; j++)
				{
					Color color = ((i == 0 && j == 0) ? Color.red : Color.gray);
					CreateLaser(transform, num++, bounds, new Vector3(-1f, (float)i, (float)j), new Vector3(1f, (float)i, (float)j), material, color);
					CreateLaser(transform, num++, bounds, new Vector3((float)i, -1f, (float)j), new Vector3((float)i, 1f, (float)j), material, color);
					CreateLaser(transform, num++, bounds, new Vector3((float)i, (float)j, -1f), new Vector3((float)i, (float)j, 1f), material, color);
				}
			}
		}

		private static void CreateLaser(Transform parent, int i, Bounds bounds, Vector3 first, Vector3 second, Material material, Color color)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("laser_" + i, new Type[1] { typeof(LineRenderer) });
			val.transform.SetParent(parent);
			LineRenderer component = val.GetComponent<LineRenderer>();
			component.useWorldSpace = false;
			((Renderer)component).material = material;
			component.startColor = color;
			component.endColor = color;
			component.startWidth = 0.005f;
			component.endWidth = 0.005f;
			Vector3 extents = ((Bounds)(ref bounds)).extents;
			component.SetPositions((Vector3[])(object)new Vector3[2]
			{
				((Bounds)(ref bounds)).center + Vector3.Scale(first, extents),
				((Bounds)(ref bounds)).center + Vector3.Scale(second, extents)
			});
		}
	}
	public class ShaderHelper
	{
		public enum ShaderState
		{
			Supported,
			Floating,
			Skuld
		}

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

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

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

		public static Shader PlanShader;

		public static void ClearCache()
		{
			UnsupportedMaterialDict.Clear();
			SupportedMaterialDict.Clear();
		}

		public static Texture2D GetTexture(Color color)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(1, 1);
			val.SetPixel(0, 0, color);
			return val;
		}

		public static Texture2D CreateScaledTexture(Texture2D texture, int width)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			Texture2D val = new Texture2D(((Texture)texture).width, ((Texture)texture).height, texture.format, false);
			val.SetPixels(texture.GetPixels());
			val.Apply();
			ScaleTexture(val, width);
			return val;
		}

		public static void ScaleTexture(Texture2D texture, int width)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(((Texture)texture).width, ((Texture)texture).height, texture.format, false);
			val.SetPixels(texture.GetPixels());
			val.Apply();
			int num = (int)Math.Round((float)width * (float)((Texture)texture).height / (float)((Texture)texture).width);
			texture.Resize(width, num);
			texture.Apply();
			Color[] pixels = texture.GetPixels(0);
			float num2 = 1f / (float)width;
			float num3 = 1f / (float)num;
			for (int i = 0; i < pixels.Length; i++)
			{
				pixels[i] = val.GetPixelBilinear(num2 * ((float)i % (float)width), num3 * Mathf.Floor((float)i / (float)width));
			}
			texture.SetPixels(pixels, 0);
			texture.Apply();
			Object.Destroy((Object)(object)val);
		}

		public static List<Renderer> GetRenderers(GameObject gameObject)
		{
			List<Renderer> list = new List<Renderer>();
			list.AddRange((IEnumerable<Renderer>)(object)gameObject.GetComponentsInChildren<MeshRenderer>());
			list.AddRange((IEnumerable<Renderer>)(object)gameObject.GetComponentsInChildren<SkinnedMeshRenderer>());
			return list;
		}

		public static void UpdateTextures(GameObject gameObject, ShaderState shaderState)
		{
			WearNTear val = default(WearNTear);
			if (gameObject.TryGetComponent<WearNTear>(ref val) && val.m_oldMaterials != null)
			{
				val.ResetHighlight();
			}
			foreach (Renderer renderer in GetRenderers(gameObject))
			{
				if ((Object)(object)renderer.sharedMaterial != (Object)null)
				{
					Material[] sharedMaterials = renderer.sharedMaterials;
					UpdateMaterials(shaderState, sharedMaterials);
					renderer.sharedMaterials = sharedMaterials;
					renderer.shadowCastingMode = (ShadowCastingMode)0;
				}
			}
		}

		private static void UpdateMaterials(ShaderState shaderState, Material[] sharedMaterials)
		{
			for (int i = 0; i < sharedMaterials.Length; i++)
			{
				Material val = sharedMaterials[i];
				if (!((Object)(object)val == (Object)null))
				{
					if (!OriginalMaterialDict.ContainsKey(((Object)val).name))
					{
						OriginalMaterialDict[((Object)val).name] = val;
					}
					sharedMaterials[i] = GetMaterial(shaderState, val);
				}
			}
		}

		private static Material GetMaterial(ShaderState shaderState, Material originalMaterial)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			float value = Config.TransparencyConfig.Value;
			value *= value;
			switch (shaderState)
			{
			case ShaderState.Skuld:
				return OriginalMaterialDict[((Object)originalMaterial).name];
			case ShaderState.Supported:
			{
				if (!SupportedMaterialDict.TryGetValue(((Object)originalMaterial).name, out var value4))
				{
					value4 = new Material(originalMaterial)
					{
						name = ((Object)originalMaterial).name
					};
					value4.SetOverrideTag("RenderType", "Transparent");
					value4.shader = PlanShader;
					Color value5 = Config.SupportedPlanColorConfig.Value;
					value5.a *= value;
					value4.color = value5;
					value4.EnableKeyword("_EMISSION");
					value4.DisableKeyword("DIRECTIONAL");
					SupportedMaterialDict[((Object)originalMaterial).name] = value4;
				}
				return value4;
			}
			case ShaderState.Floating:
			{
				if (!UnsupportedMaterialDict.TryGetValue(((Object)originalMaterial).name, out var value2))
				{
					value2 = new Material(originalMaterial)
					{
						name = ((Object)originalMaterial).name
					};
					value2.SetOverrideTag("RenderType", "Transparent");
					value2.shader = PlanShader;
					Color value3 = Config.UnsupportedColorConfig.Value;
					value3.a *= value;
					value2.color = value3;
					value2.EnableKeyword("_EMISSION");
					value2.DisableKeyword("DIRECTIONAL");
					UnsupportedMaterialDict[((Object)originalMaterial).name] = value2;
				}
				return value2;
			}
			default:
				throw new ArgumentException("Unknown shaderState: " + shaderState);
			}
		}

		internal static void SetEmissionColor(GameObject gameObject, Color color)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			foreach (Renderer renderer in GetRenderers(gameObject))
			{
				if (renderer.sharedMaterials.Length != 0)
				{
					SetEmissionColor(renderer.materials, color);
				}
			}
		}

		private static void SetEmissionColor(Material[] sharedMaterials, Color color)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			foreach (Material val in sharedMaterials)
			{
				if (val.HasProperty("_EmissionColor"))
				{
					val.SetColor("_EmissionColor", color);
				}
			}
		}

		public static Texture2D FromHeightmap(Heightmap terrain)
		{
			//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)
			return FromHeightmap(terrain, Color.gray, Color.black);
		}

		public static Texture2D FromHeightmap(Heightmap terrain, Color bandColor, Color bkgColor)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			int width = terrain.m_width;
			int width2 = terrain.m_width;
			Texture2D val = new Texture2D(width, width2)
			{
				anisoLevel = 16
			};
			Color[] array = (Color[])(object)new Color[width * width2];
			for (int i = 0; i < width2; i++)
			{
				for (int j = 0; j < width; j++)
				{
					array[i * width + j] = bkgColor;
				}
			}
			float num = 1f;
			float num2 = 0f;
			for (int k = 0; k < width2; k++)
			{
				for (int l = 0; l < width; l++)
				{
					float height = terrain.GetHeight(l, k);
					if (num > height)
					{
						num = height;
					}
					if (num2 < height)
					{
						num2 = height;
					}
				}
			}
			float num3 = 1f;
			List<float> list = new List<float>();
			for (float num4 = num + num3; num4 < num2; num4 += num3)
			{
				list.Add(num4);
			}
			bool[,] array2 = new bool[width, width2];
			for (int m = 0; m < list.Count; m++)
			{
				for (int n = 0; n < width2; n++)
				{
					for (int num5 = 0; num5 < width; num5++)
					{
						if (terrain.GetHeight(num5, n) >= list[m])
						{
							array2[num5, n] = true;
						}
						else
						{
							array2[num5, n] = false;
						}
					}
				}
				for (int num6 = 1; num6 < width2 - 1; num6++)
				{
					for (int num7 = 1; num7 < width - 1; num7++)
					{
						if (array2[num7, num6] && (!array2[num7 - 1, num6] || !array2[num7 + 1, num6] || !array2[num7, num6 - 1] || !array2[num7, num6 + 1]))
						{
							int num8 = (width2 - num6 - 1) * width + (width - num7 - 1);
							array[num8] = bandColor;
						}
					}
				}
			}
			val.SetPixels(array);
			val.Apply();
			return val;
		}
	}
}
namespace PlanBuild.Plans
{
	internal class PlanCommands
	{
		private class PrintBlacklistCommand : ConsoleCommand
		{
			public override string Name => "plan.blacklist.print";

			public override string Help => "Print out the server's plan blacklist";

			public override void Run(string[] args)
			{
				if (Object.op_Implicit((Object)(object)ZNet.instance))
				{
					if (!SynchronizationManager.Instance.PlayerIsAdmin)
					{
						Console.instance.Print("You need to be admin for this");
					}
					else
					{
						Console.instance.Print(GeneralExtensions.Join<string>((IEnumerable<string>)PlanBlacklist.GetNames(), (Func<string, string>)null, ", ") ?? "");
					}
				}
			}
		}

		private class AddBlacklistCommand : ConsoleCommand
		{
			public override string Name => "plan.blacklist.add";

			public override string Help => "[prefab_name] Add a prefab to the server's plan blacklist";

			public override void Run(string[] args)
			{
				if (!Object.op_Implicit((Object)(object)ZNet.instance))
				{
					return;
				}
				if (!SynchronizationManager.Instance.PlayerIsAdmin)
				{
					Console.instance.Print("You need to be admin for this");
					return;
				}
				if (args.Length != 1 || string.IsNullOrWhiteSpace(args[0]))
				{
					Console.instance.Print("Usage: " + ((ConsoleCommand)this).Name + " [prefab_name]");
					return;
				}
				string text = args[0].Trim();
				GameObject prefab = PrefabManager.Instance.GetPrefab(text);
				if (!Object.op_Implicit((Object)(object)prefab))
				{
					Console.instance.Print("Prefab " + text + " does not exist");
				}
				else if (!Object.op_Implicit((Object)(object)prefab.GetComponent<Piece>()))
				{
					Console.instance.Print("Prefab " + text + " has no piece component");
				}
				else
				{
					PlanBlacklist.Add(text);
				}
			}

			public override List<string> CommandOptionList()
			{
				return ZNetScene.instance.GetPrefabNames();
			}
		}

		private class RemoveBlacklistCommand : ConsoleCommand
		{
			public override string Name => "plan.blacklist.remove";

			public override string Help => "[prefab_name] Removes a prefab from the server's plan blacklist";

			public override void Run(string[] args)
			{
				if (Object.op_Implicit((Object)(object)ZNet.instance))
				{
					if (!SynchronizationManager.Instance.PlayerIsAdmin)
					{
						Console.instance.Print("You need to be admin for this");
						return;
					}
					if (args.Length != 1 || string.IsNullOrWhiteSpace(args[0]))
					{
						Console.instance.Print("Usage: " + ((ConsoleCommand)this).Name + " [prefab_name]");
						return;
					}
					string prefabName = args[0].Trim();
					PlanBlacklist.Remove(prefabName);
				}
			}

			public override List<string> CommandOptionList()
			{
				return PlanBlacklist.GetNames();
			}
		}

		public static void Init()
		{
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new PrintBlacklistCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new AddBlacklistCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new RemoveBlacklistCommand());
		}
	}
	internal class PlanBlacklist
	{
		private static readonly List<string> Names = new List<string>();

		private static readonly List<int> Hashes = new List<int>();

		public static void Init()
		{
			Reload();
			SynchronizationManager.OnConfigurationSynchronized += delegate
			{
				Reload();
			};
			SynchronizationManager.OnAdminStatusChanged += PlanManager.UpdateKnownRecipes;
		}

		public static void Reload()
		{
			Names.Clear();
			Hashes.Clear();
			foreach (string item in from x in Config.PlanBlacklistConfig.Value.Split(new char[1] { ',' })
				select x.Trim() into x
				where !string.IsNullOrEmpty(x)
				select x)
			{
				int stableHashCode = StringExtensionMethods.GetStableHashCode(item);
				if (!Hashes.Contains(stableHashCode))
				{
					Logger.LogDebug((object)("Adding " + item + " to plan blacklist"));
					Names.Add(item);
					Hashes.Add(stableHashCode);
				}
			}
			PlanManager.UpdateKnownRecipes();
		}

		public static List<string> GetNames()
		{
			return Names.OrderBy((string x) => x).ToList();
		}

		public static void Add(string prefabName)
		{
			if (!SynchronizationManager.Instance.PlayerIsAdmin)
			{
				return;
			}
			int stableHashCode = StringExtensionMethods.GetStableHashCode(prefabName.Trim());
			if (!Hashes.Contains(stableHashCode))
			{
				Names.Add(prefabName);
				Hashes.Add(stableHashCode);
				Config.PlanBlacklistConfig.Value = GeneralExtensions.Join<string>((IEnumerable<string>)Names.OrderBy((string x) => x), (Func<string, string>)null, ", ");
				((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Reload();
			}
		}

		public static void Remove(string prefabName)
		{
			if (!SynchronizationManager.Instance.PlayerIsAdmin)
			{
				return;
			}
			int stableHashCode = StringExtensionMethods.GetStableHashCode(prefabName.Trim());
			if (Hashes.Contains(stableHashCode))
			{
				Names.Remove(prefabName);
				Hashes.Remove(stableHashCode);
				Config.PlanBlacklistConfig.Value = GeneralExtensions.Join<string>((IEnumerable<string>)Names.OrderBy((string x) => x), (Func<string, string>)null, ", ");
				((BaseUnityPlugin)PlanBuildPlugin.Instance).Config.Reload();
			}
		}

		public static bool Contains(PlanPiecePrefab planPiecePrefab)
		{
			if (SynchronizationManager.Instance.PlayerIsAdmin)
			{
				return false;
			}
			if (!Object.op_Implicit((Object)(object)planPiecePrefab.OriginalPiece))
			{
				return false;
			}
			return Hashes.Contains(planPiecePrefab.OriginalHash);
		}

		public static bool Contains(Piece piece)
		{
			if (SynchronizationManager.Instance.PlayerIsAdmin)
			{
				return false;
			}
			if (!Object.op_Implicit((Object)(object)piece))
			{
				return false;
			}
			int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)piece).name.Split(new char[1] { '(' })[0].Trim());
			return Hashes.Contains(stableHashCode);
		}

		public static bool Contains(string pieceName)
		{
			if (SynchronizationManager.Instance.PlayerIsAdmin)
			{
				return false;
			}
			if (string.IsNullOrEmpty(pieceName))
			{
				return false;
			}
			int stableHashCode = StringExtensionMethods.GetStableHashCode(pieceName);
			return Hashes.Contains(stableHashCode);
		}
	}
	internal class PlanDB
	{
		private class PieceRequirements
		{
			private readonly Dictionary<string, int> requirements;

			public PieceRequirements(Dictionary<string, int> requirements)
			{
				this.requirements = requirements;
			}

			public override int GetHashCode()
			{
				int num = 13;
				IOrderedEnumerable<KeyValuePair<string, int>> orderedEnumerable = requirements.OrderBy((KeyValuePair<string, int> kvp) => kvp.Key);
				foreach (KeyValuePair<string, int> item in orderedEnumerable)
				{
					num = num * 7 + item.Key.GetHashCode();
					num = num * 7 + item.Value.GetHashCode();
				}
				return num;
			}

			public override bool Equals(object obj)
			{
				if (!(obj is PieceRequirements pieceRequirements))
				{
					return false;
				}
				if (requirements.Count == pieceRequirements.requirements.Count)
				{
					return !requirements.Except(pieceRequirements.requirements).Any();
				}
				return false;
			}

			public override string ToString()
			{
				return string.Join(", ", requirements.Select((KeyValuePair<string, int> x) => x.Key + ":" + x.Value));
			}
		}

		private static PlanDB _instance;

		public readonly Dictionary<string, Piece> PlanToOriginalMap = new Dictionary<string, Piece>();

		public readonly Dictionary<string, PlanPiecePrefab> PlanPiecePrefabs = new Dictionary<string, PlanPiecePrefab>();

		public Dictionary<string, List<Piece>> NamePiecePrefabMapping = new Dictionary<string, List<Piece>>();

		public static PlanDB Instance => _instance ?? (_instance = new PlanDB());

		public void ScanPieceTables()
		{
			Logger.LogDebug((object)"Scanning PieceTables for Pieces");
			PieceTable pieceTable = PieceManager.Instance.GetPieceTable("_PlanHammerPieceTable");
			foreach (GameObject item in ObjectDB.instance.m_items)
			{
				PieceTable val = item.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces;
				if ((Object)(object)val == (Object)null || ((Object)val).name.Equals("_PlanHammerPieceTable") || ((Object)val).name.Equals("_BlueprintPieceTable"))
				{
					continue;
				}
				foreach (GameObject piece in val.m_pieces)
				{
					if (!Object.op_Implicit((Object)(object)piece))
					{
						Logger.LogWarning((object)("Invalid prefab in " + ((Object)item).name + " PieceTable"));
						continue;
					}
					Piece component = piece.GetComponent<Piece>();
					if (!Object.op_Implicit((Object)(object)component))
					{
						Logger.LogWarning((object)("Recipe in " + ((Object)item).name + " has no Piece?! " + ((Object)piece).name));
						continue;
					}
					try
					{
						if (!(((Object)component).name == "piece_repair") && !PlanPiecePrefabs.ContainsKey(((Object)component).name) && CanCreatePlan(component) && EnsurePrefabRegistered(component))
						{
							PlanPiecePrefab planPiecePrefab = new PlanPiecePrefab(component);
							PlanToOriginalMap.Add(((Object)((CustomPiece)planPiecePrefab).PiecePrefab).name, planPiecePrefab.OriginalPiece);
							PrefabManager.Instance.RegisterToZNetScene(((CustomPiece)planPiecePrefab).PiecePrefab);
							PieceManager.Instance.AddPiece((CustomPiece)(object)planPiecePrefab);
							PlanPiecePrefabs.Add(((Object)component).name, planPiecePrefab);
							if (!NamePiecePrefabMapping.TryGetValue(component.m_name, out var value))
							{
								value = new List<Piece>();
								NamePiecePrefabMapping.Add(component.m_name, value);
							}
							value.Add(component);
							if (!pieceTable.m_pieces.Contains(((CustomPiece)planPiecePrefab).PiecePrefab))
							{
								pieceTable.m_pieces.Add(((CustomPiece)planPiecePrefab).PiecePrefab);
							}
						}
					}
					catch (Exception arg)
					{
						Logger.LogWarning((object)$"Error while creating plan of {((Object)component).name}: {arg}");
					}
				}
			}
			WarnDuplicatesWithDifferentResources();
		}

		private void WarnDuplicatesWithDifferentResources()
		{
			Dictionary<string, IEnumerable<IGrouping<PieceRequirements, Piece>>> dictionary = new Dictionary<string, IEnumerable<IGrouping<PieceRequirements, Piece>>>();
			foreach (KeyValuePair<string, List<Piece>> item in NamePiecePrefabMapping)
			{
				List<Piece> value = item.Value;
				if (value.Count != 1)
				{
					IEnumerable<IGrouping<PieceRequirements, Piece>> enumerable = from x in value
						group x by GetResourceMap(x);
					if (enumerable.Count() > 1)
					{
						dictionary[item.Key] = enumerable;
					}
				}
			}
			if (!dictionary.Any())
			{
				return;
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("Warning for mod developers:\nMultiple pieces with the same m_name but different resource requirements, this will cause issues with Player.m_knownRecipes!");
			foreach (KeyValuePair<string, IEnumerable<IGrouping<PieceRequirements, Piece>>> item2 in dictionary)
			{
				stringBuilder.AppendLine("Piece.m_name: " + item2.Key);
				foreach (IGrouping<PieceRequirements, Piece> item3 in item2.Value)
				{
					stringBuilder.AppendLine($" Requirements: {item3.Key}");
					stringBuilder.AppendLine(" Pieces: " + string.Join(", ", item3.Select((Piece x) => ((Object)x).name)) + "\n");
				}
			}
			Logger.LogWarning((object)stringBuilder.ToString());
		}

		private PieceRequirements GetResourceMap(Piece y)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(y.m_resources.Length);
			Requirement[] resources = y.m_resources;
			foreach (Requirement val in resources)
			{
				dictionary[val.m_resItem.m_itemData.m_shared.m_name] = val.m_amount;
			}
			return new PieceRequirements(dictionary);
		}

		internal IEnumerable<PlanPiecePrefab> GetPlanPiecePrefabs()
		{
			return PlanPiecePrefabs.Values;
		}

		private bool EnsurePrefabRegistered(Piece piece)
		{
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab = PrefabManager.Instance.GetPrefab(((Object)((Component)piece).gameObject).name);
			if (Object.op_Implicit((Object)(object)prefab))
			{
				return true;
			}
			Logger.LogWarning((object)("Piece " + ((Object)piece).name + " in Hammer not fully registered? Could not find prefab " + ((Object)((Component)piece).gameObject).name));
			if (!ZNetScene.instance.m_prefabs.Contains(((Component)piece).gameObject))
			{
				Logger.LogWarning((object)" Not registered in ZNetScene.m_prefabs! Adding now");
				ZNetScene.instance.m_prefabs.Add(((Component)piece).gameObject);
			}
			if (!ZNetScene.instance.m_namedPrefabs.ContainsKey(StringExtensionMethods.GetStableHashCode(((Object)((Component)piece).gameObject).name)))
			{
				Logger.LogWarning((object)" Not registered in ZNetScene.m_namedPrefabs! Adding now");
				ZNetScene.instance.m_namedPrefabs[StringExtensionMethods.GetStableHashCode(((Object)((Component)piece).gameObject).name)] = ((Component)piece).gameObject;
			}
			Transform parent = ((Component)piece).gameObject.transform.parent;
			GameObject val = ((parent != null) ? ((Component)parent).gameObject : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				Logger.LogWarning((object)" Prefab has no parent?! Adding to Jotunn");
				PrefabManager.Instance.AddPrefab(((Component)piece).gameObject);
			}
			else
			{
				Scene scene = val.scene;
				if (((Scene)(ref scene)).buildIndex != -1)
				{
					Logger.LogWarning((object)" Prefab container not marked as DontDestroyOnLoad! Marking now");
					Object.DontDestroyOnLoad((Object)(object)val);
				}
			}
			return (Object)(object)PrefabManager.Instance.GetPrefab(((Object)((Component)piece).gameObject).name) != (Object)null;
		}

		internal bool FindOriginalByPrefabName(string name, out Piece originalPiece)
		{
			return PlanToOriginalMap.TryGetValue(name, out originalPiece);
		}

		internal bool FindOriginalByPieceName(string m_name, out List<Piece> originalPieces)
		{
			return NamePiecePrefabMapping.TryGetValue(m_name, out originalPieces);
		}

		internal bool FindPlanByPrefabName(string name, out PlanPiecePrefab planPiecePrefab)
		{
			int num = name.IndexOf("(Clone)", StringComparison.Ordinal);
			if (num != -1)
			{
				name = name.Substring(0, num);
			}
			return PlanPiecePrefabs.TryGetValue(name, out planPiecePrefab);
		}

		public bool CanCreatePlan(Piece piece)
		{
			if (piece.m_enabled && (Object)(object)((Component)piece).GetComponent<Plant>() == (Object)null && (Object)(object)((Component)piece).GetComponent<TerrainOp>() == (Object)null && (Object)(object)((Component)piece).GetComponent<TerrainModifier>() == (Object)null && (Object)(object)((Component)piece).GetComponent<Ship>() == (Object)null && (Object)(object)((Component)piece).GetComponent<PlanPiece>() == (Object)null)
			{
				return !((Object)piece).name.Equals("piece_plan_totem");
			}
			return false;
		}
	}
	internal class PlanHammerPrefab
	{
		private class DeletePlansComponent : MonoBehaviour
		{
			private Piece LastHoveredPiece;

			private void Start()
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Expected O, but got Unknown
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Expected O, but got Unknown
				Player.PieceRayTest += new hook_PieceRayTest(Player_PieceRayTest);
				Player.PlacePiece += new hook_PlacePiece(Player_PlacePiece);
				Logger.LogDebug((object)(((Object)((Component)this).gameObject).name + " started"));
			}

			private void OnDestroy()
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Expected O, but got Unknown
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Expected O, but got Unknown
				Player.PlacePiece -= new hook_PlacePiece(Player_PlacePiece);
				Player.PieceRayTest -= new hook_PieceRayTest(Player_PieceRayTest);
				Logger.LogDebug((object)(((Object)((Component)this).gameObject).name + " destroyed"));
			}

			private bool Player_PieceRayTest(orig_PieceRayTest orig, Player self, out Vector3 point, out Vector3 normal, out Piece piece, out Heightmap heightmap, out Collider waterSurface, bool water)
			{
				bool result = orig.Invoke(self, ref point, ref normal, ref piece, ref heightmap, ref waterSurface, water);
				LastHoveredPiece = piece;
				return result;
			}

			private bool Player_PlacePiece(orig_PlacePiece orig, Player self, Piece piece)
			{
				PlanPiece planPiece = default(PlanPiece);
				if (Object.op_Implicit((Object)(object)LastHoveredPiece) && ((Component)LastHoveredPiece).TryGetComponent<PlanPiece>(ref planPiece))
				{
					planPiece.m_wearNTear.Remove();
				}
				return false;
			}
		}

		public const string PlanHammerName = "PlanHammer";

		public const string PlanHammerItemName = "$item_plan_hammer";

		public const string PieceTableName = "_PlanHammerPieceTable";

		public const string PieceDeletePlansName = "piece_plan_delete";

		private static Sprite HammerIcon;

		private static GameObject PieceDeletePlansPrefab;

		private static CustomItem PlanHammerItem;

		public static void Create(AssetBundle planbuildBundle)
		{
			HammerIcon = planbuildBundle.LoadAsset<Sprite>("plan_hammer");
			PieceDeletePlansPrefab = planbuildBundle.LoadAsset<GameObject>("piece_plan_delete");
			PrefabManager.OnVanillaPrefabsAvailable += CreatePlanHammerItem;
			PieceManager.OnPiecesRegistered += CreatePlanTable;
			GUIManager.OnCustomGUIAvailable += CreateCustomKeyHints;
		}

		private static void CreatePlanHammerItem()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			try
			{
				Logger.LogDebug((object)"Creating PlanHammer item");
				ItemConfig val = new ItemConfig();
				val.Name = "$item_plan_hammer";
				val.Description = "$item_plan_hammer_description";
				val.Icons = (Sprite[])(object)new Sprite[1] { HammerIcon };
				val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
				{
					new RequirementConfig
					{
						Item = "Wood",
						Amount = 1
					}
				};
				PlanHammerItem = new CustomItem("PlanHammer", "Hammer", val);
				ItemManager.Instance.AddItem(PlanHammerItem);
				SharedData shared = PlanHammerItem.ItemDrop.m_itemData.m_shared;
				shared.m_useDurability = false;
				shared.m_maxQuality = 1;
				shared.m_weight = 0f;
				shared.m_buildPieces = null;
			}
			catch (Exception arg)
			{
				Logger.LogWarning((object)$"Error caught while creating the PlanHammer item: {arg}");
			}
			finally
			{
				PrefabManager.OnVanillaPrefabsAvailable -= CreatePlanHammerItem;
			}
		}

		private static void CreatePlanTable()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			try
			{
				Logger.LogDebug((object)"Creating PlanHammer piece table");
				IEnumerable<string> source = from x in PieceManager.Instance.GetPieceCategories()
					where x != "Blueprints" && x != "Clipboard" && x != "Tools"
					select x;
				CustomPieceTable val = new CustomPieceTable("_PlanHammerPieceTable", new PieceTableConfig
				{
					CanRemovePieces = true,
					UseCategories = true,
					UseCustomCategories = true,
					CustomCategories = source.ToArray()
				});
				PieceManager.Instance.AddPieceTable(val);
				for (int i = val.PieceTable.m_availablePieces.Count; i < 100; i++)
				{
					val.PieceTable.m_availablePieces.Add(new List<Piece>());
				}
				Array.Resize(ref val.PieceTable.m_selectedPiece, val.PieceTable.m_availablePieces.Count);
				PlanHammerItem.ItemDrop.m_itemData.m_shared.m_buildPieces = val.PieceTable;
				PieceDeletePlansPrefab.AddComponent<DeletePlansComponent>();
				CustomPiece val2 = new CustomPiece(PieceDeletePlansPrefab, "_PlanHammerPieceTable", false);
				PieceManager.Instance.AddPiece(val2);
				PieceManager.Instance.RegisterPieceInPieceTable(PieceDeletePlansPrefab, "_PlanHammerPieceTable", "All");
			}
			catch (Exception arg)
			{
				Logger.LogWarning((object)$"Error caught while creating the PlanHammer table: {arg}");
			}
			finally
			{
				PieceManager.OnPiecesRegistered -= CreatePlanTable;
			}
		}

		private static void CreateCustomKeyHints()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			KeyHintManager instance = KeyHintManager.Instance;
			KeyHintConfig val = new KeyHintConfig();
			val.Item = "PlanHammer";
			val.Piece = "piece_plan_delete";
			val.ButtonConfigs = (ButtonConfig[])(object)new ButtonConfig[1]
			{
				new ButtonConfig
				{
					Name = "Attack",
					HintToken = "$hud_plandelete"
				}
			};
			instance.AddKeyHint(val);
			GUIManager.OnCustomGUIAvailable -= CreateCustomKeyHints;
		}
	}
	internal class OdinLevel : MonoBehaviour, Interactable, Hoverable
	{
		public string GetHoverName()
		{
			return "Level";
		}

		public string GetHoverText()
		{
			return Localization.instance.Localize("[<color=yellow>$KEY_Use</color>] Toggle grid");
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			return true;
		}

		public bool UseItem(Humanoid us

BepInEx/plugins/MMHOOK/MMHOOK_assembly_googleanalytics.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On;
using UnityEngine;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class AdvertiserOptInAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AdvertiserOptInAttribute self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AdvertiserOptInAttribute self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AdvertiserOptInAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AdvertiserOptInAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AdvertiserOptInAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class RangedTooltipAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(RangedTooltipAttribute self, string text, float min, float max);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, RangedTooltipAttribute self, string text, float min, float max);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class RangedTooltipAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.RangedTooltipAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.RangedTooltipAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class TooltipAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(TooltipAttribute self, string text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, TooltipAttribute self, string text);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class TooltipAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.TooltipAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.TooltipAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class Field
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Field self, string parameter);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Field self, string parameter);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_ToString(Field self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_ToString(orig_ToString orig, Field self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public new static event hook_ToString ToString
		{
			add
			{
				HookEndpointManager.Add<hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class Field
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Field.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Field.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public new static event Manipulator ToString
		{
			add
			{
				HookEndpointManager.Modify<On.Field.hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Field.hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class Fields
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Fields self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Fields self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class Fields
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Fields.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Fields.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.Fields.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Fields.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class GAIHandler
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(GAIHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, GAIHandler self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class GAIHandler
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.GAIHandler.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GAIHandler.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class GoogleAnalyticsAndroidV4
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Dispose(GoogleAnalyticsAndroidV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Dispose(orig_Dispose orig, GoogleAnalyticsAndroidV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(GoogleAnalyticsAndroidV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, GoogleAnalyticsAndroidV4 self);

		public static event hook_Dispose Dispose
		{
			add
			{
				HookEndpointManager.Add<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class GoogleAnalyticsAndroidV4
	{
		public static event Manipulator Dispose
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsAndroidV4.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsAndroidV4.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsAndroidV4.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsAndroidV4.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class GoogleAnalyticsMPV3
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_InitializeTracker(GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_InitializeTracker(orig_InitializeTracker orig, GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetTrackerVal(GoogleAnalyticsMPV3 self, Field field, object value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetTrackerVal(orig_SetTrackerVal orig, GoogleAnalyticsMPV3 self, Field field, object value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_AddTrackerVals(GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_AddTrackerVals(orig_AddTrackerVals orig, GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartSession(GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartSession(orig_StartSession orig, GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StopSession(GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StopSession(orig_StopSession orig, GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SendGaHitWithMeasurementProtocol(GoogleAnalyticsMPV3 self, string url);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SendGaHitWithMeasurementProtocol(orig_SendGaHitWithMeasurementProtocol orig, GoogleAnalyticsMPV3 self, string url);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator orig_HandleWWW(GoogleAnalyticsMPV3 self, WWW request);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate IEnumerator hook_HandleWWW(orig_HandleWWW orig, GoogleAnalyticsMPV3 self, WWW request);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_AddRequiredMPParameter_Field_object(GoogleAnalyticsMPV3 self, Field parameter, object value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_AddRequiredMPParameter_Field_object(orig_AddRequiredMPParameter_Field_object orig, GoogleAnalyticsMPV3 self, Field parameter, object value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_AddRequiredMPParameter_Field_string(GoogleAnalyticsMPV3 self, Field parameter, string value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_AddRequiredMPParameter_Field_string(orig_AddRequiredMPParameter_Field_string orig, GoogleAnalyticsMPV3 self, Field parameter, string value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_AddOptionalMPParameter_Field_object(GoogleAnalyticsMPV3 self, Field parameter, object value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_AddOptionalMPParameter_Field_object(orig_AddOptionalMPParameter_Field_object orig, GoogleAnalyticsMPV3 self, Field parameter, object value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_AddOptionalMPParameter_Field_string(GoogleAnalyticsMPV3 self, Field parameter, string value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_AddOptionalMPParameter_Field_string(orig_AddOptionalMPParameter_Field_string orig, GoogleAnalyticsMPV3 self, Field parameter, string value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogScreen(GoogleAnalyticsMPV3 self, AppViewHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogScreen(orig_LogScreen orig, GoogleAnalyticsMPV3 self, AppViewHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogEvent(GoogleAnalyticsMPV3 self, EventHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogEvent(orig_LogEvent orig, GoogleAnalyticsMPV3 self, EventHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogTransaction(GoogleAnalyticsMPV3 self, TransactionHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogTransaction(orig_LogTransaction orig, GoogleAnalyticsMPV3 self, TransactionHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogItem(GoogleAnalyticsMPV3 self, ItemHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogItem(orig_LogItem orig, GoogleAnalyticsMPV3 self, ItemHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogException(GoogleAnalyticsMPV3 self, ExceptionHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogException(orig_LogException orig, GoogleAnalyticsMPV3 self, ExceptionHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogSocial(GoogleAnalyticsMPV3 self, SocialHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogSocial(orig_LogSocial orig, GoogleAnalyticsMPV3 self, SocialHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogTiming(GoogleAnalyticsMPV3 self, TimingHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogTiming(orig_LogTiming orig, GoogleAnalyticsMPV3 self, TimingHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ClearUserIDOverride(GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ClearUserIDOverride(orig_ClearUserIDOverride orig, GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetTrackingCode(GoogleAnalyticsMPV3 self, string trackingCode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetTrackingCode(orig_SetTrackingCode orig, GoogleAnalyticsMPV3 self, string trackingCode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetBundleIdentifier(GoogleAnalyticsMPV3 self, string bundleIdentifier);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetBundleIdentifier(orig_SetBundleIdentifier orig, GoogleAnalyticsMPV3 self, string bundleIdentifier);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAppName(GoogleAnalyticsMPV3 self, string appName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAppName(orig_SetAppName orig, GoogleAnalyticsMPV3 self, string appName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAppVersion(GoogleAnalyticsMPV3 self, string appVersion);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAppVersion(orig_SetAppVersion orig, GoogleAnalyticsMPV3 self, string appVersion);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetLogLevelValue(GoogleAnalyticsMPV3 self, DebugMode logLevel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetLogLevelValue(orig_SetLogLevelValue orig, GoogleAnalyticsMPV3 self, DebugMode logLevel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAnonymizeIP(GoogleAnalyticsMPV3 self, bool anonymizeIP);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAnonymizeIP(orig_SetAnonymizeIP orig, GoogleAnalyticsMPV3 self, bool anonymizeIP);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetDryRun(GoogleAnalyticsMPV3 self, bool dryRun);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetDryRun(orig_SetDryRun orig, GoogleAnalyticsMPV3 self, bool dryRun);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetOptOut(GoogleAnalyticsMPV3 self, bool optOut);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetOptOut(orig_SetOptOut orig, GoogleAnalyticsMPV3 self, bool optOut);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(GoogleAnalyticsMPV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, GoogleAnalyticsMPV3 self);

		public static event hook_InitializeTracker InitializeTracker
		{
			add
			{
				HookEndpointManager.Add<hook_InitializeTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_InitializeTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetTrackerVal SetTrackerVal
		{
			add
			{
				HookEndpointManager.Add<hook_SetTrackerVal>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetTrackerVal>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddTrackerVals AddTrackerVals
		{
			add
			{
				HookEndpointManager.Add<hook_AddTrackerVals>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddTrackerVals>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartSession StartSession
		{
			add
			{
				HookEndpointManager.Add<hook_StartSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StopSession StopSession
		{
			add
			{
				HookEndpointManager.Add<hook_StopSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StopSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SendGaHitWithMeasurementProtocol SendGaHitWithMeasurementProtocol
		{
			add
			{
				HookEndpointManager.Add<hook_SendGaHitWithMeasurementProtocol>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SendGaHitWithMeasurementProtocol>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_HandleWWW HandleWWW
		{
			add
			{
				HookEndpointManager.Add<hook_HandleWWW>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_HandleWWW>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddRequiredMPParameter_Field_object AddRequiredMPParameter_Field_object
		{
			add
			{
				HookEndpointManager.Add<hook_AddRequiredMPParameter_Field_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddRequiredMPParameter_Field_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddRequiredMPParameter_Field_string AddRequiredMPParameter_Field_string
		{
			add
			{
				HookEndpointManager.Add<hook_AddRequiredMPParameter_Field_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddRequiredMPParameter_Field_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddOptionalMPParameter_Field_object AddOptionalMPParameter_Field_object
		{
			add
			{
				HookEndpointManager.Add<hook_AddOptionalMPParameter_Field_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddOptionalMPParameter_Field_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddOptionalMPParameter_Field_string AddOptionalMPParameter_Field_string
		{
			add
			{
				HookEndpointManager.Add<hook_AddOptionalMPParameter_Field_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddOptionalMPParameter_Field_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogScreen LogScreen
		{
			add
			{
				HookEndpointManager.Add<hook_LogScreen>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogScreen>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogEvent LogEvent
		{
			add
			{
				HookEndpointManager.Add<hook_LogEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogTransaction LogTransaction
		{
			add
			{
				HookEndpointManager.Add<hook_LogTransaction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogTransaction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogItem LogItem
		{
			add
			{
				HookEndpointManager.Add<hook_LogItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogException LogException
		{
			add
			{
				HookEndpointManager.Add<hook_LogException>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogException>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogSocial LogSocial
		{
			add
			{
				HookEndpointManager.Add<hook_LogSocial>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogSocial>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogTiming LogTiming
		{
			add
			{
				HookEndpointManager.Add<hook_LogTiming>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogTiming>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ClearUserIDOverride ClearUserIDOverride
		{
			add
			{
				HookEndpointManager.Add<hook_ClearUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ClearUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetTrackingCode SetTrackingCode
		{
			add
			{
				HookEndpointManager.Add<hook_SetTrackingCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetTrackingCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetBundleIdentifier SetBundleIdentifier
		{
			add
			{
				HookEndpointManager.Add<hook_SetBundleIdentifier>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetBundleIdentifier>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetAppName SetAppName
		{
			add
			{
				HookEndpointManager.Add<hook_SetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetAppVersion SetAppVersion
		{
			add
			{
				HookEndpointManager.Add<hook_SetAppVersion>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAppVersion>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetLogLevelValue SetLogLevelValue
		{
			add
			{
				HookEndpointManager.Add<hook_SetLogLevelValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetLogLevelValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetAnonymizeIP SetAnonymizeIP
		{
			add
			{
				HookEndpointManager.Add<hook_SetAnonymizeIP>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAnonymizeIP>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetDryRun SetDryRun
		{
			add
			{
				HookEndpointManager.Add<hook_SetDryRun>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetDryRun>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetOptOut SetOptOut
		{
			add
			{
				HookEndpointManager.Add<hook_SetOptOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetOptOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class GoogleAnalyticsMPV3
	{
		public static event Manipulator InitializeTracker
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_InitializeTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_InitializeTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetTrackerVal
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SetTrackerVal>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SetTrackerVal>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AddTrackerVals
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_AddTrackerVals>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_AddTrackerVals>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator StartSession
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_StartSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_StartSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator StopSession
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_StopSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_StopSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SendGaHitWithMeasurementProtocol
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SendGaHitWithMeasurementProtocol>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SendGaHitWithMeasurementProtocol>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator HandleWWW
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_HandleWWW>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_HandleWWW>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AddRequiredMPParameter_Field_object
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_AddRequiredMPParameter_Field_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_AddRequiredMPParameter_Field_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AddRequiredMPParameter_Field_string
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_AddRequiredMPParameter_Field_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_AddRequiredMPParameter_Field_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AddOptionalMPParameter_Field_object
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_AddOptionalMPParameter_Field_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_AddOptionalMPParameter_Field_object>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AddOptionalMPParameter_Field_string
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_AddOptionalMPParameter_Field_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_AddOptionalMPParameter_Field_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogScreen
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_LogScreen>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_LogScreen>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogEvent
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_LogEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_LogEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogTransaction
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_LogTransaction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_LogTransaction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogItem
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_LogItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_LogItem>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogException
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_LogException>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_LogException>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogSocial
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_LogSocial>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_LogSocial>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogTiming
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_LogTiming>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_LogTiming>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ClearUserIDOverride
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_ClearUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_ClearUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetTrackingCode
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SetTrackingCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SetTrackingCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetBundleIdentifier
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SetBundleIdentifier>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SetBundleIdentifier>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetAppName
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SetAppName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetAppVersion
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SetAppVersion>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SetAppVersion>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetLogLevelValue
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SetLogLevelValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SetLogLevelValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetAnonymizeIP
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SetAnonymizeIP>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SetAnonymizeIP>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetDryRun
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SetDryRun>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SetDryRun>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetOptOut
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_SetOptOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_SetOptOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsMPV3.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsMPV3.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class GoogleAnalyticsV4
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_HandleException(GoogleAnalyticsV4 self, string condition, string stackTrace, LogType type);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_HandleException(orig_HandleException orig, GoogleAnalyticsV4 self, string condition, string stackTrace, LogType type);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_InitializeTracker(GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_InitializeTracker(orig_InitializeTracker orig, GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetAppLevelOptOut(GoogleAnalyticsV4 self, bool optOut);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetAppLevelOptOut(orig_SetAppLevelOptOut orig, GoogleAnalyticsV4 self, bool optOut);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetUserIDOverride(GoogleAnalyticsV4 self, string userID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetUserIDOverride(orig_SetUserIDOverride orig, GoogleAnalyticsV4 self, string userID);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ClearUserIDOverride(GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ClearUserIDOverride(orig_ClearUserIDOverride orig, GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DispatchHits(GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DispatchHits(orig_DispatchHits orig, GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartSession(GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartSession(orig_StartSession orig, GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StopSession(GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StopSession(orig_StopSession orig, GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetOnTracker(GoogleAnalyticsV4 self, Field fieldName, object value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetOnTracker(orig_SetOnTracker orig, GoogleAnalyticsV4 self, Field fieldName, object value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogScreen_string(GoogleAnalyticsV4 self, string title);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogScreen_string(orig_LogScreen_string orig, GoogleAnalyticsV4 self, string title);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogScreen_AppViewHitBuilder(GoogleAnalyticsV4 self, AppViewHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogScreen_AppViewHitBuilder(orig_LogScreen_AppViewHitBuilder orig, GoogleAnalyticsV4 self, AppViewHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogEvent_string_string_string_long(GoogleAnalyticsV4 self, string eventCategory, string eventAction, string eventLabel, long value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogEvent_string_string_string_long(orig_LogEvent_string_string_string_long orig, GoogleAnalyticsV4 self, string eventCategory, string eventAction, string eventLabel, long value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogEvent_EventHitBuilder(GoogleAnalyticsV4 self, EventHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogEvent_EventHitBuilder(orig_LogEvent_EventHitBuilder orig, GoogleAnalyticsV4 self, EventHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogTransaction_string_string_double_double_double(GoogleAnalyticsV4 self, string transID, string affiliation, double revenue, double tax, double shipping);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogTransaction_string_string_double_double_double(orig_LogTransaction_string_string_double_double_double orig, GoogleAnalyticsV4 self, string transID, string affiliation, double revenue, double tax, double shipping);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogTransaction_string_string_double_double_double_string(GoogleAnalyticsV4 self, string transID, string affiliation, double revenue, double tax, double shipping, string currencyCode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogTransaction_string_string_double_double_double_string(orig_LogTransaction_string_string_double_double_double_string orig, GoogleAnalyticsV4 self, string transID, string affiliation, double revenue, double tax, double shipping, string currencyCode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogTransaction_TransactionHitBuilder(GoogleAnalyticsV4 self, TransactionHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogTransaction_TransactionHitBuilder(orig_LogTransaction_TransactionHitBuilder orig, GoogleAnalyticsV4 self, TransactionHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogItem_string_string_string_string_double_long(GoogleAnalyticsV4 self, string transID, string name, string sku, string category, double price, long quantity);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogItem_string_string_string_string_double_long(orig_LogItem_string_string_string_string_double_long orig, GoogleAnalyticsV4 self, string transID, string name, string sku, string category, double price, long quantity);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogItem_string_string_string_string_double_long_string(GoogleAnalyticsV4 self, string transID, string name, string sku, string category, double price, long quantity, string currencyCode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogItem_string_string_string_string_double_long_string(orig_LogItem_string_string_string_string_double_long_string orig, GoogleAnalyticsV4 self, string transID, string name, string sku, string category, double price, long quantity, string currencyCode);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogItem_ItemHitBuilder(GoogleAnalyticsV4 self, ItemHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogItem_ItemHitBuilder(orig_LogItem_ItemHitBuilder orig, GoogleAnalyticsV4 self, ItemHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogException_string_bool(GoogleAnalyticsV4 self, string exceptionDescription, bool isFatal);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogException_string_bool(orig_LogException_string_bool orig, GoogleAnalyticsV4 self, string exceptionDescription, bool isFatal);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogException_ExceptionHitBuilder(GoogleAnalyticsV4 self, ExceptionHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogException_ExceptionHitBuilder(orig_LogException_ExceptionHitBuilder orig, GoogleAnalyticsV4 self, ExceptionHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogSocial_string_string_string(GoogleAnalyticsV4 self, string socialNetwork, string socialAction, string socialTarget);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogSocial_string_string_string(orig_LogSocial_string_string_string orig, GoogleAnalyticsV4 self, string socialNetwork, string socialAction, string socialTarget);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogSocial_SocialHitBuilder(GoogleAnalyticsV4 self, SocialHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogSocial_SocialHitBuilder(orig_LogSocial_SocialHitBuilder orig, GoogleAnalyticsV4 self, SocialHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogTiming_string_long_string_string(GoogleAnalyticsV4 self, string timingCategory, long timingInterval, string timingName, string timingLabel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogTiming_string_long_string_string(orig_LogTiming_string_long_string_string orig, GoogleAnalyticsV4 self, string timingCategory, long timingInterval, string timingName, string timingLabel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LogTiming_TimingHitBuilder(GoogleAnalyticsV4 self, TimingHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LogTiming_TimingHitBuilder(orig_LogTiming_TimingHitBuilder orig, GoogleAnalyticsV4 self, TimingHitBuilder builder);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Dispose(GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Dispose(orig_Dispose orig, GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_belowThreshold(DebugMode userLogLevel, DebugMode comparelogLevel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_belowThreshold(orig_belowThreshold orig, DebugMode userLogLevel, DebugMode comparelogLevel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate GoogleAnalyticsV4 orig_getInstance();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate GoogleAnalyticsV4 hook_getInstance(orig_getInstance orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, GoogleAnalyticsV4 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_HandleException HandleException
		{
			add
			{
				HookEndpointManager.Add<hook_HandleException>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_HandleException>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_InitializeTracker InitializeTracker
		{
			add
			{
				HookEndpointManager.Add<hook_InitializeTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_InitializeTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetAppLevelOptOut SetAppLevelOptOut
		{
			add
			{
				HookEndpointManager.Add<hook_SetAppLevelOptOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetAppLevelOptOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetUserIDOverride SetUserIDOverride
		{
			add
			{
				HookEndpointManager.Add<hook_SetUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ClearUserIDOverride ClearUserIDOverride
		{
			add
			{
				HookEndpointManager.Add<hook_ClearUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ClearUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DispatchHits DispatchHits
		{
			add
			{
				HookEndpointManager.Add<hook_DispatchHits>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DispatchHits>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartSession StartSession
		{
			add
			{
				HookEndpointManager.Add<hook_StartSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StopSession StopSession
		{
			add
			{
				HookEndpointManager.Add<hook_StopSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StopSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetOnTracker SetOnTracker
		{
			add
			{
				HookEndpointManager.Add<hook_SetOnTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetOnTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogScreen_string LogScreen_string
		{
			add
			{
				HookEndpointManager.Add<hook_LogScreen_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogScreen_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogScreen_AppViewHitBuilder LogScreen_AppViewHitBuilder
		{
			add
			{
				HookEndpointManager.Add<hook_LogScreen_AppViewHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogScreen_AppViewHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogEvent_string_string_string_long LogEvent_string_string_string_long
		{
			add
			{
				HookEndpointManager.Add<hook_LogEvent_string_string_string_long>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogEvent_string_string_string_long>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogEvent_EventHitBuilder LogEvent_EventHitBuilder
		{
			add
			{
				HookEndpointManager.Add<hook_LogEvent_EventHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogEvent_EventHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogTransaction_string_string_double_double_double LogTransaction_string_string_double_double_double
		{
			add
			{
				HookEndpointManager.Add<hook_LogTransaction_string_string_double_double_double>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogTransaction_string_string_double_double_double>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogTransaction_string_string_double_double_double_string LogTransaction_string_string_double_double_double_string
		{
			add
			{
				HookEndpointManager.Add<hook_LogTransaction_string_string_double_double_double_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogTransaction_string_string_double_double_double_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogTransaction_TransactionHitBuilder LogTransaction_TransactionHitBuilder
		{
			add
			{
				HookEndpointManager.Add<hook_LogTransaction_TransactionHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogTransaction_TransactionHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogItem_string_string_string_string_double_long LogItem_string_string_string_string_double_long
		{
			add
			{
				HookEndpointManager.Add<hook_LogItem_string_string_string_string_double_long>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogItem_string_string_string_string_double_long>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogItem_string_string_string_string_double_long_string LogItem_string_string_string_string_double_long_string
		{
			add
			{
				HookEndpointManager.Add<hook_LogItem_string_string_string_string_double_long_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogItem_string_string_string_string_double_long_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogItem_ItemHitBuilder LogItem_ItemHitBuilder
		{
			add
			{
				HookEndpointManager.Add<hook_LogItem_ItemHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogItem_ItemHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogException_string_bool LogException_string_bool
		{
			add
			{
				HookEndpointManager.Add<hook_LogException_string_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogException_string_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogException_ExceptionHitBuilder LogException_ExceptionHitBuilder
		{
			add
			{
				HookEndpointManager.Add<hook_LogException_ExceptionHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogException_ExceptionHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogSocial_string_string_string LogSocial_string_string_string
		{
			add
			{
				HookEndpointManager.Add<hook_LogSocial_string_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogSocial_string_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogSocial_SocialHitBuilder LogSocial_SocialHitBuilder
		{
			add
			{
				HookEndpointManager.Add<hook_LogSocial_SocialHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogSocial_SocialHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogTiming_string_long_string_string LogTiming_string_long_string_string
		{
			add
			{
				HookEndpointManager.Add<hook_LogTiming_string_long_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogTiming_string_long_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LogTiming_TimingHitBuilder LogTiming_TimingHitBuilder
		{
			add
			{
				HookEndpointManager.Add<hook_LogTiming_TimingHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LogTiming_TimingHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Dispose Dispose
		{
			add
			{
				HookEndpointManager.Add<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_belowThreshold belowThreshold
		{
			add
			{
				HookEndpointManager.Add<hook_belowThreshold>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_belowThreshold>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_getInstance getInstance
		{
			add
			{
				HookEndpointManager.Add<hook_getInstance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_getInstance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class GoogleAnalyticsV4
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator HandleException
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_HandleException>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_HandleException>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator InitializeTracker
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_InitializeTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_InitializeTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetAppLevelOptOut
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_SetAppLevelOptOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_SetAppLevelOptOut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetUserIDOverride
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_SetUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_SetUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ClearUserIDOverride
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_ClearUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_ClearUserIDOverride>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator DispatchHits
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_DispatchHits>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_DispatchHits>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator StartSession
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_StartSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_StartSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator StopSession
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_StopSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_StopSession>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetOnTracker
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_SetOnTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_SetOnTracker>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogScreen_string
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogScreen_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogScreen_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogScreen_AppViewHitBuilder
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogScreen_AppViewHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogScreen_AppViewHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogEvent_string_string_string_long
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogEvent_string_string_string_long>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogEvent_string_string_string_long>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogEvent_EventHitBuilder
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogEvent_EventHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogEvent_EventHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogTransaction_string_string_double_double_double
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogTransaction_string_string_double_double_double>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogTransaction_string_string_double_double_double>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogTransaction_string_string_double_double_double_string
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogTransaction_string_string_double_double_double_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogTransaction_string_string_double_double_double_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogTransaction_TransactionHitBuilder
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogTransaction_TransactionHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogTransaction_TransactionHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogItem_string_string_string_string_double_long
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogItem_string_string_string_string_double_long>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogItem_string_string_string_string_double_long>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogItem_string_string_string_string_double_long_string
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogItem_string_string_string_string_double_long_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogItem_string_string_string_string_double_long_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogItem_ItemHitBuilder
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogItem_ItemHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogItem_ItemHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogException_string_bool
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogException_string_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogException_string_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogException_ExceptionHitBuilder
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogException_ExceptionHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogException_ExceptionHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogSocial_string_string_string
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogSocial_string_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogSocial_string_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogSocial_SocialHitBuilder
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogSocial_SocialHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogSocial_SocialHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogTiming_string_long_string_string
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogTiming_string_long_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogTiming_string_long_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LogTiming_TimingHitBuilder
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_LogTiming_TimingHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_LogTiming_TimingHitBuilder>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Dispose
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator belowThreshold
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_belowThreshold>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_belowThreshold>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator getInstance
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_getInstance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_getInstance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsV4.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsV4.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class GoogleAnalyticsiOSV3
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(GoogleAnalyticsiOSV3 self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, GoogleAnalyticsiOSV3 self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class GoogleAnalyticsiOSV3
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.GoogleAnalyticsiOSV3.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GoogleAnalyticsiOSV3.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class AppViewHitBuilder
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetScreenName(AppViewHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetScreenName(orig_GetScreenName orig, AppViewHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate AppViewHitBuilder orig_SetScreenName(AppViewHitBuilder self, string screenName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate AppViewHitBuilder hook_SetScreenName(orig_SetScreenName orig, AppViewHitBuilder self, string screenName);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate AppViewHitBuilder orig_GetThis(AppViewHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate AppViewHitBuilder hook_GetThis(orig_GetThis orig, AppViewHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate AppViewHitBuilder orig_Validate(AppViewHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate AppViewHitBuilder hook_Validate(orig_Validate orig, AppViewHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AppViewHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AppViewHitBuilder self);

		public static event hook_GetScreenName GetScreenName
		{
			add
			{
				HookEndpointManager.Add<hook_GetScreenName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetScreenName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetScreenName SetScreenName
		{
			add
			{
				HookEndpointManager.Add<hook_SetScreenName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetScreenName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetThis GetThis
		{
			add
			{
				HookEndpointManager.Add<hook_GetThis>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetThis>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Validate Validate
		{
			add
			{
				HookEndpointManager.Add<hook_Validate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Validate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AppViewHitBuilder
	{
		public static event Manipulator GetScreenName
		{
			add
			{
				HookEndpointManager.Modify<On.AppViewHitBuilder.hook_GetScreenName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AppViewHitBuilder.hook_GetScreenName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetScreenName
		{
			add
			{
				HookEndpointManager.Modify<On.AppViewHitBuilder.hook_SetScreenName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AppViewHitBuilder.hook_SetScreenName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetThis
		{
			add
			{
				HookEndpointManager.Modify<On.AppViewHitBuilder.hook_GetThis>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AppViewHitBuilder.hook_GetThis>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Validate
		{
			add
			{
				HookEndpointManager.Modify<On.AppViewHitBuilder.hook_Validate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AppViewHitBuilder.hook_Validate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AppViewHitBuilder.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AppViewHitBuilder.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class EventHitBuilder
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetEventCategory(EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetEventCategory(orig_GetEventCategory orig, EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder orig_SetEventCategory(EventHitBuilder self, string eventCategory);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder hook_SetEventCategory(orig_SetEventCategory orig, EventHitBuilder self, string eventCategory);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetEventAction(EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetEventAction(orig_GetEventAction orig, EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder orig_SetEventAction(EventHitBuilder self, string eventAction);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder hook_SetEventAction(orig_SetEventAction orig, EventHitBuilder self, string eventAction);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetEventLabel(EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetEventLabel(orig_GetEventLabel orig, EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder orig_SetEventLabel(EventHitBuilder self, string eventLabel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder hook_SetEventLabel(orig_SetEventLabel orig, EventHitBuilder self, string eventLabel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate long orig_GetEventValue(EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate long hook_GetEventValue(orig_GetEventValue orig, EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder orig_SetEventValue(EventHitBuilder self, long eventValue);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder hook_SetEventValue(orig_SetEventValue orig, EventHitBuilder self, long eventValue);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder orig_GetThis(EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder hook_GetThis(orig_GetThis orig, EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder orig_Validate(EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate EventHitBuilder hook_Validate(orig_Validate orig, EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(EventHitBuilder self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, EventHitBuilder self);

		public static event hook_GetEventCategory GetEventCategory
		{
			add
			{
				HookEndpointManager.Add<hook_GetEventCategory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetEventCategory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetEventCategory SetEventCategory
		{
			add
			{
				HookEndpointManager.Add<hook_SetEventCategory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetEventCategory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetEventAction GetEventAction
		{
			add
			{
				HookEndpointManager.Add<hook_GetEventAction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetEventAction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetEventAction SetEventAction
		{
			add
			{
				HookEndpointManager.Add<hook_SetEventAction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetEventAction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetEventLabel GetEventLabel
		{
			add
			{
				HookEndpointManager.Add<hook_GetEventLabel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetEventLabel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetEventLabel SetEventLabel
		{
			add
			{
				HookEndpointManager.Add<hook_SetEventLabel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetEventLabel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetEventValue GetEventValue
		{
			add
			{
				HookEndpointManager.Add<hook_GetEventValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetEventValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetEventValue SetEventValue
		{
			add
			{
				HookEndpointManager.Add<hook_SetEventValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetEventValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			

BepInEx/plugins/MMHOOK/MMHOOK_assembly_guiutils.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Fishlabs.UiTools;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On;
using On.Fishlabs.UiTools;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class AlphaMotion
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(AlphaMotion self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, AlphaMotion self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(AlphaMotion self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, AlphaMotion self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AlphaMotion self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AlphaMotion self);

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AlphaMotion
	{
		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.AlphaMotion.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AlphaMotion.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.AlphaMotion.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AlphaMotion.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AlphaMotion.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AlphaMotion.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class ButtonImageColor
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(ButtonImageColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, ButtonImageColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(ButtonImageColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, ButtonImageColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ButtonImageColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ButtonImageColor self);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class ButtonImageColor
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonImageColor.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonImageColor.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonImageColor.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonImageColor.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonImageColor.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonImageColor.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class ButtonSfx
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(ButtonSfx self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, ButtonSfx self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnClick(ButtonSfx self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnClick(orig_OnClick orig, ButtonSfx self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnChange(ButtonSfx self, bool v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnChange(orig_OnChange orig, ButtonSfx self, bool v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnSelect(ButtonSfx self, BaseEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnSelect(orig_OnSelect orig, ButtonSfx self, BaseEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ButtonSfx self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ButtonSfx self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnClick OnClick
		{
			add
			{
				HookEndpointManager.Add<hook_OnClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnChange OnChange
		{
			add
			{
				HookEndpointManager.Add<hook_OnChange>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnChange>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnSelect OnSelect
		{
			add
			{
				HookEndpointManager.Add<hook_OnSelect>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnSelect>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class ButtonSfx
	{
		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonSfx.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonSfx.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnClick
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonSfx.hook_OnClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonSfx.hook_OnClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnChange
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonSfx.hook_OnChange>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonSfx.hook_OnChange>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnSelect
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonSfx.hook_OnSelect>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonSfx.hook_OnSelect>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonSfx.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonSfx.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonSfx.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonSfx.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class ButtonTextColor
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(ButtonTextColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, ButtonTextColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(ButtonTextColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, ButtonTextColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ButtonTextColor self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ButtonTextColor self);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class ButtonTextColor
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonTextColor.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonTextColor.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonTextColor.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonTextColor.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.ButtonTextColor.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ButtonTextColor.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class GuiBar
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetWidth(GuiBar self, float width);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetWidth(orig_SetWidth orig, GuiBar self, float width);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetValue(GuiBar self, float value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetValue(orig_SetValue orig, GuiBar self, float value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetSmoothValue(GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetSmoothValue(orig_GetSmoothValue orig, GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetMaxValue(GuiBar self, float value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetMaxValue(orig_SetMaxValue orig, GuiBar self, float value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LateUpdate(GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LateUpdate(orig_LateUpdate orig, GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetBar(GuiBar self, float i);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetBar(orig_SetBar orig, GuiBar self, float i);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetColor(GuiBar self, Color color);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetColor(orig_SetColor orig, GuiBar self, Color color);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Color orig_GetColor(GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Color hook_GetColor(orig_GetColor orig, GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ResetColor(GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ResetColor(orig_ResetColor orig, GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(GuiBar self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, GuiBar self);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetWidth SetWidth
		{
			add
			{
				HookEndpointManager.Add<hook_SetWidth>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetWidth>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetValue SetValue
		{
			add
			{
				HookEndpointManager.Add<hook_SetValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetSmoothValue GetSmoothValue
		{
			add
			{
				HookEndpointManager.Add<hook_GetSmoothValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetSmoothValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetMaxValue SetMaxValue
		{
			add
			{
				HookEndpointManager.Add<hook_SetMaxValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetMaxValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LateUpdate LateUpdate
		{
			add
			{
				HookEndpointManager.Add<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetBar SetBar
		{
			add
			{
				HookEndpointManager.Add<hook_SetBar>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetBar>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetColor SetColor
		{
			add
			{
				HookEndpointManager.Add<hook_SetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetColor GetColor
		{
			add
			{
				HookEndpointManager.Add<hook_GetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ResetColor ResetColor
		{
			add
			{
				HookEndpointManager.Add<hook_ResetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ResetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class GuiBar
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetWidth
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_SetWidth>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_SetWidth>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetValue
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_SetValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_SetValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetSmoothValue
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_GetSmoothValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_GetSmoothValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetMaxValue
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_SetMaxValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_SetMaxValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LateUpdate
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetBar
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_SetBar>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_SetBar>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetColor
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_SetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_SetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetColor
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_GetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_GetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ResetColor
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_ResetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_ResetColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.GuiBar.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiBar.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class GuiPixelFix
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LateUpdate(GuiPixelFix self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LateUpdate(orig_LateUpdate orig, GuiPixelFix self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(GuiPixelFix self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, GuiPixelFix self);

		public static event hook_LateUpdate LateUpdate
		{
			add
			{
				HookEndpointManager.Add<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class GuiPixelFix
	{
		public static event Manipulator LateUpdate
		{
			add
			{
				HookEndpointManager.Modify<On.GuiPixelFix.hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiPixelFix.hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.GuiPixelFix.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiPixelFix.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class GuiScaler
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDestroy(GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDestroy(orig_OnDestroy orig, GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateScale(GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateScale(orig_UpdateScale orig, GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetScreenSizeFactor(GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetScreenSizeFactor(orig_GetScreenSizeFactor orig, GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LoadGuiScale();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LoadGuiScale(orig_LoadGuiScale orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetScale(float scale);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetScale(orig_SetScale orig, float scale);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, GuiScaler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDestroy OnDestroy
		{
			add
			{
				HookEndpointManager.Add<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateScale UpdateScale
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetScreenSizeFactor GetScreenSizeFactor
		{
			add
			{
				HookEndpointManager.Add<hook_GetScreenSizeFactor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetScreenSizeFactor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LoadGuiScale LoadGuiScale
		{
			add
			{
				HookEndpointManager.Add<hook_LoadGuiScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LoadGuiScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetScale SetScale
		{
			add
			{
				HookEndpointManager.Add<hook_SetScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class GuiScaler
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.GuiScaler.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiScaler.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDestroy
		{
			add
			{
				HookEndpointManager.Modify<On.GuiScaler.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiScaler.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.GuiScaler.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiScaler.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateScale
		{
			add
			{
				HookEndpointManager.Modify<On.GuiScaler.hook_UpdateScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiScaler.hook_UpdateScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetScreenSizeFactor
		{
			add
			{
				HookEndpointManager.Modify<On.GuiScaler.hook_GetScreenSizeFactor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiScaler.hook_GetScreenSizeFactor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LoadGuiScale
		{
			add
			{
				HookEndpointManager.Modify<On.GuiScaler.hook_LoadGuiScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiScaler.hook_LoadGuiScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetScale
		{
			add
			{
				HookEndpointManager.Modify<On.GuiScaler.hook_SetScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiScaler.hook_SetScale>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.GuiScaler.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiScaler.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.GuiScaler.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.GuiScaler.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class Localization
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Initialize();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Initialize(orig_Initialize orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Localization self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Localization self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetLanguage(Localization self, string language);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetLanguage(orig_SetLanguage orig, Localization self, string language);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetSelectedLanguage(Localization self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetSelectedLanguage(orig_GetSelectedLanguage orig, Localization self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetNextLanguage(Localization self, string lang);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetNextLanguage(orig_GetNextLanguage orig, Localization self, string lang);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetPrevLanguage(Localization self, string lang);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetPrevLanguage(orig_GetPrevLanguage orig, Localization self, string lang);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Localize_Transform(Localization self, Transform root);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Localize_Transform(orig_Localize_Transform orig, Localization self, Transform root);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RemoveTextFromCache_Text(Localization self, Text text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RemoveTextFromCache_Text(orig_RemoveTextFromCache_Text orig, Localization self, Text text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RemoveTextFromCache_TextMeshProUGUI(Localization self, TextMeshProUGUI text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RemoveTextFromCache_TextMeshProUGUI(orig_RemoveTextFromCache_TextMeshProUGUI orig, Localization self, TextMeshProUGUI text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ReLocalizeVisible(Localization self, Transform root);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ReLocalizeVisible(orig_ReLocalizeVisible orig, Localization self, Transform root);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ReLocalizeAll(Localization self, Transform root);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ReLocalizeAll(orig_ReLocalizeAll orig, Localization self, Transform root);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_Localize_string_StringArray(Localization self, string text, string[] words);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_Localize_string_StringArray(orig_Localize_string_StringArray orig, Localization self, string text, string[] words);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_InsertWords(Localization self, string text, string[] words);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_InsertWords(orig_InsertWords orig, Localization self, string text, string[] words);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_Localize_string(Localization self, string text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_Localize_string(orig_Localize_string orig, Localization self, string text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_FindNextWord(Localization self, string text, int startIndex, out string word, out int wordStart, out int wordEnd);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_FindNextWord(orig_FindNextWord orig, Localization self, string text, int startIndex, out string word, out int wordStart, out int wordEnd);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_Translate(Localization self, string word);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_Translate(orig_Translate orig, Localization self, string word);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetBoundKeyString(Localization self, string bindingName, bool emptyStringOnMissing);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetBoundKeyString(orig_GetBoundKeyString orig, Localization self, string bindingName, bool emptyStringOnMissing);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddWord(Localization self, string key, string text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddWord(orig_AddWord orig, Localization self, string key, string text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Clear(Localization self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Clear(orig_Clear orig, Localization self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_StripCitations(Localization self, string s);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_StripCitations(orig_StripCitations orig, Localization self, string s);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_SetupLanguage(Localization self, string language);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_SetupLanguage(orig_SetupLanguage orig, Localization self, string language);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_LoadCSV(Localization self, TextAsset file, string language);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_LoadCSV(orig_LoadCSV orig, Localization self, TextAsset file, string language);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<List<string>> orig_DoQuoteLineSplit(Localization self, StringReader reader);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<List<string>> hook_DoQuoteLineSplit(orig_DoQuoteLineSplit orig, Localization self, StringReader reader);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_TranslateSingleId(Localization self, string locaId, string language);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_TranslateSingleId(orig_TranslateSingleId orig, Localization self, string locaId, string language);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<string> orig_GetLanguages(Localization self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<string> hook_GetLanguages(orig_GetLanguages orig, Localization self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<string> orig_LoadLanguages(Localization self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<string> hook_LoadLanguages(orig_LoadLanguages orig, Localization self);

		public static event hook_Initialize Initialize
		{
			add
			{
				HookEndpointManager.Add<hook_Initialize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Initialize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetLanguage SetLanguage
		{
			add
			{
				HookEndpointManager.Add<hook_SetLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetSelectedLanguage GetSelectedLanguage
		{
			add
			{
				HookEndpointManager.Add<hook_GetSelectedLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetSelectedLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetNextLanguage GetNextLanguage
		{
			add
			{
				HookEndpointManager.Add<hook_GetNextLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetNextLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetPrevLanguage GetPrevLanguage
		{
			add
			{
				HookEndpointManager.Add<hook_GetPrevLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetPrevLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Localize_Transform Localize_Transform
		{
			add
			{
				HookEndpointManager.Add<hook_Localize_Transform>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Localize_Transform>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RemoveTextFromCache_Text RemoveTextFromCache_Text
		{
			add
			{
				HookEndpointManager.Add<hook_RemoveTextFromCache_Text>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RemoveTextFromCache_Text>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RemoveTextFromCache_TextMeshProUGUI RemoveTextFromCache_TextMeshProUGUI
		{
			add
			{
				HookEndpointManager.Add<hook_RemoveTextFromCache_TextMeshProUGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RemoveTextFromCache_TextMeshProUGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ReLocalizeVisible ReLocalizeVisible
		{
			add
			{
				HookEndpointManager.Add<hook_ReLocalizeVisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ReLocalizeVisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ReLocalizeAll ReLocalizeAll
		{
			add
			{
				HookEndpointManager.Add<hook_ReLocalizeAll>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ReLocalizeAll>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Localize_string_StringArray Localize_string_StringArray
		{
			add
			{
				HookEndpointManager.Add<hook_Localize_string_StringArray>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Localize_string_StringArray>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_InsertWords InsertWords
		{
			add
			{
				HookEndpointManager.Add<hook_InsertWords>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_InsertWords>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Localize_string Localize_string
		{
			add
			{
				HookEndpointManager.Add<hook_Localize_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Localize_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FindNextWord FindNextWord
		{
			add
			{
				HookEndpointManager.Add<hook_FindNextWord>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FindNextWord>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Translate Translate
		{
			add
			{
				HookEndpointManager.Add<hook_Translate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Translate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetBoundKeyString GetBoundKeyString
		{
			add
			{
				HookEndpointManager.Add<hook_GetBoundKeyString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetBoundKeyString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddWord AddWord
		{
			add
			{
				HookEndpointManager.Add<hook_AddWord>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddWord>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Clear Clear
		{
			add
			{
				HookEndpointManager.Add<hook_Clear>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Clear>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StripCitations StripCitations
		{
			add
			{
				HookEndpointManager.Add<hook_StripCitations>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StripCitations>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetupLanguage SetupLanguage
		{
			add
			{
				HookEndpointManager.Add<hook_SetupLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetupLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LoadCSV LoadCSV
		{
			add
			{
				HookEndpointManager.Add<hook_LoadCSV>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LoadCSV>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DoQuoteLineSplit DoQuoteLineSplit
		{
			add
			{
				HookEndpointManager.Add<hook_DoQuoteLineSplit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DoQuoteLineSplit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_TranslateSingleId TranslateSingleId
		{
			add
			{
				HookEndpointManager.Add<hook_TranslateSingleId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_TranslateSingleId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetLanguages GetLanguages
		{
			add
			{
				HookEndpointManager.Add<hook_GetLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LoadLanguages LoadLanguages
		{
			add
			{
				HookEndpointManager.Add<hook_LoadLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LoadLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class Localization
	{
		public static event Manipulator Initialize
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_Initialize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_Initialize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetLanguage
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_SetLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_SetLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetSelectedLanguage
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_GetSelectedLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_GetSelectedLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetNextLanguage
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_GetNextLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_GetNextLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetPrevLanguage
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_GetPrevLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_GetPrevLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Localize_Transform
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_Localize_Transform>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_Localize_Transform>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator RemoveTextFromCache_Text
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_RemoveTextFromCache_Text>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_RemoveTextFromCache_Text>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator RemoveTextFromCache_TextMeshProUGUI
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_RemoveTextFromCache_TextMeshProUGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_RemoveTextFromCache_TextMeshProUGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ReLocalizeVisible
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_ReLocalizeVisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_ReLocalizeVisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ReLocalizeAll
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_ReLocalizeAll>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_ReLocalizeAll>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Localize_string_StringArray
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_Localize_string_StringArray>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_Localize_string_StringArray>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator InsertWords
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_InsertWords>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_InsertWords>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Localize_string
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_Localize_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_Localize_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator FindNextWord
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_FindNextWord>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_FindNextWord>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Translate
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_Translate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_Translate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetBoundKeyString
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_GetBoundKeyString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_GetBoundKeyString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AddWord
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_AddWord>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_AddWord>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Clear
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_Clear>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_Clear>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator StripCitations
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_StripCitations>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_StripCitations>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetupLanguage
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_SetupLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_SetupLanguage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LoadCSV
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_LoadCSV>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_LoadCSV>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator DoQuoteLineSplit
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_DoQuoteLineSplit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_DoQuoteLineSplit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator TranslateSingleId
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_TranslateSingleId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_TranslateSingleId>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetLanguages
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_GetLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_GetLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LoadLanguages
		{
			add
			{
				HookEndpointManager.Modify<On.Localization.hook_LoadLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localization.hook_LoadLanguages>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class LocalizationSettings
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(LocalizationSettings self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, LocalizationSettings self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class LocalizationSettings
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.LocalizationSettings.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LocalizationSettings.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class Localize
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(Localize self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, Localize self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDestroy(Localize self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDestroy(orig_OnDestroy orig, Localize self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RelocalizeAllUponChange(Localize self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RelocalizeAllUponChange(orig_RelocalizeAllUponChange orig, Localize self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RefreshLocalization(Localize self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RefreshLocalization(orig_RefreshLocalization orig, Localize self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Localize self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Localize self);

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDestroy OnDestroy
		{
			add
			{
				HookEndpointManager.Add<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RelocalizeAllUponChange RelocalizeAllUponChange
		{
			add
			{
				HookEndpointManager.Add<hook_RelocalizeAllUponChange>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RelocalizeAllUponChange>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RefreshLocalization RefreshLocalization
		{
			add
			{
				HookEndpointManager.Add<hook_RefreshLocalization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RefreshLocalization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class Localize
	{
		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.Localize.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localize.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDestroy
		{
			add
			{
				HookEndpointManager.Modify<On.Localize.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localize.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator RelocalizeAllUponChange
		{
			add
			{
				HookEndpointManager.Modify<On.Localize.hook_RelocalizeAllUponChange>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localize.hook_RelocalizeAllUponChange>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator RefreshLocalization
		{
			add
			{
				HookEndpointManager.Modify<On.Localize.hook_RefreshLocalization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localize.hook_RefreshLocalization>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Localize.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Localize.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class MouseClick
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnPointerClick(MouseClick self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnPointerClick(orig_OnPointerClick orig, MouseClick self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(MouseClick self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, MouseClick self);

		public static event hook_OnPointerClick OnPointerClick
		{
			add
			{
				HookEndpointManager.Add<hook_OnPointerClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnPointerClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class MouseClick
	{
		public static event Manipulator OnPointerClick
		{
			add
			{
				HookEndpointManager.Modify<On.MouseClick.hook_OnPointerClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.MouseClick.hook_OnPointerClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.MouseClick.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.MouseClick.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class UIGroupHandler
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDestroy(UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDestroy(orig_OnDestroy orig, UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Selectable orig_FindSelectable(UIGroupHandler self, GameObject root);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Selectable hook_FindSelectable(orig_FindSelectable orig, UIGroupHandler self, GameObject root);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsHighestPriority(UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsHighestPriority(orig_IsHighestPriority orig, UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ResetActiveElement(UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ResetActiveElement(orig_ResetActiveElement orig, UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_HaveSelectedObject(UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_HaveSelectedObject(orig_HaveSelectedObject orig, UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetActive(UIGroupHandler self, bool active);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetActive(orig_SetActive orig, UIGroupHandler self, bool active);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, UIGroupHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDestroy OnDestroy
		{
			add
			{
				HookEndpointManager.Add<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FindSelectable FindSelectable
		{
			add
			{
				HookEndpointManager.Add<hook_FindSelectable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FindSelectable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_IsHighestPriority IsHighestPriority
		{
			add
			{
				HookEndpointManager.Add<hook_IsHighestPriority>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_IsHighestPriority>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ResetActiveElement ResetActiveElement
		{
			add
			{
				HookEndpointManager.Add<hook_ResetActiveElement>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ResetActiveElement>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_HaveSelectedObject HaveSelectedObject
		{
			add
			{
				HookEndpointManager.Add<hook_HaveSelectedObject>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_HaveSelectedObject>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetActive SetActive
		{
			add
			{
				HookEndpointManager.Add<hook_SetActive>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetActive>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class UIGroupHandler
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDestroy
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator FindSelectable
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_FindSelectable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_FindSelectable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator IsHighestPriority
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_IsHighestPriority>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_IsHighestPriority>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ResetActiveElement
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_ResetActiveElement>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_ResetActiveElement>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator HaveSelectedObject
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_HaveSelectedObject>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_HaveSelectedObject>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetActive
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_SetActive>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_SetActive>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.UIGroupHandler.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIGroupHandler.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class UIInputHandler
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnPointerDown(UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnPointerDown(orig_OnPointerDown orig, UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnPointerUp(UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnPointerUp(orig_OnPointerUp orig, UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnPointerClick(UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnPointerClick(orig_OnPointerClick orig, UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnPointerEnter(UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnPointerEnter(orig_OnPointerEnter orig, UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnPointerExit(UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnPointerExit(orig_OnPointerExit orig, UIInputHandler self, PointerEventData eventData);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(UIInputHandler self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, UIInputHandler self);

		public static event hook_OnPointerDown OnPointerDown
		{
			add
			{
				HookEndpointManager.Add<hook_OnPointerDown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnPointerDown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnPointerUp OnPointerUp
		{
			add
			{
				HookEndpointManager.Add<hook_OnPointerUp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnPointerUp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnPointerClick OnPointerClick
		{
			add
			{
				HookEndpointManager.Add<hook_OnPointerClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnPointerClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnPointerEnter OnPointerEnter
		{
			add
			{
				HookEndpointManager.Add<hook_OnPointerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnPointerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnPointerExit OnPointerExit
		{
			add
			{
				HookEndpointManager.Add<hook_OnPointerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnPointerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class UIInputHandler
	{
		public static event Manipulator OnPointerDown
		{
			add
			{
				HookEndpointManager.Modify<On.UIInputHandler.hook_OnPointerDown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIInputHandler.hook_OnPointerDown>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnPointerUp
		{
			add
			{
				HookEndpointManager.Modify<On.UIInputHandler.hook_OnPointerUp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIInputHandler.hook_OnPointerUp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnPointerClick
		{
			add
			{
				HookEndpointManager.Modify<On.UIInputHandler.hook_OnPointerClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIInputHandler.hook_OnPointerClick>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnPointerEnter
		{
			add
			{
				HookEndpointManager.Modify<On.UIInputHandler.hook_OnPointerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UIInputHandler.hook_OnPointerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnPointerExit
		

BepInEx/plugins/MMHOOK/MMHOOK_assembly_lux.dll

Decompiled 8 months ago
using System;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using LuxParticles;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On.LuxParticles;
using UnityEngine.Rendering;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On.LuxParticles
{
	public static class LuxParticles_AmbientLighting
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LateUpdate(LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LateUpdate(orig_LateUpdate orig, LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateAmbientLighting(LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateAmbientLighting(orig_UpdateAmbientLighting orig, LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateAmbientLightingForNewParticleSystems(LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateAmbientLightingForNewParticleSystems(orig_UpdateAmbientLightingForNewParticleSystems orig, LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SphericalHarmonicsL2 orig_PremultiplyCoefficients(SphericalHarmonicsL2 sh);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SphericalHarmonicsL2 hook_PremultiplyCoefficients(orig_PremultiplyCoefficients orig, SphericalHarmonicsL2 sh);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_GetShaderConstantsFromNormalizedSH(LuxParticles_AmbientLighting self, ref SphericalHarmonicsL2 ambientProbe, bool IsSkyLighting);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_GetShaderConstantsFromNormalizedSH(orig_GetShaderConstantsFromNormalizedSH orig, LuxParticles_AmbientLighting self, ref SphericalHarmonicsL2 ambientProbe, bool IsSkyLighting);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetSHLighting(LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetSHLighting(orig_SetSHLighting orig, LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, LuxParticles_AmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LateUpdate LateUpdate
		{
			add
			{
				HookEndpointManager.Add<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateAmbientLighting UpdateAmbientLighting
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateAmbientLighting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateAmbientLighting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateAmbientLightingForNewParticleSystems UpdateAmbientLightingForNewParticleSystems
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateAmbientLightingForNewParticleSystems>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateAmbientLightingForNewParticleSystems>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_PremultiplyCoefficients PremultiplyCoefficients
		{
			add
			{
				HookEndpointManager.Add<hook_PremultiplyCoefficients>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PremultiplyCoefficients>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetShaderConstantsFromNormalizedSH GetShaderConstantsFromNormalizedSH
		{
			add
			{
				HookEndpointManager.Add<hook_GetShaderConstantsFromNormalizedSH>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetShaderConstantsFromNormalizedSH>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetSHLighting SetSHLighting
		{
			add
			{
				HookEndpointManager.Add<hook_SetSHLighting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetSHLighting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.LuxParticles
{
	public static class LuxParticles_AmbientLighting
	{
		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_AmbientLighting.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_AmbientLighting.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LateUpdate
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_AmbientLighting.hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_AmbientLighting.hook_LateUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateAmbientLighting
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_AmbientLighting.hook_UpdateAmbientLighting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_AmbientLighting.hook_UpdateAmbientLighting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateAmbientLightingForNewParticleSystems
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_AmbientLighting.hook_UpdateAmbientLightingForNewParticleSystems>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_AmbientLighting.hook_UpdateAmbientLightingForNewParticleSystems>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator PremultiplyCoefficients
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_AmbientLighting.hook_PremultiplyCoefficients>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_AmbientLighting.hook_PremultiplyCoefficients>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetShaderConstantsFromNormalizedSH
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_AmbientLighting.hook_GetShaderConstantsFromNormalizedSH>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_AmbientLighting.hook_GetShaderConstantsFromNormalizedSH>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetSHLighting
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_AmbientLighting.hook_SetSHLighting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_AmbientLighting.hook_SetSHLighting>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_AmbientLighting.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_AmbientLighting.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_AmbientLighting.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_AmbientLighting.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.LuxParticles
{
	public static class LuxParticles_DirectionalLight
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(LuxParticles_DirectionalLight self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, LuxParticles_DirectionalLight self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(LuxParticles_DirectionalLight self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, LuxParticles_DirectionalLight self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDestroy(LuxParticles_DirectionalLight self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDestroy(orig_OnDestroy orig, LuxParticles_DirectionalLight self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(LuxParticles_DirectionalLight self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, LuxParticles_DirectionalLight self);

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDestroy OnDestroy
		{
			add
			{
				HookEndpointManager.Add<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.LuxParticles
{
	public static class LuxParticles_DirectionalLight
	{
		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_DirectionalLight.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_DirectionalLight.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_DirectionalLight.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_DirectionalLight.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDestroy
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_DirectionalLight.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_DirectionalLight.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_DirectionalLight.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_DirectionalLight.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.LuxParticles
{
	public static class LuxParticles_LocalAmbientLighting
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Register(LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Register(orig_Register orig, LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDestroy(LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDestroy(orig_OnDestroy orig, LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnBecameVisible(LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnBecameVisible(orig_OnBecameVisible orig, LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnBecameInvisible(LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnBecameInvisible(orig_OnBecameInvisible orig, LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, LuxParticles_LocalAmbientLighting self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Register Register
		{
			add
			{
				HookEndpointManager.Add<hook_Register>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Register>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDestroy OnDestroy
		{
			add
			{
				HookEndpointManager.Add<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnBecameVisible OnBecameVisible
		{
			add
			{
				HookEndpointManager.Add<hook_OnBecameVisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnBecameVisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnBecameInvisible OnBecameInvisible
		{
			add
			{
				HookEndpointManager.Add<hook_OnBecameInvisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnBecameInvisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.LuxParticles
{
	public static class LuxParticles_LocalAmbientLighting
	{
		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Register
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_Register>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_Register>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDestroy
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnBecameVisible
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnBecameVisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnBecameVisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnBecameInvisible
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnBecameInvisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_OnBecameInvisible>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LuxParticles.LuxParticles_LocalAmbientLighting.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace BepHookGen
{
	[StructLayout(LayoutKind.Auto, CharSet = CharSet.Auto)]
	internal class size9216
	{
	}
}

BepInEx/plugins/MMHOOK/MMHOOK_assembly_postprocessing.dll

Decompiled 8 months ago
using System;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On;
using On.UnityEngine.PostProcessing;
using UnityEngine;
using UnityEngine.PostProcessing;
using UnityEngine.Rendering;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class ExampleWheelController
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(ExampleWheelController self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, ExampleWheelController self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Update(ExampleWheelController self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Update(orig_Update orig, ExampleWheelController self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ExampleWheelController self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ExampleWheelController self);

		public static class Uniforms
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_cctor();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_cctor(orig_cctor orig);

			public static event hook_cctor cctor
			{
				add
				{
					HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Update Update
		{
			add
			{
				HookEndpointManager.Add<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class ExampleWheelController
	{
		public static class Uniforms
		{
			public static event Manipulator cctor
			{
				add
				{
					HookEndpointManager.Modify<On.ExampleWheelController.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.ExampleWheelController.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.ExampleWheelController.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ExampleWheelController.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Update
		{
			add
			{
				HookEndpointManager.Modify<On.ExampleWheelController.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ExampleWheelController.hook_Update>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.ExampleWheelController.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.ExampleWheelController.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class GetSetAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(GetSetAttribute self, string name);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, GetSetAttribute self, string name);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class GetSetAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.GetSetAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.GetSetAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class MinAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(MinAttribute self, float min);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, MinAttribute self, float min);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class MinAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.MinAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.MinAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class TrackballAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(TrackballAttribute self, string method);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, TrackballAttribute self, string method);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class TrackballAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.TrackballAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.TrackballAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class TrackballGroupAttribute
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(TrackballGroupAttribute self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, TrackballGroupAttribute self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class TrackballGroupAttribute
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.TrackballGroupAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.TrackballGroupAttribute.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class AmbientOcclusionComponent
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DepthTextureMode orig_GetCameraFlags(AmbientOcclusionComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DepthTextureMode hook_GetCameraFlags(orig_GetCameraFlags orig, AmbientOcclusionComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetName(AmbientOcclusionComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetName(orig_GetName orig, AmbientOcclusionComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate CameraEvent orig_GetCameraEvent(AmbientOcclusionComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate CameraEvent hook_GetCameraEvent(orig_GetCameraEvent orig, AmbientOcclusionComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_PopulateCommandBuffer(AmbientOcclusionComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_PopulateCommandBuffer(orig_PopulateCommandBuffer orig, AmbientOcclusionComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AmbientOcclusionComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AmbientOcclusionComponent self);

		public static class Uniforms
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_cctor();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_cctor(orig_cctor orig);

			public static event hook_cctor cctor
			{
				add
				{
					HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_GetCameraFlags GetCameraFlags
		{
			add
			{
				HookEndpointManager.Add<hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetName GetName
		{
			add
			{
				HookEndpointManager.Add<hook_GetName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCameraEvent GetCameraEvent
		{
			add
			{
				HookEndpointManager.Add<hook_GetCameraEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCameraEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_PopulateCommandBuffer PopulateCommandBuffer
		{
			add
			{
				HookEndpointManager.Add<hook_PopulateCommandBuffer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PopulateCommandBuffer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class AmbientOcclusionComponent
	{
		public static class Uniforms
		{
			public static event Manipulator cctor
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator GetCameraFlags
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetName
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_GetName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_GetName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetCameraEvent
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_GetCameraEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_GetCameraEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator PopulateCommandBuffer
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_PopulateCommandBuffer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_PopulateCommandBuffer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.AmbientOcclusionComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class BloomComponent
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Prepare(BloomComponent self, RenderTexture source, Material uberMaterial, Texture autoExposure);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Prepare(orig_Prepare orig, BloomComponent self, RenderTexture source, Material uberMaterial, Texture autoExposure);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(BloomComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, BloomComponent self);

		public static class Uniforms
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_cctor();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_cctor(orig_cctor orig);

			public static event hook_cctor cctor
			{
				add
				{
					HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_Prepare Prepare
		{
			add
			{
				HookEndpointManager.Add<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class BloomComponent
	{
		public static class Uniforms
		{
			public static event Manipulator cctor
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BloomComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BloomComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator Prepare
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BloomComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BloomComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BloomComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BloomComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class BuiltinDebugViewsComponent
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DepthTextureMode orig_GetCameraFlags(BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DepthTextureMode hook_GetCameraFlags(orig_GetCameraFlags orig, BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate CameraEvent orig_GetCameraEvent(BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate CameraEvent hook_GetCameraEvent(orig_GetCameraEvent orig, BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetName(BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetName(orig_GetName orig, BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_PopulateCommandBuffer(BuiltinDebugViewsComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_PopulateCommandBuffer(orig_PopulateCommandBuffer orig, BuiltinDebugViewsComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DepthPass(BuiltinDebugViewsComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DepthPass(orig_DepthPass orig, BuiltinDebugViewsComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DepthNormalsPass(BuiltinDebugViewsComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DepthNormalsPass(orig_DepthNormalsPass orig, BuiltinDebugViewsComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_MotionVectorsPass(BuiltinDebugViewsComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_MotionVectorsPass(orig_MotionVectorsPass orig, BuiltinDebugViewsComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_PrepareArrows(BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_PrepareArrows(orig_PrepareArrows orig, BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(BuiltinDebugViewsComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, BuiltinDebugViewsComponent self);

		public static class Uniforms
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_cctor();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_cctor(orig_cctor orig);

			public static event hook_cctor cctor
			{
				add
				{
					HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static class ArrowArray
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_BuildMesh(object self, int columns, int rows);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_BuildMesh(orig_BuildMesh orig, object self, int columns, int rows);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_Release(object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_Release(orig_Release orig, object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_ctor(object self);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_ctor(orig_ctor orig, object self);

			public static event hook_BuildMesh BuildMesh
			{
				add
				{
					HookEndpointManager.Add<hook_BuildMesh>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_BuildMesh>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_Release Release
			{
				add
				{
					HookEndpointManager.Add<hook_Release>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_Release>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}

			public static event hook_ctor ctor
			{
				add
				{
					HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_GetCameraFlags GetCameraFlags
		{
			add
			{
				HookEndpointManager.Add<hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCameraEvent GetCameraEvent
		{
			add
			{
				HookEndpointManager.Add<hook_GetCameraEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCameraEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetName GetName
		{
			add
			{
				HookEndpointManager.Add<hook_GetName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_PopulateCommandBuffer PopulateCommandBuffer
		{
			add
			{
				HookEndpointManager.Add<hook_PopulateCommandBuffer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PopulateCommandBuffer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DepthPass DepthPass
		{
			add
			{
				HookEndpointManager.Add<hook_DepthPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DepthPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DepthNormalsPass DepthNormalsPass
		{
			add
			{
				HookEndpointManager.Add<hook_DepthNormalsPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DepthNormalsPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_MotionVectorsPass MotionVectorsPass
		{
			add
			{
				HookEndpointManager.Add<hook_MotionVectorsPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_MotionVectorsPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_PrepareArrows PrepareArrows
		{
			add
			{
				HookEndpointManager.Add<hook_PrepareArrows>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_PrepareArrows>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class BuiltinDebugViewsComponent
	{
		public static class Uniforms
		{
			public static event Manipulator cctor
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static class ArrowArray
		{
			public static event Manipulator BuildMesh
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.ArrowArray.hook_BuildMesh>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.ArrowArray.hook_BuildMesh>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator Release
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.ArrowArray.hook_Release>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.ArrowArray.hook_Release>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}

			public static event Manipulator ctor
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.ArrowArray.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.ArrowArray.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator GetCameraFlags
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetCameraEvent
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_GetCameraEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_GetCameraEvent>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetName
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_GetName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_GetName>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator PopulateCommandBuffer
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_PopulateCommandBuffer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_PopulateCommandBuffer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator DepthPass
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_DepthPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_DepthPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator DepthNormalsPass
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_DepthNormalsPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_DepthNormalsPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator MotionVectorsPass
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_MotionVectorsPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_MotionVectorsPass>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator PrepareArrows
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_PrepareArrows>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_PrepareArrows>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.BuiltinDebugViewsComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class ChromaticAberrationComponent
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(ChromaticAberrationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, ChromaticAberrationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Prepare(ChromaticAberrationComponent self, Material uberMaterial);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Prepare(orig_Prepare orig, ChromaticAberrationComponent self, Material uberMaterial);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ChromaticAberrationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ChromaticAberrationComponent self);

		public static class Uniforms
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_cctor();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_cctor(orig_cctor orig);

			public static event hook_cctor cctor
			{
				add
				{
					HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Prepare Prepare
		{
			add
			{
				HookEndpointManager.Add<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class ChromaticAberrationComponent
	{
		public static class Uniforms
		{
			public static event Manipulator cctor
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ChromaticAberrationComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ChromaticAberrationComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ChromaticAberrationComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ChromaticAberrationComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Prepare
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ChromaticAberrationComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ChromaticAberrationComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ChromaticAberrationComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ChromaticAberrationComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class ColorGradingComponent
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_StandardIlluminantY(ColorGradingComponent self, float x);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_StandardIlluminantY(orig_StandardIlluminantY orig, ColorGradingComponent self, float x);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_CIExyToLMS(ColorGradingComponent self, float x, float y);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_CIExyToLMS(orig_CIExyToLMS orig, ColorGradingComponent self, float x, float y);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_CalculateColorBalance(ColorGradingComponent self, float temperature, float tint);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_CalculateColorBalance(orig_CalculateColorBalance orig, ColorGradingComponent self, float temperature, float tint);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Color orig_NormalizeColor(Color c);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Color hook_NormalizeColor(orig_NormalizeColor orig, Color c);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_ClampVector(Vector3 v, float min, float max);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_ClampVector(orig_ClampVector orig, Vector3 v, float min, float max);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetLiftValue(Color lift);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetLiftValue(orig_GetLiftValue orig, Color lift);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetGammaValue(Color gamma);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetGammaValue(orig_GetGammaValue orig, Color gamma);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetGainValue(Color gain);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetGainValue(orig_GetGainValue orig, Color gain);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CalculateLiftGammaGain(Color lift, Color gamma, Color gain, out Vector3 outLift, out Vector3 outGamma, out Vector3 outGain);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CalculateLiftGammaGain(orig_CalculateLiftGammaGain orig, Color lift, Color gamma, Color gain, out Vector3 outLift, out Vector3 outGamma, out Vector3 outGain);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetSlopeValue(Color slope);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetSlopeValue(orig_GetSlopeValue orig, Color slope);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetPowerValue(Color power);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetPowerValue(orig_GetPowerValue orig, Color power);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetOffsetValue(Color offset);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetOffsetValue(orig_GetOffsetValue orig, Color offset);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CalculateSlopePowerOffset(Color slope, Color power, Color offset, out Vector3 outSlope, out Vector3 outPower, out Vector3 outOffset);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CalculateSlopePowerOffset(orig_CalculateSlopePowerOffset orig, Color slope, Color power, Color offset, out Vector3 outSlope, out Vector3 outPower, out Vector3 outOffset);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate TextureFormat orig_GetCurveFormat(ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate TextureFormat hook_GetCurveFormat(orig_GetCurveFormat orig, ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D orig_GetCurveTexture(ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture2D hook_GetCurveTexture(orig_GetCurveTexture orig, ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsLogLutValid(ColorGradingComponent self, RenderTexture lut);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsLogLutValid(orig_IsLogLutValid orig, ColorGradingComponent self, RenderTexture lut);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RenderTextureFormat orig_GetLutFormat(ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RenderTextureFormat hook_GetLutFormat(orig_GetLutFormat orig, ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_GenerateLut(ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_GenerateLut(orig_GenerateLut orig, ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Prepare(ColorGradingComponent self, Material uberMaterial);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Prepare(orig_Prepare orig, ColorGradingComponent self, Material uberMaterial);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnGUI(ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnGUI(orig_OnGUI orig, ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ColorGradingComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ColorGradingComponent self);

		public static class Uniforms
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_cctor();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_cctor(orig_cctor orig);

			public static event hook_cctor cctor
			{
				add
				{
					HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_StandardIlluminantY StandardIlluminantY
		{
			add
			{
				HookEndpointManager.Add<hook_StandardIlluminantY>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StandardIlluminantY>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CIExyToLMS CIExyToLMS
		{
			add
			{
				HookEndpointManager.Add<hook_CIExyToLMS>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CIExyToLMS>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CalculateColorBalance CalculateColorBalance
		{
			add
			{
				HookEndpointManager.Add<hook_CalculateColorBalance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CalculateColorBalance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_NormalizeColor NormalizeColor
		{
			add
			{
				HookEndpointManager.Add<hook_NormalizeColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_NormalizeColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ClampVector ClampVector
		{
			add
			{
				HookEndpointManager.Add<hook_ClampVector>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ClampVector>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetLiftValue GetLiftValue
		{
			add
			{
				HookEndpointManager.Add<hook_GetLiftValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetLiftValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetGammaValue GetGammaValue
		{
			add
			{
				HookEndpointManager.Add<hook_GetGammaValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetGammaValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetGainValue GetGainValue
		{
			add
			{
				HookEndpointManager.Add<hook_GetGainValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetGainValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CalculateLiftGammaGain CalculateLiftGammaGain
		{
			add
			{
				HookEndpointManager.Add<hook_CalculateLiftGammaGain>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CalculateLiftGammaGain>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetSlopeValue GetSlopeValue
		{
			add
			{
				HookEndpointManager.Add<hook_GetSlopeValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetSlopeValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetPowerValue GetPowerValue
		{
			add
			{
				HookEndpointManager.Add<hook_GetPowerValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetPowerValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetOffsetValue GetOffsetValue
		{
			add
			{
				HookEndpointManager.Add<hook_GetOffsetValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetOffsetValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CalculateSlopePowerOffset CalculateSlopePowerOffset
		{
			add
			{
				HookEndpointManager.Add<hook_CalculateSlopePowerOffset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CalculateSlopePowerOffset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCurveFormat GetCurveFormat
		{
			add
			{
				HookEndpointManager.Add<hook_GetCurveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCurveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCurveTexture GetCurveTexture
		{
			add
			{
				HookEndpointManager.Add<hook_GetCurveTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCurveTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_IsLogLutValid IsLogLutValid
		{
			add
			{
				HookEndpointManager.Add<hook_IsLogLutValid>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_IsLogLutValid>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetLutFormat GetLutFormat
		{
			add
			{
				HookEndpointManager.Add<hook_GetLutFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetLutFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GenerateLut GenerateLut
		{
			add
			{
				HookEndpointManager.Add<hook_GenerateLut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GenerateLut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Prepare Prepare
		{
			add
			{
				HookEndpointManager.Add<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnGUI OnGUI
		{
			add
			{
				HookEndpointManager.Add<hook_OnGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class ColorGradingComponent
	{
		public static class Uniforms
		{
			public static event Manipulator cctor
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator StandardIlluminantY
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_StandardIlluminantY>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_StandardIlluminantY>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CIExyToLMS
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_CIExyToLMS>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_CIExyToLMS>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CalculateColorBalance
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_CalculateColorBalance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_CalculateColorBalance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator NormalizeColor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_NormalizeColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_NormalizeColor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ClampVector
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_ClampVector>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_ClampVector>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetLiftValue
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetLiftValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetLiftValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetGammaValue
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetGammaValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetGammaValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetGainValue
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetGainValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetGainValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CalculateLiftGammaGain
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_CalculateLiftGammaGain>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_CalculateLiftGammaGain>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetSlopeValue
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetSlopeValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetSlopeValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetPowerValue
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetPowerValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetPowerValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetOffsetValue
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetOffsetValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetOffsetValue>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CalculateSlopePowerOffset
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_CalculateSlopePowerOffset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_CalculateSlopePowerOffset>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetCurveFormat
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetCurveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetCurveFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetCurveTexture
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetCurveTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetCurveTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator IsLogLutValid
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_IsLogLutValid>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_IsLogLutValid>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetLutFormat
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetLutFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GetLutFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GenerateLut
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GenerateLut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_GenerateLut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Prepare
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnGUI
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_OnGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_OnGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.ColorGradingComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class DepthOfFieldComponent
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DepthTextureMode orig_GetCameraFlags(DepthOfFieldComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DepthTextureMode hook_GetCameraFlags(orig_GetCameraFlags orig, DepthOfFieldComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_CalculateFocalLength(DepthOfFieldComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_CalculateFocalLength(orig_CalculateFocalLength orig, DepthOfFieldComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_CalculateMaxCoCRadius(DepthOfFieldComponent self, int screenHeight);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_CalculateMaxCoCRadius(orig_CalculateMaxCoCRadius orig, DepthOfFieldComponent self, int screenHeight);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckHistory(DepthOfFieldComponent self, int width, int height);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckHistory(orig_CheckHistory orig, DepthOfFieldComponent self, int width, int height);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RenderTextureFormat orig_SelectFormat(DepthOfFieldComponent self, RenderTextureFormat primary, RenderTextureFormat secondary);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate RenderTextureFormat hook_SelectFormat(orig_SelectFormat orig, DepthOfFieldComponent self, RenderTextureFormat primary, RenderTextureFormat secondary);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Prepare(DepthOfFieldComponent self, RenderTexture source, Material uberMaterial, bool antialiasCoC, Vector2 taaJitter, float taaBlending);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Prepare(orig_Prepare orig, DepthOfFieldComponent self, RenderTexture source, Material uberMaterial, bool antialiasCoC, Vector2 taaJitter, float taaBlending);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(DepthOfFieldComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, DepthOfFieldComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(DepthOfFieldComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, DepthOfFieldComponent self);

		public static class Uniforms
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_cctor();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_cctor(orig_cctor orig);

			public static event hook_cctor cctor
			{
				add
				{
					HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_GetCameraFlags GetCameraFlags
		{
			add
			{
				HookEndpointManager.Add<hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CalculateFocalLength CalculateFocalLength
		{
			add
			{
				HookEndpointManager.Add<hook_CalculateFocalLength>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CalculateFocalLength>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CalculateMaxCoCRadius CalculateMaxCoCRadius
		{
			add
			{
				HookEndpointManager.Add<hook_CalculateMaxCoCRadius>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CalculateMaxCoCRadius>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CheckHistory CheckHistory
		{
			add
			{
				HookEndpointManager.Add<hook_CheckHistory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckHistory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SelectFormat SelectFormat
		{
			add
			{
				HookEndpointManager.Add<hook_SelectFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SelectFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Prepare Prepare
		{
			add
			{
				HookEndpointManager.Add<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class DepthOfFieldComponent
	{
		public static class Uniforms
		{
			public static event Manipulator cctor
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator GetCameraFlags
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_GetCameraFlags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CalculateFocalLength
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_CalculateFocalLength>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_CalculateFocalLength>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CalculateMaxCoCRadius
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_CalculateMaxCoCRadius>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_CalculateMaxCoCRadius>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CheckHistory
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_CheckHistory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_CheckHistory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SelectFormat
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_SelectFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_SelectFormat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Prepare
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DepthOfFieldComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class DitheringComponent
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(DitheringComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, DitheringComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_LoadNoiseTextures(DitheringComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_LoadNoiseTextures(orig_LoadNoiseTextures orig, DitheringComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Prepare(DitheringComponent self, Material uberMaterial);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Prepare(orig_Prepare orig, DitheringComponent self, Material uberMaterial);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(DitheringComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, DitheringComponent self);

		public static class Uniforms
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_cctor();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_cctor(orig_cctor orig);

			public static event hook_cctor cctor
			{
				add
				{
					HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_LoadNoiseTextures LoadNoiseTextures
		{
			add
			{
				HookEndpointManager.Add<hook_LoadNoiseTextures>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_LoadNoiseTextures>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Prepare Prepare
		{
			add
			{
				HookEndpointManager.Add<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class DitheringComponent
	{
		public static class Uniforms
		{
			public static event Manipulator cctor
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DitheringComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DitheringComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DitheringComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DitheringComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator LoadNoiseTextures
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DitheringComponent.hook_LoadNoiseTextures>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DitheringComponent.hook_LoadNoiseTextures>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Prepare
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DitheringComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DitheringComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.DitheringComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.DitheringComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class EyeAdaptationComponent
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ResetHistory(EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ResetHistory(orig_ResetHistory orig, EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector4 orig_GetHistogramScaleOffsetRes(EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector4 hook_GetHistogramScaleOffsetRes(orig_GetHistogramScaleOffsetRes orig, EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture orig_Prepare(EyeAdaptationComponent self, RenderTexture source, Material uberMaterial);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Texture hook_Prepare(orig_Prepare orig, EyeAdaptationComponent self, RenderTexture source, Material uberMaterial);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnGUI(EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnGUI(orig_OnGUI orig, EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(EyeAdaptationComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, EyeAdaptationComponent self);

		public static class Uniforms
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_cctor();

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_cctor(orig_cctor orig);

			public static event hook_cctor cctor
			{
				add
				{
					HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_ResetHistory ResetHistory
		{
			add
			{
				HookEndpointManager.Add<hook_ResetHistory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ResetHistory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetHistogramScaleOffsetRes GetHistogramScaleOffsetRes
		{
			add
			{
				HookEndpointManager.Add<hook_GetHistogramScaleOffsetRes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetHistogramScaleOffsetRes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Prepare Prepare
		{
			add
			{
				HookEndpointManager.Add<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnGUI OnGUI
		{
			add
			{
				HookEndpointManager.Add<hook_OnGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityEngine.PostProcessing
{
	public static class EyeAdaptationComponent
	{
		public static class Uniforms
		{
			public static event Manipulator cctor
			{
				add
				{
					HookEndpointManager.Modify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.Uniforms.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator ResetHistory
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_ResetHistory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_ResetHistory>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetHistogramScaleOffsetRes
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_GetHistogramScaleOffsetRes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_GetHistogramScaleOffsetRes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Prepare
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_Prepare>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnGUI
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_OnGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_OnGUI>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityEngine.PostProcessing.EyeAdaptationComponent.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityEngine.PostProcessing
{
	public static class FogComponent
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetName(FogComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetName(orig_GetName orig, FogComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DepthTextureMode orig_GetCameraFlags(FogComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DepthTextureMode hook_GetCameraFlags(orig_GetCameraFlags orig, FogComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate CameraEvent orig_GetCameraEvent(FogComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate CameraEvent hook_GetCameraEvent(orig_GetCameraEvent orig, FogComponent self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_PopulateCommandBuffer(FogComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_PopulateCommandBuffer(orig_PopulateCommandBuffer orig, FogComponent self, CommandBuffer cb);

		[EditorBrowsable(EditorBrowsableSt

BepInEx/plugins/MMHOOK/MMHOOK_assembly_simplemeshcombine.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On;
using UnityEngine;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class RunTimeCombineAndRelease
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(RunTimeCombineAndRelease self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, RunTimeCombineAndRelease self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(RunTimeCombineAndRelease self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, RunTimeCombineAndRelease self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Combine(RunTimeCombineAndRelease self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Combine(orig_Combine orig, RunTimeCombineAndRelease self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Release(RunTimeCombineAndRelease self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Release(orig_Release orig, RunTimeCombineAndRelease self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(RunTimeCombineAndRelease self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, RunTimeCombineAndRelease self);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Combine Combine
		{
			add
			{
				HookEndpointManager.Add<hook_Combine>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Combine>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Release Release
		{
			add
			{
				HookEndpointManager.Add<hook_Release>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Release>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class RunTimeCombineAndRelease
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.RunTimeCombineAndRelease.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.RunTimeCombineAndRelease.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.RunTimeCombineAndRelease.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.RunTimeCombineAndRelease.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Combine
		{
			add
			{
				HookEndpointManager.Modify<On.RunTimeCombineAndRelease.hook_Combine>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.RunTimeCombineAndRelease.hook_Combine>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Release
		{
			add
			{
				HookEndpointManager.Modify<On.RunTimeCombineAndRelease.hook_Release>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.RunTimeCombineAndRelease.hook_Release>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.RunTimeCombineAndRelease.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.RunTimeCombineAndRelease.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class SimpleMeshCombine
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_EnableRenderers(SimpleMeshCombine self, bool e);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_EnableRenderers(orig_EnableRenderers orig, SimpleMeshCombine self, bool e);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate MeshFilter[] orig_FindEnabledMeshes(SimpleMeshCombine self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate MeshFilter[] hook_FindEnabledMeshes(orig_FindEnabledMeshes orig, SimpleMeshCombine self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CombineMeshes(SimpleMeshCombine self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CombineMeshes(orig_CombineMeshes orig, SimpleMeshCombine self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_Contains(SimpleMeshCombine self, ArrayList l, Material n);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_Contains(orig_Contains orig, SimpleMeshCombine self, ArrayList l, Material n);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(SimpleMeshCombine self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, SimpleMeshCombine self);

		public static event hook_EnableRenderers EnableRenderers
		{
			add
			{
				HookEndpointManager.Add<hook_EnableRenderers>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EnableRenderers>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FindEnabledMeshes FindEnabledMeshes
		{
			add
			{
				HookEndpointManager.Add<hook_FindEnabledMeshes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FindEnabledMeshes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CombineMeshes CombineMeshes
		{
			add
			{
				HookEndpointManager.Add<hook_CombineMeshes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CombineMeshes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Contains Contains
		{
			add
			{
				HookEndpointManager.Add<hook_Contains>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Contains>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class SimpleMeshCombine
	{
		public static event Manipulator EnableRenderers
		{
			add
			{
				HookEndpointManager.Modify<On.SimpleMeshCombine.hook_EnableRenderers>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SimpleMeshCombine.hook_EnableRenderers>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator FindEnabledMeshes
		{
			add
			{
				HookEndpointManager.Modify<On.SimpleMeshCombine.hook_FindEnabledMeshes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SimpleMeshCombine.hook_FindEnabledMeshes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CombineMeshes
		{
			add
			{
				HookEndpointManager.Modify<On.SimpleMeshCombine.hook_CombineMeshes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SimpleMeshCombine.hook_CombineMeshes>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Contains
		{
			add
			{
				HookEndpointManager.Modify<On.SimpleMeshCombine.hook_Contains>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SimpleMeshCombine.hook_Contains>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.SimpleMeshCombine.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SimpleMeshCombine.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class SimpleMeshCombineMaster
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(SimpleMeshCombineMaster self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, SimpleMeshCombineMaster self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class SimpleMeshCombineMaster
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.SimpleMeshCombineMaster.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SimpleMeshCombineMaster.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace BepHookGen
{
	[StructLayout(LayoutKind.Auto, CharSet = CharSet.Auto)]
	internal class size7168
	{
	}
}

BepInEx/plugins/MMHOOK/MMHOOK_assembly_sunshafts.dll

Decompiled 8 months ago
using System;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On.UnityStandardAssets.ImageEffects;
using UnityEngine;
using UnityStandardAssets.ImageEffects;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On.UnityStandardAssets.ImageEffects
{
	public static class Antialiasing
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Material orig_CurrentAAMaterial(Antialiasing self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Material hook_CurrentAAMaterial(orig_CurrentAAMaterial orig, Antialiasing self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(Antialiasing self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, Antialiasing self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(Antialiasing self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, Antialiasing self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Antialiasing self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Antialiasing self);

		public static event hook_CurrentAAMaterial CurrentAAMaterial
		{
			add
			{
				HookEndpointManager.Add<hook_CurrentAAMaterial>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CurrentAAMaterial>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class Antialiasing
	{
		public static event Manipulator CurrentAAMaterial
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Antialiasing.hook_CurrentAAMaterial>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Antialiasing.hook_CurrentAAMaterial>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Antialiasing.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Antialiasing.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Antialiasing.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Antialiasing.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Antialiasing.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Antialiasing.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class Bloom
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(Bloom self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, Bloom self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(Bloom self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, Bloom self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddTo(Bloom self, float intensity_, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddTo(orig_AddTo orig, Bloom self, float intensity_, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_BlendFlares(Bloom self, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_BlendFlares(orig_BlendFlares orig, Bloom self, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_BrightFilter_float_RenderTexture_RenderTexture(Bloom self, float thresh, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_BrightFilter_float_RenderTexture_RenderTexture(orig_BrightFilter_float_RenderTexture_RenderTexture orig, Bloom self, float thresh, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_BrightFilter_Color_RenderTexture_RenderTexture(Bloom self, Color threshColor, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_BrightFilter_Color_RenderTexture_RenderTexture(orig_BrightFilter_Color_RenderTexture_RenderTexture orig, Bloom self, Color threshColor, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Vignette(Bloom self, float amount, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Vignette(orig_Vignette orig, Bloom self, float amount, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Bloom self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Bloom self);

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddTo AddTo
		{
			add
			{
				HookEndpointManager.Add<hook_AddTo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddTo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BlendFlares BlendFlares
		{
			add
			{
				HookEndpointManager.Add<hook_BlendFlares>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BlendFlares>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BrightFilter_float_RenderTexture_RenderTexture BrightFilter_float_RenderTexture_RenderTexture
		{
			add
			{
				HookEndpointManager.Add<hook_BrightFilter_float_RenderTexture_RenderTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BrightFilter_float_RenderTexture_RenderTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BrightFilter_Color_RenderTexture_RenderTexture BrightFilter_Color_RenderTexture_RenderTexture
		{
			add
			{
				HookEndpointManager.Add<hook_BrightFilter_Color_RenderTexture_RenderTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BrightFilter_Color_RenderTexture_RenderTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Vignette Vignette
		{
			add
			{
				HookEndpointManager.Add<hook_Vignette>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Vignette>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class Bloom
	{
		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Bloom.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Bloom.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Bloom.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Bloom.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AddTo
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Bloom.hook_AddTo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Bloom.hook_AddTo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator BlendFlares
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Bloom.hook_BlendFlares>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Bloom.hook_BlendFlares>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator BrightFilter_float_RenderTexture_RenderTexture
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Bloom.hook_BrightFilter_float_RenderTexture_RenderTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Bloom.hook_BrightFilter_float_RenderTexture_RenderTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator BrightFilter_Color_RenderTexture_RenderTexture
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Bloom.hook_BrightFilter_Color_RenderTexture_RenderTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Bloom.hook_BrightFilter_Color_RenderTexture_RenderTexture>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Vignette
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Bloom.hook_Vignette>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Bloom.hook_Vignette>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Bloom.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Bloom.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class BloomAndFlares
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(BloomAndFlares self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, BloomAndFlares self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(BloomAndFlares self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, BloomAndFlares self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddTo(BloomAndFlares self, float intensity_, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddTo(orig_AddTo orig, BloomAndFlares self, float intensity_, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_BlendFlares(BloomAndFlares self, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_BlendFlares(orig_BlendFlares orig, BloomAndFlares self, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_BrightFilter(BloomAndFlares self, float thresh, float useAlphaAsMask, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_BrightFilter(orig_BrightFilter orig, BloomAndFlares self, float thresh, float useAlphaAsMask, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Vignette(BloomAndFlares self, float amount, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Vignette(orig_Vignette orig, BloomAndFlares self, float amount, RenderTexture from, RenderTexture to);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(BloomAndFlares self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, BloomAndFlares self);

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddTo AddTo
		{
			add
			{
				HookEndpointManager.Add<hook_AddTo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddTo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BlendFlares BlendFlares
		{
			add
			{
				HookEndpointManager.Add<hook_BlendFlares>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BlendFlares>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BrightFilter BrightFilter
		{
			add
			{
				HookEndpointManager.Add<hook_BrightFilter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BrightFilter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Vignette Vignette
		{
			add
			{
				HookEndpointManager.Add<hook_Vignette>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Vignette>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class BloomAndFlares
	{
		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AddTo
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_AddTo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_AddTo>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator BlendFlares
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_BlendFlares>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_BlendFlares>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator BrightFilter
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_BrightFilter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_BrightFilter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Vignette
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_Vignette>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_Vignette>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomAndFlares.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class BloomOptimized
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(BloomOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, BloomOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(BloomOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, BloomOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(BloomOptimized self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, BloomOptimized self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(BloomOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, BloomOptimized self);

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class BloomOptimized
	{
		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomOptimized.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomOptimized.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomOptimized.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomOptimized.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomOptimized.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomOptimized.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BloomOptimized.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BloomOptimized.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class Blur
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(Blur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, Blur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(Blur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, Blur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_FourTapCone(Blur self, RenderTexture source, RenderTexture dest, int iteration);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_FourTapCone(orig_FourTapCone orig, Blur self, RenderTexture source, RenderTexture dest, int iteration);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DownSample4x(Blur self, RenderTexture source, RenderTexture dest);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DownSample4x(orig_DownSample4x orig, Blur self, RenderTexture source, RenderTexture dest);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(Blur self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, Blur self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Blur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Blur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FourTapCone FourTapCone
		{
			add
			{
				HookEndpointManager.Add<hook_FourTapCone>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FourTapCone>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DownSample4x DownSample4x
		{
			add
			{
				HookEndpointManager.Add<hook_DownSample4x>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DownSample4x>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class Blur
	{
		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Blur.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Blur.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Blur.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Blur.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator FourTapCone
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Blur.hook_FourTapCone>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Blur.hook_FourTapCone>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator DownSample4x
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Blur.hook_DownSample4x>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Blur.hook_DownSample4x>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Blur.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Blur.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Blur.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Blur.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.Blur.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.Blur.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class BlurOptimized
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(BlurOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, BlurOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(BlurOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, BlurOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(BlurOptimized self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, BlurOptimized self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(BlurOptimized self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, BlurOptimized self);

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class BlurOptimized
	{
		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BlurOptimized.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BlurOptimized.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BlurOptimized.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BlurOptimized.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BlurOptimized.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BlurOptimized.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.BlurOptimized.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.BlurOptimized.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class CameraMotionBlur
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CalculateViewProjection(CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CalculateViewProjection(orig_CalculateViewProjection orig, CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(CameraMotionBlur self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, CameraMotionBlur self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Remember(CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Remember(orig_Remember orig, CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Camera orig_GetTmpCam(CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Camera hook_GetTmpCam(orig_GetTmpCam orig, CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StartFrame(CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StartFrame(orig_StartFrame orig, CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_divRoundUp(int x, int d);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_divRoundUp(orig_divRoundUp orig, int x, int d);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, CameraMotionBlur self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_CalculateViewProjection CalculateViewProjection
		{
			add
			{
				HookEndpointManager.Add<hook_CalculateViewProjection>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CalculateViewProjection>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Remember Remember
		{
			add
			{
				HookEndpointManager.Add<hook_Remember>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Remember>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetTmpCam GetTmpCam
		{
			add
			{
				HookEndpointManager.Add<hook_GetTmpCam>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetTmpCam>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_StartFrame StartFrame
		{
			add
			{
				HookEndpointManager.Add<hook_StartFrame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_StartFrame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_divRoundUp divRoundUp
		{
			add
			{
				HookEndpointManager.Add<hook_divRoundUp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_divRoundUp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class CameraMotionBlur
	{
		public static event Manipulator CalculateViewProjection
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_CalculateViewProjection>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_CalculateViewProjection>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Remember
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_Remember>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_Remember>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetTmpCam
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_GetTmpCam>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_GetTmpCam>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator StartFrame
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_StartFrame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_StartFrame>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator divRoundUp
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_divRoundUp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_divRoundUp>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CameraMotionBlur.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class ColorCorrectionCurves
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateParameters(ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateParameters(orig_UpdateParameters orig, ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateTextures(ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateTextures(orig_UpdateTextures orig, ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(ColorCorrectionCurves self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, ColorCorrectionCurves self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ColorCorrectionCurves self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ColorCorrectionCurves self);

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateParameters UpdateParameters
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateParameters>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateParameters>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateTextures UpdateTextures
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateTextures>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateTextures>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class ColorCorrectionCurves
	{
		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateParameters
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_UpdateParameters>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_UpdateParameters>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateTextures
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_UpdateTextures>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_UpdateTextures>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionCurves.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class ColorCorrectionLookup
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(ColorCorrectionLookup self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, ColorCorrectionLookup self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(ColorCorrectionLookup self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, ColorCorrectionLookup self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDestroy(ColorCorrectionLookup self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDestroy(orig_OnDestroy orig, ColorCorrectionLookup self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetIdentityLut(ColorCorrectionLookup self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetIdentityLut(orig_SetIdentityLut orig, ColorCorrectionLookup self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_ValidDimensions(ColorCorrectionLookup self, Texture2D tex2d);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_ValidDimensions(orig_ValidDimensions orig, ColorCorrectionLookup self, Texture2D tex2d);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Convert(ColorCorrectionLookup self, Texture2D temp2DTex, string path);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Convert(orig_Convert orig, ColorCorrectionLookup self, Texture2D temp2DTex, string path);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(ColorCorrectionLookup self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, ColorCorrectionLookup self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ColorCorrectionLookup self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ColorCorrectionLookup self);

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDestroy OnDestroy
		{
			add
			{
				HookEndpointManager.Add<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetIdentityLut SetIdentityLut
		{
			add
			{
				HookEndpointManager.Add<hook_SetIdentityLut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetIdentityLut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ValidDimensions ValidDimensions
		{
			add
			{
				HookEndpointManager.Add<hook_ValidDimensions>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ValidDimensions>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Convert Convert
		{
			add
			{
				HookEndpointManager.Add<hook_Convert>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Convert>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class ColorCorrectionLookup
	{
		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDestroy
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetIdentityLut
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_SetIdentityLut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_SetIdentityLut>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ValidDimensions
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_ValidDimensions>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_ValidDimensions>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Convert
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_Convert>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_Convert>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionLookup.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class ColorCorrectionRamp
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(ColorCorrectionRamp self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, ColorCorrectionRamp self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ColorCorrectionRamp self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ColorCorrectionRamp self);

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class ColorCorrectionRamp
	{
		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionRamp.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionRamp.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ColorCorrectionRamp.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ColorCorrectionRamp.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class ContrastEnhance
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(ContrastEnhance self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, ContrastEnhance self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(ContrastEnhance self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, ContrastEnhance self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ContrastEnhance self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ContrastEnhance self);

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class ContrastEnhance
	{
		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ContrastEnhance.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ContrastEnhance.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ContrastEnhance.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ContrastEnhance.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ContrastEnhance.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ContrastEnhance.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class ContrastStretch
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(ContrastStretch self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, ContrastStretch self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(ContrastStretch self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, ContrastStretch self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(ContrastStretch self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, ContrastStretch self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(ContrastStretch self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, ContrastStretch self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CalculateAdaptation(ContrastStretch self, Texture curTexture);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CalculateAdaptation(orig_CalculateAdaptation orig, ContrastStretch self, Texture curTexture);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(ContrastStretch self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, ContrastStretch self);

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CalculateAdaptation CalculateAdaptation
		{
			add
			{
				HookEndpointManager.Add<hook_CalculateAdaptation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CalculateAdaptation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class ContrastStretch
	{
		public static event Manipulator Start
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CalculateAdaptation
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_CalculateAdaptation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_CalculateAdaptation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.ContrastStretch.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class CreaseShading
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(CreaseShading self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, CreaseShading self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(CreaseShading self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, CreaseShading self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(CreaseShading self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, CreaseShading self);

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class CreaseShading
	{
		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CreaseShading.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CreaseShading.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnRenderImage
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CreaseShading.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CreaseShading.hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.CreaseShading.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.CreaseShading.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On.UnityStandardAssets.ImageEffects
{
	public static class DepthOfField
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckResources(DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckResources(orig_CheckResources orig, DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ReleaseComputeResources(DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ReleaseComputeResources(orig_ReleaseComputeResources orig, DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CreateComputeResources(DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CreateComputeResources(orig_CreateComputeResources orig, DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_FocalDistance01(DepthOfField self, float worldDist);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_FocalDistance01(orig_FocalDistance01 orig, DepthOfField self, float worldDist);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_WriteCoc(DepthOfField self, RenderTexture fromTo, bool fgDilate);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_WriteCoc(orig_WriteCoc orig, DepthOfField self, RenderTexture fromTo, bool fgDilate);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRenderImage(DepthOfField self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRenderImage(orig_OnRenderImage orig, DepthOfField self, RenderTexture source, RenderTexture destination);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(DepthOfField self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, DepthOfField self);

		public static event hook_CheckResources CheckResources
		{
			add
			{
				HookEndpointManager.Add<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ReleaseComputeResources ReleaseComputeResources
		{
			add
			{
				HookEndpointManager.Add<hook_ReleaseComputeResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ReleaseComputeResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CreateComputeResources CreateComputeResources
		{
			add
			{
				HookEndpointManager.Add<hook_CreateComputeResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CreateComputeResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FocalDistance01 FocalDistance01
		{
			add
			{
				HookEndpointManager.Add<hook_FocalDistance01>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FocalDistance01>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_WriteCoc WriteCoc
		{
			add
			{
				HookEndpointManager.Add<hook_WriteCoc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_WriteCoc>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnRenderImage OnRenderImage
		{
			add
			{
				HookEndpointManager.Add<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnRenderImage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL.UnityStandardAssets.ImageEffects
{
	public static class DepthOfField
	{
		public static event Manipulator CheckResources
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.DepthOfField.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.DepthOfField.hook_CheckResources>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnEnable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.DepthOfField.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.UnityStandardAssets.ImageEffects.DepthOfField.hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnDisable
		{
			add
			{
				HookEndpointManager.Modify<On.UnityStandardAssets.ImageEffects.DepthOfField.hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookE

BepInEx/plugins/MMHOOK/MMHOOK_assembly_utils.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using LlamAcademy.Spring;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On;
using On.LlamAcademy.Spring;
using UnityEngine;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class Cover
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_GetCoverForPoint(Vector3 startPos, out float coverPercentage, out bool underRoof, float minDistance);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_GetCoverForPoint(orig_GetCoverForPoint orig, Vector3 startPos, out float coverPercentage, out bool underRoof, float minDistance);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsUnderRoof(Vector3 startPos);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsUnderRoof(orig_IsUnderRoof orig, Vector3 startPos);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Setup();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Setup(orig_Setup orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CreateCoverRays();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CreateCoverRays(orig_CreateCoverRays orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Cover self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Cover self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_GetCoverForPoint GetCoverForPoint
		{
			add
			{
				HookEndpointManager.Add<hook_GetCoverForPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCoverForPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_IsUnderRoof IsUnderRoof
		{
			add
			{
				HookEndpointManager.Add<hook_IsUnderRoof>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_IsUnderRoof>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Setup Setup
		{
			add
			{
				HookEndpointManager.Add<hook_Setup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Setup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CreateCoverRays CreateCoverRays
		{
			add
			{
				HookEndpointManager.Add<hook_CreateCoverRays>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CreateCoverRays>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class Cover
	{
		public static event Manipulator GetCoverForPoint
		{
			add
			{
				HookEndpointManager.Modify<On.Cover.hook_GetCoverForPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Cover.hook_GetCoverForPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator IsUnderRoof
		{
			add
			{
				HookEndpointManager.Modify<On.Cover.hook_IsUnderRoof>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Cover.hook_IsUnderRoof>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Setup
		{
			add
			{
				HookEndpointManager.Modify<On.Cover.hook_Setup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Cover.hook_Setup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CreateCoverRays
		{
			add
			{
				HookEndpointManager.Modify<On.Cover.hook_CreateCoverRays>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Cover.hook_CreateCoverRays>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.Cover.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Cover.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.Cover.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.Cover.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class DrawBounds
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDrawGizmosSelected(DrawBounds self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDrawGizmosSelected(orig_OnDrawGizmosSelected orig, DrawBounds self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(DrawBounds self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, DrawBounds self);

		public static event hook_OnDrawGizmosSelected OnDrawGizmosSelected
		{
			add
			{
				HookEndpointManager.Add<hook_OnDrawGizmosSelected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDrawGizmosSelected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class DrawBounds
	{
		public static event Manipulator OnDrawGizmosSelected
		{
			add
			{
				HookEndpointManager.Modify<On.DrawBounds.hook_OnDrawGizmosSelected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.DrawBounds.hook_OnDrawGizmosSelected>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.DrawBounds.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.DrawBounds.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class FileHelpers
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_BytesAsNumberString(ulong bytes, uint decimalCount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_BytesAsNumberString(orig_BytesAsNumberString orig, ulong bytes, uint decimalCount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SplitFilePath(string path, out string directory, out string fileName, out string fileExtension);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SplitFilePath(orig_SplitFilePath orig, string path, out string directory, out string fileName, out string fileExtension);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateCloudEnabledStatus();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateCloudEnabledStatus(orig_UpdateCloudEnabledStatus orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ReplaceOldFile(string saveFile, string newFile, string oldFile, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ReplaceOldFile(orig_ReplaceOldFile orig, string saveFile, string newFile, string oldFile, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Copy_string_string_FileSource(string source, string dest, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Copy_string_string_FileSource(orig_Copy_string_string_FileSource orig, string source, string dest, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Copy_string_FileSource_string_FileSource(string source, FileSource sourceLocation, string dest, FileSource destLocation);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Copy_string_FileSource_string_FileSource(orig_Copy_string_FileSource_string_FileSource orig, string source, FileSource sourceLocation, string dest, FileSource destLocation);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CloudMove(string source, string dest);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CloudMove(orig_CloudMove orig, string source, string dest);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_FileCopyIntoCloud(string source, string target);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_FileCopyIntoCloud(orig_FileCopyIntoCloud orig, string source, string target);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_FileCopyOutFromCloud(string cloudFilePath, string target, bool deleteOnCloud);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_FileCopyOutFromCloud(orig_FileCopyOutFromCloud orig, string cloudFilePath, string target, bool deleteOnCloud);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_FileExistsCloud(string cloudFilePath);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_FileExistsCloud(orig_FileExistsCloud orig, string cloudFilePath);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CloudFileWriteInChunks(string pchFile, byte[] data);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CloudFileWriteInChunks(orig_CloudFileWriteInChunks orig, string pchFile, byte[] data);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetSourceString(FileSource source);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetSourceString(orig_GetSourceString orig, FileSource source);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string[] orig_GetFiles(FileSource fileSource, string path, string fileSuffix, string searchPattern);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string[] hook_GetFiles(orig_GetFiles orig, FileSource fileSource, string path, string fileSuffix, string searchPattern);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsFileCorrupt(string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsFileCorrupt(orig_IsFileCorrupt orig, string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string[] orig_GetCorruptFiles(FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string[] hook_GetCorruptFiles(orig_GetCorruptFiles orig, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Delete(string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Delete(orig_Delete orig, string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DateTime orig_GetLastWriteTime(string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DateTime hook_GetLastWriteTime(orig_GetLastWriteTime orig, string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ulong orig_GetTotalCloudUsage();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ulong hook_GetTotalCloudUsage(orig_GetTotalCloudUsage orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ulong orig_GetTotalCloudCapacity();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ulong hook_GetTotalCloudCapacity(orig_GetTotalCloudCapacity orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate long orig_GetRemainingCloudCapacity();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate long hook_GetRemainingCloudCapacity(orig_GetRemainingCloudCapacity orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ulong orig_GetFileSize(string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ulong hook_GetFileSize(orig_GetFileSize orig, string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_OperationExceedsCloudCapacity(ulong requiredBytes);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_OperationExceedsCloudCapacity(orig_OperationExceedsCloudCapacity orig, ulong requiredBytes);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_TerminateCloudStorage();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_TerminateCloudStorage(orig_TerminateCloudStorage orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Exists(string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Exists(orig_Exists orig, string path, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_EnsureDirectoryExists(string path);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_EnsureDirectoryExists(orig_EnsureDirectoryExists orig, string path);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_<GetFiles>g__normalizePath|14_0(string str);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_<GetFiles>g__normalizePath|14_0(orig_<GetFiles>g__normalizePath|14_0 orig, string str);

		public static event hook_BytesAsNumberString BytesAsNumberString
		{
			add
			{
				HookEndpointManager.Add<hook_BytesAsNumberString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BytesAsNumberString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SplitFilePath SplitFilePath
		{
			add
			{
				HookEndpointManager.Add<hook_SplitFilePath>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SplitFilePath>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateCloudEnabledStatus UpdateCloudEnabledStatus
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateCloudEnabledStatus>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateCloudEnabledStatus>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ReplaceOldFile ReplaceOldFile
		{
			add
			{
				HookEndpointManager.Add<hook_ReplaceOldFile>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ReplaceOldFile>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Copy_string_string_FileSource Copy_string_string_FileSource
		{
			add
			{
				HookEndpointManager.Add<hook_Copy_string_string_FileSource>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Copy_string_string_FileSource>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Copy_string_FileSource_string_FileSource Copy_string_FileSource_string_FileSource
		{
			add
			{
				HookEndpointManager.Add<hook_Copy_string_FileSource_string_FileSource>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Copy_string_FileSource_string_FileSource>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CloudMove CloudMove
		{
			add
			{
				HookEndpointManager.Add<hook_CloudMove>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CloudMove>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FileCopyIntoCloud FileCopyIntoCloud
		{
			add
			{
				HookEndpointManager.Add<hook_FileCopyIntoCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FileCopyIntoCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FileCopyOutFromCloud FileCopyOutFromCloud
		{
			add
			{
				HookEndpointManager.Add<hook_FileCopyOutFromCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FileCopyOutFromCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FileExistsCloud FileExistsCloud
		{
			add
			{
				HookEndpointManager.Add<hook_FileExistsCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FileExistsCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CloudFileWriteInChunks CloudFileWriteInChunks
		{
			add
			{
				HookEndpointManager.Add<hook_CloudFileWriteInChunks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CloudFileWriteInChunks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetSourceString GetSourceString
		{
			add
			{
				HookEndpointManager.Add<hook_GetSourceString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetSourceString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetFiles GetFiles
		{
			add
			{
				HookEndpointManager.Add<hook_GetFiles>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetFiles>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_IsFileCorrupt IsFileCorrupt
		{
			add
			{
				HookEndpointManager.Add<hook_IsFileCorrupt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_IsFileCorrupt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCorruptFiles GetCorruptFiles
		{
			add
			{
				HookEndpointManager.Add<hook_GetCorruptFiles>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCorruptFiles>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Delete Delete
		{
			add
			{
				HookEndpointManager.Add<hook_Delete>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Delete>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetLastWriteTime GetLastWriteTime
		{
			add
			{
				HookEndpointManager.Add<hook_GetLastWriteTime>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetLastWriteTime>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetTotalCloudUsage GetTotalCloudUsage
		{
			add
			{
				HookEndpointManager.Add<hook_GetTotalCloudUsage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetTotalCloudUsage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetTotalCloudCapacity GetTotalCloudCapacity
		{
			add
			{
				HookEndpointManager.Add<hook_GetTotalCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetTotalCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetRemainingCloudCapacity GetRemainingCloudCapacity
		{
			add
			{
				HookEndpointManager.Add<hook_GetRemainingCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetRemainingCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetFileSize GetFileSize
		{
			add
			{
				HookEndpointManager.Add<hook_GetFileSize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetFileSize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OperationExceedsCloudCapacity OperationExceedsCloudCapacity
		{
			add
			{
				HookEndpointManager.Add<hook_OperationExceedsCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OperationExceedsCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_TerminateCloudStorage TerminateCloudStorage
		{
			add
			{
				HookEndpointManager.Add<hook_TerminateCloudStorage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_TerminateCloudStorage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Exists Exists
		{
			add
			{
				HookEndpointManager.Add<hook_Exists>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Exists>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_EnsureDirectoryExists EnsureDirectoryExists
		{
			add
			{
				HookEndpointManager.Add<hook_EnsureDirectoryExists>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EnsureDirectoryExists>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_cctor cctor
		{
			add
			{
				HookEndpointManager.Add<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_<GetFiles>g__normalizePath|14_0 <GetFiles>g__normalizePath|14_0
		{
			add
			{
				HookEndpointManager.Add<hook_<GetFiles>g__normalizePath|14_0>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_<GetFiles>g__normalizePath|14_0>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class FileHelpers
	{
		public static event Manipulator BytesAsNumberString
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_BytesAsNumberString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_BytesAsNumberString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SplitFilePath
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_SplitFilePath>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_SplitFilePath>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator UpdateCloudEnabledStatus
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_UpdateCloudEnabledStatus>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_UpdateCloudEnabledStatus>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ReplaceOldFile
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_ReplaceOldFile>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_ReplaceOldFile>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Copy_string_string_FileSource
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_Copy_string_string_FileSource>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_Copy_string_string_FileSource>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Copy_string_FileSource_string_FileSource
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_Copy_string_FileSource_string_FileSource>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_Copy_string_FileSource_string_FileSource>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CloudMove
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_CloudMove>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_CloudMove>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator FileCopyIntoCloud
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_FileCopyIntoCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_FileCopyIntoCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator FileCopyOutFromCloud
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_FileCopyOutFromCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_FileCopyOutFromCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator FileExistsCloud
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_FileExistsCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_FileExistsCloud>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CloudFileWriteInChunks
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_CloudFileWriteInChunks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_CloudFileWriteInChunks>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetSourceString
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_GetSourceString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_GetSourceString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetFiles
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_GetFiles>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_GetFiles>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator IsFileCorrupt
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_IsFileCorrupt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_IsFileCorrupt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetCorruptFiles
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_GetCorruptFiles>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_GetCorruptFiles>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Delete
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_Delete>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_Delete>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetLastWriteTime
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_GetLastWriteTime>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_GetLastWriteTime>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetTotalCloudUsage
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_GetTotalCloudUsage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_GetTotalCloudUsage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetTotalCloudCapacity
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_GetTotalCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_GetTotalCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetRemainingCloudCapacity
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_GetRemainingCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_GetRemainingCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetFileSize
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_GetFileSize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_GetFileSize>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OperationExceedsCloudCapacity
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_OperationExceedsCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_OperationExceedsCloudCapacity>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator TerminateCloudStorage
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_TerminateCloudStorage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_TerminateCloudStorage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Exists
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_Exists>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_Exists>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator EnsureDirectoryExists
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_EnsureDirectoryExists>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_EnsureDirectoryExists>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator cctor
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_cctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator <GetFiles>g__normalizePath|14_0
		{
			add
			{
				HookEndpointManager.Modify<On.FileHelpers.hook_<GetFiles>g__normalizePath|14_0>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileHelpers.hook_<GetFiles>g__normalizePath|14_0>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class FileWriter
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(FileWriter self, string path, FileHelperType type, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, FileWriter self, string path, FileHelperType type, FileSource fileSource);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Finish(FileWriter self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Finish(orig_Finish orig, FileWriter self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DumpCloudWriteToLocalFile(FileWriter self, string localPath);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DumpCloudWriteToLocalFile(orig_DumpCloudWriteToLocalFile orig, FileWriter self, string localPath);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Finish Finish
		{
			add
			{
				HookEndpointManager.Add<hook_Finish>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Finish>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DumpCloudWriteToLocalFile DumpCloudWriteToLocalFile
		{
			add
			{
				HookEndpointManager.Add<hook_DumpCloudWriteToLocalFile>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DumpCloudWriteToLocalFile>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class FileWriter
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.FileWriter.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileWriter.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Finish
		{
			add
			{
				HookEndpointManager.Modify<On.FileWriter.hook_Finish>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileWriter.hook_Finish>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator DumpCloudWriteToLocalFile
		{
			add
			{
				HookEndpointManager.Modify<On.FileWriter.hook_DumpCloudWriteToLocalFile>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileWriter.hook_DumpCloudWriteToLocalFile>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class FileReader
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(FileReader self, string path, FileSource fileSource, FileHelperType type);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, FileReader self, string path, FileSource fileSource, FileHelperType type);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Dispose(FileReader self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Dispose(orig_Dispose orig, FileReader self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Dispose Dispose
		{
			add
			{
				HookEndpointManager.Add<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class FileReader
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.FileReader.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileReader.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Dispose
		{
			add
			{
				HookEndpointManager.Modify<On.FileReader.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.FileReader.hook_Dispose>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class HideWhenRunning
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(HideWhenRunning self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, HideWhenRunning self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(HideWhenRunning self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, HideWhenRunning self);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class HideWhenRunning
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.HideWhenRunning.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.HideWhenRunning.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.HideWhenRunning.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.HideWhenRunning.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class InputActionsSwitcher
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(InputActionsSwitcher self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, InputActionsSwitcher self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class InputActionsSwitcher
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.InputActionsSwitcher.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.InputActionsSwitcher.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class LookAt
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(LookAt self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, LookAt self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnAnimatorIK(LookAt self, int layerIndex);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnAnimatorIK(orig_OnAnimatorIK orig, LookAt self, int layerIndex);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetLoockAtTarget(LookAt self, Vector3 target);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetLoockAtTarget(orig_SetLoockAtTarget orig, LookAt self, Vector3 target);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ResetTarget(LookAt self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ResetTarget(orig_ResetTarget orig, LookAt self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(LookAt self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, LookAt self);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnAnimatorIK OnAnimatorIK
		{
			add
			{
				HookEndpointManager.Add<hook_OnAnimatorIK>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnAnimatorIK>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetLoockAtTarget SetLoockAtTarget
		{
			add
			{
				HookEndpointManager.Add<hook_SetLoockAtTarget>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetLoockAtTarget>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ResetTarget ResetTarget
		{
			add
			{
				HookEndpointManager.Add<hook_ResetTarget>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ResetTarget>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class LookAt
	{
		public static event Manipulator Awake
		{
			add
			{
				HookEndpointManager.Modify<On.LookAt.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LookAt.hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnAnimatorIK
		{
			add
			{
				HookEndpointManager.Modify<On.LookAt.hook_OnAnimatorIK>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LookAt.hook_OnAnimatorIK>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetLoockAtTarget
		{
			add
			{
				HookEndpointManager.Modify<On.LookAt.hook_SetLoockAtTarget>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LookAt.hook_SetLoockAtTarget>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ResetTarget
		{
			add
			{
				HookEndpointManager.Modify<On.LookAt.hook_ResetTarget>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LookAt.hook_ResetTarget>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.LookAt.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.LookAt.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class PlatformPrefs
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor_float_bool(PlatformPrefs self, float val, bool saveSeperately);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor_float_bool(orig_ctor_float_bool orig, PlatformPrefs self, float val, bool saveSeperately);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor_int_bool(PlatformPrefs self, int val, bool saveSeperately);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor_int_bool(orig_ctor_int_bool orig, PlatformPrefs self, int val, bool saveSeperately);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor_string_bool(PlatformPrefs self, string val, bool saveSeperately);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor_string_bool(orig_ctor_string_bool orig, PlatformPrefs self, string val, bool saveSeperately);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetFloat(string name, float defaultValue);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetFloat(orig_GetFloat orig, string name, float defaultValue);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetFloat(string name, float value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetFloat(orig_SetFloat orig, string name, float value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetInt(string name, int defaultValue);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetInt(orig_GetInt orig, string name, int defaultValue);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetInt(string name, int value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetInt(orig_SetInt orig, string name, int value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetString(string name, string defaultValue);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetString(orig_GetString orig, string name, string defaultValue);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetString(string name, string value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetString(orig_SetString orig, string name, string value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckPlatformPref(ref string name, out PlatformPrefs pref);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckPlatformPref(orig_CheckPlatformPref orig, ref string name, out PlatformPrefs pref);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetDefaults(PlatformDefaults[] defaults);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetDefaults(orig_SetDefaults orig, PlatformDefaults[] defaults);

		public static class PlatformDefaults
		{
			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void orig_ctor(PlatformDefaults self, string name, Func<bool> check, Dictionary<string, PlatformPrefs> prefs);

			[EditorBrowsable(EditorBrowsableState.Never)]
			public delegate void hook_ctor(orig_ctor orig, PlatformDefaults self, string name, Func<bool> check, Dictionary<string, PlatformPrefs> prefs);

			public static event hook_ctor ctor
			{
				add
				{
					HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
				remove
				{
					HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
				}
			}
		}

		public static event hook_ctor_float_bool ctor_float_bool
		{
			add
			{
				HookEndpointManager.Add<hook_ctor_float_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor_float_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor_int_bool ctor_int_bool
		{
			add
			{
				HookEndpointManager.Add<hook_ctor_int_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor_int_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor_string_bool ctor_string_bool
		{
			add
			{
				HookEndpointManager.Add<hook_ctor_string_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor_string_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetFloat GetFloat
		{
			add
			{
				HookEndpointManager.Add<hook_GetFloat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetFloat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetFloat SetFloat
		{
			add
			{
				HookEndpointManager.Add<hook_SetFloat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetFloat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetInt GetInt
		{
			add
			{
				HookEndpointManager.Add<hook_GetInt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetInt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetInt SetInt
		{
			add
			{
				HookEndpointManager.Add<hook_SetInt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetInt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetString GetString
		{
			add
			{
				HookEndpointManager.Add<hook_GetString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetString SetString
		{
			add
			{
				HookEndpointManager.Add<hook_SetString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CheckPlatformPref CheckPlatformPref
		{
			add
			{
				HookEndpointManager.Add<hook_CheckPlatformPref>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckPlatformPref>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetDefaults SetDefaults
		{
			add
			{
				HookEndpointManager.Add<hook_SetDefaults>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetDefaults>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class PlatformPrefs
	{
		public static class PlatformDefaults
		{
			public static event Manipulator ctor
			{
				add
				{
					HookEndpointManager.Modify<On.PlatformPrefs.PlatformDefaults.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
				remove
				{
					HookEndpointManager.Unmodify<On.PlatformPrefs.PlatformDefaults.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
				}
			}
		}

		public static event Manipulator ctor_float_bool
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_ctor_float_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_ctor_float_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor_int_bool
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_ctor_int_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_ctor_int_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor_string_bool
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_ctor_string_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_ctor_string_bool>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetFloat
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_GetFloat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_GetFloat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetFloat
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_SetFloat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_SetFloat>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetInt
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_GetInt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_GetInt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetInt
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_SetInt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_SetInt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetString
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_GetString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_GetString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetString
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_SetString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_SetString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CheckPlatformPref
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_CheckPlatformPref>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_CheckPlatformPref>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator SetDefaults
		{
			add
			{
				HookEndpointManager.Modify<On.PlatformPrefs.hook_SetDefaults>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.PlatformPrefs.hook_SetDefaults>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class StringExtensionMethods
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetStableHashCode(string str);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetStableHashCode(orig_GetStableHashCode orig, string str);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int[] orig_AllIndicesOf_string_string(string thisString, string substring);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int[] hook_AllIndicesOf_string_string(orig_AllIndicesOf_string_string orig, string thisString, string substring);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int[] orig_AllIndicesOf_string_char(string thisString, char target);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int[] hook_AllIndicesOf_string_char(orig_AllIndicesOf_string_char orig, string thisString, char target);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_RemoveRichTextTags(string text);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_RemoveRichTextTags(orig_RemoveRichTextTags orig, string text);

		public static event hook_GetStableHashCode GetStableHashCode
		{
			add
			{
				HookEndpointManager.Add<hook_GetStableHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetStableHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AllIndicesOf_string_string AllIndicesOf_string_string
		{
			add
			{
				HookEndpointManager.Add<hook_AllIndicesOf_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AllIndicesOf_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AllIndicesOf_string_char AllIndicesOf_string_char
		{
			add
			{
				HookEndpointManager.Add<hook_AllIndicesOf_string_char>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AllIndicesOf_string_char>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RemoveRichTextTags RemoveRichTextTags
		{
			add
			{
				HookEndpointManager.Add<hook_RemoveRichTextTags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RemoveRichTextTags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class StringExtensionMethods
	{
		public static event Manipulator GetStableHashCode
		{
			add
			{
				HookEndpointManager.Modify<On.StringExtensionMethods.hook_GetStableHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.StringExtensionMethods.hook_GetStableHashCode>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AllIndicesOf_string_string
		{
			add
			{
				HookEndpointManager.Modify<On.StringExtensionMethods.hook_AllIndicesOf_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.StringExtensionMethods.hook_AllIndicesOf_string_string>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator AllIndicesOf_string_char
		{
			add
			{
				HookEndpointManager.Modify<On.StringExtensionMethods.hook_AllIndicesOf_string_char>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.StringExtensionMethods.hook_AllIndicesOf_string_char>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator RemoveRichTextTags
		{
			add
			{
				HookEndpointManager.Modify<On.StringExtensionMethods.hook_RemoveRichTextTags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.StringExtensionMethods.hook_RemoveRichTextTags>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class StringUtils
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_EncodeStringListAsString(IReadOnlyList<string> stringsToEncode, bool encloseInQuotes);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_EncodeStringListAsString(orig_EncodeStringListAsString orig, IReadOnlyList<string> stringsToEncode, bool encloseInQuotes);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_EncodeDictionaryAsString(IDictionary<string, string> dictionaryToEncode, bool encloseInQuotes);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_EncodeDictionaryAsString(orig_EncodeDictionaryAsString orig, IDictionary<string, string> dictionaryToEncode, bool encloseInQuotes);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_EncodeKVPArrayAsString(IReadOnlyList<KeyValuePair<string, string>> keyValuePairsToEncode, bool encloseInQuotes);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_EncodeKVPArrayAsString(orig_EncodeKVPArrayAsString orig, IReadOnlyList<KeyValuePair<string, string>> keyValuePairsToEncode, bool encloseInQuotes);

		public static event hook_EncodeStringListAsString EncodeStringListAsString
		{
			add
			{
				HookEndpointManager.Add<hook_EncodeStringListAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EncodeStringListAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_EncodeDictionaryAsString EncodeDictionaryAsString
		{
			add
			{
				HookEndpointManager.Add<hook_EncodeDictionaryAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EncodeDictionaryAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_EncodeKVPArrayAsString EncodeKVPArrayAsString
		{
			add
			{
				HookEndpointManager.Add<hook_EncodeKVPArrayAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_EncodeKVPArrayAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class StringUtils
	{
		public static event Manipulator EncodeStringListAsString
		{
			add
			{
				HookEndpointManager.Modify<On.StringUtils.hook_EncodeStringListAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.StringUtils.hook_EncodeStringListAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator EncodeDictionaryAsString
		{
			add
			{
				HookEndpointManager.Modify<On.StringUtils.hook_EncodeDictionaryAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.StringUtils.hook_EncodeDictionaryAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator EncodeKVPArrayAsString
		{
			add
			{
				HookEndpointManager.Modify<On.StringUtils.hook_EncodeKVPArrayAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.StringUtils.hook_EncodeKVPArrayAsString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class SyncedList
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(SyncedList self, string fileName, string defaultFileComment);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, SyncedList self, string fileName, string defaultFileComment);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<string> orig_GetList(SyncedList self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<string> hook_GetList(orig_GetList orig, SyncedList self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_Count(SyncedList self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_Count(orig_Count orig, SyncedList self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Contains(SyncedList self, string s);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Contains(orig_Contains orig, SyncedList self, string s);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Add(SyncedList self, string s);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Add(orig_Add orig, SyncedList self, string s);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Remove(SyncedList self, string s);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Remove(orig_Remove orig, SyncedList self, string s);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Save(SyncedList self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Save(orig_Save orig, SyncedList self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CheckLoad(SyncedList self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CheckLoad(orig_CheckLoad orig, SyncedList self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Load(SyncedList self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Load(orig_Load orig, SyncedList self);

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetList GetList
		{
			add
			{
				HookEndpointManager.Add<hook_GetList>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetList>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Count Count
		{
			add
			{
				HookEndpointManager.Add<hook_Count>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Count>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Contains Contains
		{
			add
			{
				HookEndpointManager.Add<hook_Contains>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Contains>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Add Add
		{
			add
			{
				HookEndpointManager.Add<hook_Add>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Add>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Remove Remove
		{
			add
			{
				HookEndpointManager.Add<hook_Remove>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Remove>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Save Save
		{
			add
			{
				HookEndpointManager.Add<hook_Save>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Save>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CheckLoad CheckLoad
		{
			add
			{
				HookEndpointManager.Add<hook_CheckLoad>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CheckLoad>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Load Load
		{
			add
			{
				HookEndpointManager.Add<hook_Load>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Load>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class SyncedList
	{
		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.SyncedList.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SyncedList.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetList
		{
			add
			{
				HookEndpointManager.Modify<On.SyncedList.hook_GetList>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SyncedList.hook_GetList>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Count
		{
			add
			{
				HookEndpointManager.Modify<On.SyncedList.hook_Count>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SyncedList.hook_Count>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Contains
		{
			add
			{
				HookEndpointManager.Modify<On.SyncedList.hook_Contains>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SyncedList.hook_Contains>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Add
		{
			add
			{
				HookEndpointManager.Modify<On.SyncedList.hook_Add>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SyncedList.hook_Add>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Remove
		{
			add
			{
				HookEndpointManager.Modify<On.SyncedList.hook_Remove>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SyncedList.hook_Remove>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Save
		{
			add
			{
				HookEndpointManager.Modify<On.SyncedList.hook_Save>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SyncedList.hook_Save>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator CheckLoad
		{
			add
			{
				HookEndpointManager.Modify<On.SyncedList.hook_CheckLoad>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SyncedList.hook_CheckLoad>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator Load
		{
			add
			{
				HookEndpointManager.Modify<On.SyncedList.hook_Load>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.SyncedList.hook_Load>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class TriggerTracker
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnTriggerEnter(TriggerTracker self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnTriggerEnter(orig_OnTriggerEnter orig, TriggerTracker self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnTriggerExit(TriggerTracker self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnTriggerExit(orig_OnTriggerExit orig, TriggerTracker self, Collider other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsColliding(TriggerTracker self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsColliding(orig_IsColliding orig, TriggerTracker self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<Collider> orig_GetColliders(TriggerTracker self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<Collider> hook_GetColliders(orig_GetColliders orig, TriggerTracker self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(TriggerTracker self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, TriggerTracker self);

		public static event hook_OnTriggerEnter OnTriggerEnter
		{
			add
			{
				HookEndpointManager.Add<hook_OnTriggerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnTriggerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnTriggerExit OnTriggerExit
		{
			add
			{
				HookEndpointManager.Add<hook_OnTriggerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnTriggerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_IsColliding IsColliding
		{
			add
			{
				HookEndpointManager.Add<hook_IsColliding>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_IsColliding>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetColliders GetColliders
		{
			add
			{
				HookEndpointManager.Add<hook_GetColliders>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetColliders>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class TriggerTracker
	{
		public static event Manipulator OnTriggerEnter
		{
			add
			{
				HookEndpointManager.Modify<On.TriggerTracker.hook_OnTriggerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.TriggerTracker.hook_OnTriggerEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnTriggerExit
		{
			add
			{
				HookEndpointManager.Modify<On.TriggerTracker.hook_OnTriggerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.TriggerTracker.hook_OnTriggerExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator IsColliding
		{
			add
			{
				HookEndpointManager.Modify<On.TriggerTracker.hook_IsColliding>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.TriggerTracker.hook_IsColliding>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator GetColliders
		{
			add
			{
				HookEndpointManager.Modify<On.TriggerTracker.hook_GetColliders>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.TriggerTracker.hook_GetColliders>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.TriggerTracker.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.TriggerTracker.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class Vector2i
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor_Vector2(ref Vector2i self, Vector2 v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor_Vector2(orig_ctor_Vector2 orig, ref Vector2i self, Vector2 v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor_Vector3(ref Vector2i self, Vector3 v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor_Vector3(orig_ctor_Vector3 orig, ref Vector2i self, Vector3 v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor_Vector2i(ref Vector2i self, Vector2i v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor_Vector2i(orig_ctor_Vector2i orig, ref Vector2i self, Vector2i v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor_int_int(ref Vector2i self, int _x, int _y);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor_int_int(orig_ctor_int_int orig, ref Vector2i self, int _x, int _y);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_Magnitude(ref Vector2i self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_Magnitude(orig_Magnitude orig, ref Vector2i self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_Distance(Vector2i a, Vector2i b);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_Distance(orig_Distance orig, Vector2i a, Vector2i b);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector2 orig_ToVector2(ref Vector2i self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector2 hook_ToVector2(orig_ToVector2 orig, ref Vector2i self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_ToString(ref Vector2i self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_ToString(orig_ToString orig, ref Vector2i self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetHashCode(ref Vector2i self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetHashCode(orig_GetHashCode orig, ref Vector2i self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_Equals(ref Vector2i self, Vector2i other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_Equals(orig_Equals orig, ref Vector2i self, Vector2i other);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_ctor_Vector2 ctor_Vector2
		{
			add
			{
				HookEndpointManager.Add<hook_ctor_Vector2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor_Vector2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor_Vector3 ctor_Vector3
		{
			add
			{
				HookEndpointManager.Add<hook_ctor_Vector3>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor_Vector3>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor_Vector2i ctor_Vector2i
		{
			add
			{
				HookEndpointManager.Add<hook_ctor_Vector2i>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor_Vector2i>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor_int_int ctor_int_int
		{
			add
			{
				HookEndpointManager.Add<hook_ctor_int_int>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor_int_int>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Magnitude Magnitude
		{
			add
			{
				HookEndpointManager.Add<hook_Magnitude>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Magnitude>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Distance Distance
		{
			add
			{
				HookEndpointManager.Add<hook_Distance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Distance>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ToVector2 ToVector2
		{
			add
			{
				HookEndpointManager.Add<hook_ToVector2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ToVector2>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public new static event hook_ToString ToString
		{
			add
			{
				HookEndpointManager.Add<hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ToString>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value

BepInEx/plugins/MMHOOK/MMHOOK_assembly_valheim.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Fishlabs;
using Fishlabs.Core.Data;
using Fishlabs.UI;
using Fishlabs.Valheim;
using MonoMod.Cil;
using MonoMod.RuntimeDetour.HookGen;
using On;
using On.Fishlabs;
using On.Fishlabs.UI;
using On.Fishlabs.Valheim;
using On.UserManagement;
using On.Valheim.Assets;
using On.Valheim.UI;
using PlayFab;
using PlayFab.ClientModels;
using PlayFab.MultiplayerModels;
using PlayFab.Party;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.EventSystems;
using UnityEngine.ParticleSystemJobs;
using UnityEngine.UI;
using Valheim.UI;

[assembly: AssemblyVersion("0.0.0.0")]
namespace On
{
	public static class AnimSetTrigger
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnStateEnter(AnimSetTrigger self, Animator animator, AnimatorStateInfo stateInfo, int layerIndex);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnStateEnter(orig_OnStateEnter orig, AnimSetTrigger self, Animator animator, AnimatorStateInfo stateInfo, int layerIndex);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnStateExit(AnimSetTrigger self, Animator animator, AnimatorStateInfo stateInfo, int layerIndex);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnStateExit(orig_OnStateExit orig, AnimSetTrigger self, Animator animator, AnimatorStateInfo stateInfo, int layerIndex);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(AnimSetTrigger self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, AnimSetTrigger self);

		public static event hook_OnStateEnter OnStateEnter
		{
			add
			{
				HookEndpointManager.Add<hook_OnStateEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnStateEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnStateExit OnStateExit
		{
			add
			{
				HookEndpointManager.Add<hook_OnStateExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnStateExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ctor ctor
		{
			add
			{
				HookEndpointManager.Add<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}
	}
}
namespace IL
{
	public static class AnimSetTrigger
	{
		public static event Manipulator OnStateEnter
		{
			add
			{
				HookEndpointManager.Modify<On.AnimSetTrigger.hook_OnStateEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimSetTrigger.hook_OnStateEnter>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator OnStateExit
		{
			add
			{
				HookEndpointManager.Modify<On.AnimSetTrigger.hook_OnStateExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimSetTrigger.hook_OnStateExit>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}

		public static event Manipulator ctor
		{
			add
			{
				HookEndpointManager.Modify<On.AnimSetTrigger.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
			remove
			{
				HookEndpointManager.Unmodify<On.AnimSetTrigger.hook_ctor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)(object)value);
			}
		}
	}
}
namespace On
{
	public static class Character
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Awake(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Awake(orig_Awake orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnEnable(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnEnable(orig_OnEnable orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDisable(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDisable(orig_OnDisable orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetupMaxHealth(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetupMaxHealth(orig_SetupMaxHealth orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Start(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Start(orig_Start orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDestroy(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDestroy(orig_OnDestroy orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetLevel(Character self, int level);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetLevel(orig_SetLevel orig, Character self, int level);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetLevel(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetLevel(orig_GetLevel orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsPlayer(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsPlayer(orig_IsPlayer orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Faction orig_GetFaction(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Faction hook_GetFaction(orig_GetFaction orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetGroup(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetGroup(orig_GetGroup orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CustomFixedUpdate(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CustomFixedUpdate(orig_CustomFixedUpdate orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateLayer(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateLayer(orig_UpdateLayer orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UnderWorldCheck(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UnderWorldCheck(orig_UnderWorldCheck orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateSmoke(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateSmoke(orig_UpdateSmoke orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateContinousEffects(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateContinousEffects(orig_UpdateContinousEffects orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetupContinuousEffect(Character self, Vector3 point, bool enabledEffect, EffectList effects, ref GameObject[] instances);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetupContinuousEffect(orig_SetupContinuousEffect orig, Character self, Vector3 point, bool enabledEffect, EffectList effects, ref GameObject[] instances);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnSwimming(Character self, Vector3 targetVel, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnSwimming(orig_OnSwimming orig, Character self, Vector3 targetVel, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnSneaking(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnSneaking(orig_OnSneaking orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnJump(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnJump(orig_OnJump orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_TakeInput(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_TakeInput(orig_TakeInput orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetSlideAngle(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetSlideAngle(orig_GetSlideAngle orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_HaveRider(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_HaveRider(orig_HaveRider orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ApplySlide(Character self, float dt, ref Vector3 currentVel, Vector3 bodyVel, bool running);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ApplySlide(orig_ApplySlide orig, Character self, float dt, ref Vector3 currentVel, Vector3 bodyVel, bool running);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateMotion(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateMotion(orig_UpdateMotion orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetTakeInputDelay(float delayInSeconds);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetTakeInputDelay(orig_SetTakeInputDelay orig, float delayInSeconds);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateDebugFly(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateDebugFly(orig_UpdateDebugFly orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateSwimming(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateSwimming(orig_UpdateSwimming orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateFlying(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateFlying(orig_UpdateFlying orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateWalking(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateWalking(orig_UpdateWalking orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsSneaking(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsSneaking(orig_IsSneaking orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetSlopeAngle(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetSlopeAngle(orig_GetSlopeAngle orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddPushbackForce(Character self, ref Vector3 velocity);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddPushbackForce(orig_AddPushbackForce orig, Character self, ref Vector3 velocity);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ApplyPushback_HitData(Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ApplyPushback_HitData(orig_ApplyPushback_HitData orig, Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ApplyPushback_Vector3_float(Character self, Vector3 dir, float pushForce);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ApplyPushback_Vector3_float(orig_ApplyPushback_Vector3_float orig, Character self, Vector3 dir, float pushForce);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdatePushback(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdatePushback(orig_UpdatePushback orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ApplyGroundForce(Character self, ref Vector3 vel, Vector3 targetVel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ApplyGroundForce(orig_ApplyGroundForce orig, Character self, ref Vector3 vel, Vector3 targetVel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_UpdateRotation(Character self, float turnSpeed, float dt, bool smooth);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_UpdateRotation(orig_UpdateRotation orig, Character self, float turnSpeed, float dt, bool smooth);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateGroundTilt(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateGroundTilt(orig_UpdateGroundTilt orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_GetGroundHeight(Character self, Vector3 p, out float height, out Vector3 normal);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_GetGroundHeight(orig_GetGroundHeight orig, Character self, Vector3 p, out float height, out Vector3 normal);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsWallRunning(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsWallRunning(orig_IsWallRunning orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsOnSnow(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsOnSnow(orig_IsOnSnow orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Heal(Character self, float hp, bool showText);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Heal(orig_Heal orig, Character self, float hp, bool showText);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RPC_Heal(Character self, long sender, float hp, bool showText);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RPC_Heal(orig_RPC_Heal orig, Character self, long sender, float hp, bool showText);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetTopPoint(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetTopPoint(orig_GetTopPoint orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetRadius(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetRadius(orig_GetRadius orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetHeight(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetHeight(orig_GetHeight orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetHeadPoint(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetHeadPoint(orig_GetHeadPoint orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetEyePoint(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetEyePoint(orig_GetEyePoint orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetCenterPoint(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetCenterPoint(orig_GetCenterPoint orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DestructibleType orig_GetDestructibleType(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DestructibleType hook_GetDestructibleType(orig_GetDestructibleType orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate short orig_FindWeakSpotIndex(Character self, Collider c);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate short hook_FindWeakSpotIndex(orig_FindWeakSpotIndex orig, Character self, Collider c);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate WeakSpot orig_GetWeakSpot(Character self, short index);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate WeakSpot hook_GetWeakSpot(orig_GetWeakSpot orig, Character self, short index);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Damage(Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Damage(orig_Damage orig, Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RPC_Damage(Character self, long sender, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RPC_Damage(orig_RPC_Damage orig, Character self, long sender, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DamageModifier orig_GetDamageModifier(Character self, DamageType damageType);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DamageModifier hook_GetDamageModifier(orig_GetDamageModifier orig, Character self, DamageType damageType);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DamageModifiers orig_GetDamageModifiers(Character self, WeakSpot weakspot);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate DamageModifiers hook_GetDamageModifiers(orig_GetDamageModifiers orig, Character self, WeakSpot weakspot);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ApplyDamage(Character self, HitData hit, bool showDamageText, bool triggerEffects, DamageModifier mod);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ApplyDamage(orig_ApplyDamage orig, Character self, HitData hit, bool showDamageText, bool triggerEffects, DamageModifier mod);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DoDamageCameraShake(Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DoDamageCameraShake(orig_DoDamageCameraShake orig, Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_DamageArmorDurability(Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_DamageArmorDurability(orig_DamageArmorDurability orig, Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddFireDamage(Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddFireDamage(orig_AddFireDamage orig, Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddSpiritDamage(Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddSpiritDamage(orig_AddSpiritDamage orig, Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddPoisonDamage(Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddPoisonDamage(orig_AddPoisonDamage orig, Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddFrostDamage(Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddFrostDamage(orig_AddFrostDamage orig, Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddLightningDamage(Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddLightningDamage(orig_AddLightningDamage orig, Character self, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddDPS(float damage, Character me);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddDPS(orig_AddDPS orig, float damage, Character me);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CalculateDPS(string name, List<KeyValuePair<float, float>> damages, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CalculateDPS(orig_CalculateDPS orig, string name, List<KeyValuePair<float, float>> damages, float damage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetStaggerPercentage(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetStaggerPercentage(orig_GetStaggerPercentage orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetStaggerTreshold(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetStaggerTreshold(orig_GetStaggerTreshold orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_AddStaggerDamage(Character self, float damage, Vector3 forceDirection);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_AddStaggerDamage(orig_AddStaggerDamage orig, Character self, float damage, Vector3 forceDirection);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateStagger(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateStagger(orig_UpdateStagger orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Stagger(Character self, Vector3 forceDirection);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Stagger(orig_Stagger orig, Character self, Vector3 forceDirection);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RPC_Stagger(Character self, long sender, Vector3 forceDirection);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RPC_Stagger(orig_RPC_Stagger orig, Character self, long sender, Vector3 forceDirection);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ApplyArmorDamageMods(Character self, ref DamageModifiers mods);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ApplyArmorDamageMods(orig_ApplyArmorDamageMods orig, Character self, ref DamageModifiers mods);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetBodyArmor(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetBodyArmor(orig_GetBodyArmor orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_BlockAttack(Character self, HitData hit, Character attacker);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_BlockAttack(orig_BlockAttack orig, Character self, HitData hit, Character attacker);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDamaged(Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDamaged(orig_OnDamaged orig, Character self, HitData hit);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnCollisionStay(Character self, Collision collision);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnCollisionStay(orig_OnCollisionStay orig, Character self, Collision collision);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateGroundContact(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateGroundContact(orig_UpdateGroundContact orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ResetGroundContact(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ResetGroundContact(orig_ResetGroundContact orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Ship orig_GetStandingOnShip(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Ship hook_GetStandingOnShip(orig_GetStandingOnShip orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsOnGround(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsOnGround(orig_IsOnGround orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_CheckDeath(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_CheckDeath(orig_CheckDeath orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnRagdollCreated(Character self, Ragdoll ragdoll);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnRagdollCreated(orig_OnRagdollCreated orig, Character self, Ragdoll ragdoll);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDeath(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDeath(orig_OnDeath orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetHealth(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetHealth(orig_GetHealth orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetHealth(Character self, float health);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetHealth(orig_SetHealth orig, Character self, float health);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UseHealth(Character self, float hp);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UseHealth(orig_UseHealth orig, Character self, float hp);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetHealthPercentage(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetHealthPercentage(orig_GetHealthPercentage orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsDead(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsDead(orig_IsDead orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetMaxHealth(Character self, float health);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetMaxHealth(orig_SetMaxHealth orig, Character self, float health);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetMaxHealth(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetMaxHealth(orig_GetMaxHealth orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetMaxHealthBase(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetMaxHealthBase(orig_GetMaxHealthBase orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetMaxStamina(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetMaxStamina(orig_GetMaxStamina orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetMaxEitr(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetMaxEitr(orig_GetMaxEitr orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetEitrPercentage(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetEitrPercentage(orig_GetEitrPercentage orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetStaminaPercentage(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetStaminaPercentage(orig_GetStaminaPercentage orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsBoss(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsBoss(orig_IsBoss orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetLookDir(Character self, Vector3 dir, float transitionTime);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetLookDir(orig_SetLookDir orig, Character self, Vector3 dir, float transitionTime);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateLookTransition(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateLookTransition(orig_UpdateLookTransition orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetLookDir(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetLookDir(orig_GetLookDir orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnAttackTrigger(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnAttackTrigger(orig_OnAttackTrigger orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnStopMoving(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnStopMoving(orig_OnStopMoving orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnWeaponTrailStart(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnWeaponTrailStart(orig_OnWeaponTrailStart orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetMoveDir(Character self, Vector3 dir);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetMoveDir(orig_SetMoveDir orig, Character self, Vector3 dir);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetRun(Character self, bool run);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetRun(orig_SetRun orig, Character self, bool run);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetWalk(Character self, bool walk);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetWalk(orig_SetWalk orig, Character self, bool walk);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_GetWalk(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_GetWalk(orig_GetWalk orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateEyeRotation(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateEyeRotation(orig_UpdateEyeRotation orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnAutoJump(Character self, Vector3 dir, float upVel, float forwardVel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnAutoJump(orig_OnAutoJump orig, Character self, Vector3 dir, float upVel, float forwardVel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Jump(Character self, bool force);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Jump(orig_Jump orig, Character self, bool force);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateBodyFriction(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateBodyFriction(orig_UpdateBodyFriction orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_StartAttack(Character self, Character target, bool charge);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_StartAttack(orig_StartAttack orig, Character self, Character target, bool charge);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetTimeSinceLastAttack(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetTimeSinceLastAttack(orig_GetTimeSinceLastAttack orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnNearFire(Character self, Vector3 point);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnNearFire(orig_OnNearFire orig, Character self, Vector3 point);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ZDOID orig_GetZDOID(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate ZDOID hook_GetZDOID(orig_GetZDOID orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsOwner(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsOwner(orig_IsOwner orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate long orig_GetOwner(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate long hook_GetOwner(orig_GetOwner orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_UseMeleeCamera(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_UseMeleeCamera(orig_UseMeleeCamera orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_AlwaysRotateCamera(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_AlwaysRotateCamera(orig_AlwaysRotateCamera orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetLiquidLevel(Character self, float level, LiquidType type, Component liquidObj);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetLiquidLevel(orig_SetLiquidLevel orig, Character self, float level, LiquidType type, Component liquidObj);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsPVPEnabled(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsPVPEnabled(orig_IsPVPEnabled orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InIntro(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InIntro(orig_InIntro orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InCutscene(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InCutscene(orig_InCutscene orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsCrouching(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsCrouching(orig_IsCrouching orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InBed(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InBed(orig_InBed orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsAttached(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsAttached(orig_IsAttached orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsAttachedToShip(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsAttachedToShip(orig_IsAttachedToShip orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsRiding(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsRiding(orig_IsRiding orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetCrouch(Character self, bool crouch);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetCrouch(orig_SetCrouch orig, Character self, bool crouch);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AttachStart(Character self, Transform attachPoint, GameObject colliderRoot, bool hideWeapons, bool isBed, bool onShip, string attachAnimation, Vector3 detachOffset, Transform cameraPos);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AttachStart(orig_AttachStart orig, Character self, Transform attachPoint, GameObject colliderRoot, bool hideWeapons, bool isBed, bool onShip, string attachAnimation, Vector3 detachOffset, Transform cameraPos);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AttachStop(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AttachStop(orig_AttachStop orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateWater(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateWater(orig_UpdateWater orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ApplyLiquidResistance(Character self, ref float speed);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ApplyLiquidResistance(orig_ApplyLiquidResistance orig, Character self, ref float speed);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsSwimming(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsSwimming(orig_IsSwimming orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InLiquidSwimDepth(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InLiquidSwimDepth(orig_InLiquidSwimDepth orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InLiquidSwimDepth_float(Character self, float depth);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InLiquidSwimDepth_float(orig_InLiquidSwimDepth_float orig, Character self, float depth);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InLiquidKneeDepth(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InLiquidKneeDepth(orig_InLiquidKneeDepth orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InLiquidKneeDepth_float(Character self, float depth);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InLiquidKneeDepth_float(orig_InLiquidKneeDepth_float orig, Character self, float depth);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InLiquidWetDepth(Character self, float depth);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InLiquidWetDepth(orig_InLiquidWetDepth orig, Character self, float depth);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_InLiquidDepth(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_InLiquidDepth(orig_InLiquidDepth orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetLiquidLevel(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetLiquidLevel(orig_GetLiquidLevel orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InLiquid(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InLiquid(orig_InLiquid orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InTar(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InTar(orig_InTar orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InWater(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InWater(orig_InWater orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CheckRun(Character self, Vector3 moveDir, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CheckRun(orig_CheckRun orig, Character self, Vector3 moveDir, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsRunning(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsRunning(orig_IsRunning orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsWalking(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsWalking(orig_IsWalking orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InPlaceMode(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InPlaceMode(orig_InPlaceMode orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddEitr(Character self, float v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddEitr(orig_AddEitr orig, Character self, float v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UseEitr(Character self, float eitr);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UseEitr(orig_UseEitr orig, Character self, float eitr);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_HaveEitr(Character self, float amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_HaveEitr(orig_HaveEitr orig, Character self, float amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_HaveStamina(Character self, float amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_HaveStamina(orig_HaveStamina orig, Character self, float amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_HaveHealth(Character self, float amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_HaveHealth(orig_HaveHealth orig, Character self, float amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddStamina(Character self, float v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddStamina(orig_AddStamina orig, Character self, float v);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UseStamina(Character self, float stamina, bool isHomeUsage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UseStamina(orig_UseStamina orig, Character self, float stamina, bool isHomeUsage);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetNextOrCurrentAnimHash(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetNextOrCurrentAnimHash(orig_GetNextOrCurrentAnimHash orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetCurrentAnimHash(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetCurrentAnimHash(orig_GetCurrentAnimHash orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_GetNextAnimHash(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_GetNextAnimHash(orig_GetNextAnimHash orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateCachedAnimHashes(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateCachedAnimHashes(orig_UpdateCachedAnimHashes orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsStaggering(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsStaggering(orig_IsStaggering orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CanMove(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CanMove(orig_CanMove orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsEncumbered(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsEncumbered(orig_IsEncumbered orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsTeleporting(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsTeleporting(orig_IsTeleporting orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_CanWallRun(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_CanWallRun(orig_CanWallRun orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ShowPickupMessage(Character self, ItemData item, int amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ShowPickupMessage(orig_ShowPickupMessage orig, Character self, ItemData item, int amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ShowRemovedMessage(Character self, ItemData item, int amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ShowRemovedMessage(orig_ShowRemovedMessage orig, Character self, ItemData item, int amount);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Message(Character self, MessageType type, string msg, int amount, Sprite icon);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Message(orig_Message orig, Character self, MessageType type, string msg, int amount, Sprite icon);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate CapsuleCollider orig_GetCollider(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate CapsuleCollider hook_GetCollider(orig_GetCollider orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetStealthFactor(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetStealthFactor(orig_GetStealthFactor orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateNoise(Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateNoise(orig_UpdateNoise orig, Character self, float dt);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddNoise(Character self, float range);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddNoise(orig_AddNoise orig, Character self, float range);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RPC_AddNoise(Character self, long sender, float range);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RPC_AddNoise(orig_RPC_AddNoise orig, Character self, long sender, float range);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetNoiseRange(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetNoiseRange(orig_GetNoiseRange orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InGodMode(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InGodMode(orig_InGodMode orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InGhostMode(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InGhostMode(orig_InGhostMode orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsDebugFlying(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsDebugFlying(orig_IsDebugFlying orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetHoverText(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetHoverText(orig_GetHoverText orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string orig_GetHoverName(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate string hook_GetHoverName(orig_GetHoverName orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsDrawingBow(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsDrawingBow(orig_IsDrawingBow orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InAttack(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InAttack(orig_InAttack orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_StopEmote(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_StopEmote(orig_StopEmote orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InMinorAction(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InMinorAction(orig_InMinorAction orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InMinorActionSlowdown(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InMinorActionSlowdown(orig_InMinorActionSlowdown orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InDodge(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InDodge(orig_InDodge orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsDodgeInvincible(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsDodgeInvincible(orig_IsDodgeInvincible orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InEmote(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InEmote(orig_InEmote orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsBlocking(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsBlocking(orig_IsBlocking orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsFlying(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsFlying(orig_IsFlying orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsKnockedBack(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsKnockedBack(orig_IsKnockedBack orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnDrawGizmosSelected(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnDrawGizmosSelected(orig_OnDrawGizmosSelected orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_TeleportTo(Character self, Vector3 pos, Quaternion rot, bool distantTeleport);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_TeleportTo(orig_TeleportTo orig, Character self, Vector3 pos, Quaternion rot, bool distantTeleport);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RPC_TeleportTo(Character self, long sender, Vector3 pos, Quaternion rot, bool distantTeleport);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RPC_TeleportTo(orig_RPC_TeleportTo orig, Character self, long sender, Vector3 pos, Quaternion rot, bool distantTeleport);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SyncVelocity(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SyncVelocity(orig_SyncVelocity orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetVelocity(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetVelocity(orig_GetVelocity orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_AddRootMotion(Character self, Vector3 vel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_AddRootMotion(orig_AddRootMotion orig, Character self, Vector3 vel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ApplyRootMotion(Character self, ref Vector3 vel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ApplyRootMotion(orig_ApplyRootMotion orig, Character self, ref Vector3 vel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_GetCharactersInRange(Vector3 point, float radius, List<Character> characters);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_GetCharactersInRange(orig_GetCharactersInRange orig, Vector3 point, float radius, List<Character> characters);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<Character> orig_GetAllCharacters();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate List<Character> hook_GetAllCharacters(orig_GetAllCharacters orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsCharacterInRange(Vector3 point, float range);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsCharacterInRange(orig_IsCharacterInRange orig, Vector3 point, float range);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_OnTargeted(Character self, bool sensed, bool alerted);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_OnTargeted(orig_OnTargeted orig, Character self, bool sensed, bool alerted);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate GameObject orig_GetVisual(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate GameObject hook_GetVisual(orig_GetVisual orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_UpdateLodgroup(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_UpdateLodgroup(orig_UpdateLodgroup orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsSitting(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsSitting(orig_IsSitting orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetEquipmentMovementModifier(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetEquipmentMovementModifier(orig_GetEquipmentMovementModifier orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetEquipmentBaseItemModifier(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetEquipmentBaseItemModifier(orig_GetEquipmentBaseItemModifier orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetJogSpeedFactor(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetJogSpeedFactor(orig_GetJogSpeedFactor orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetRunSpeedFactor(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetRunSpeedFactor(orig_GetRunSpeedFactor orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetAttackSpeedFactorMovement(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetAttackSpeedFactorMovement(orig_GetAttackSpeedFactorMovement orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetAttackSpeedFactorRotation(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetAttackSpeedFactorRotation(orig_GetAttackSpeedFactorRotation orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RaiseSkill(Character self, SkillType skill, float value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RaiseSkill(orig_RaiseSkill orig, Character self, SkillType skill, float value);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Skills orig_GetSkills(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Skills hook_GetSkills(orig_GetSkills orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetSkillLevel(Character self, SkillType skillType);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetSkillLevel(orig_GetSkillLevel orig, Character self, SkillType skillType);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetSkillFactor(Character self, SkillType skill);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetSkillFactor(orig_GetSkillFactor orig, Character self, SkillType skill);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetRandomSkillFactor(Character self, SkillType skill);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetRandomSkillFactor(orig_GetRandomSkillFactor orig, Character self, SkillType skill);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsMonsterFaction(Character self, float time);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsMonsterFaction(orig_IsMonsterFaction orig, Character self, float time);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Transform orig_GetTransform(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Transform hook_GetTransform(orig_GetTransform orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Collider orig_GetLastGroundCollider(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Collider hook_GetLastGroundCollider(orig_GetLastGroundCollider orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetLastGroundNormal(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetLastGroundNormal(orig_GetLastGroundNormal orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ResetCloth(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ResetCloth(orig_ResetCloth orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RPC_ResetCloth(Character self, long sender);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RPC_ResetCloth(orig_RPC_ResetCloth orig, Character self, long sender);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_GetRelativePosition(Character self, out ZDOID parent, out string attachJoint, out Vector3 relativePos, out Quaternion relativeRot, out Vector3 relativeVel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_GetRelativePosition(orig_GetRelativePosition orig, Character self, out ZDOID parent, out string attachJoint, out Vector3 relativePos, out Quaternion relativeRot, out Vector3 relativeVel);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Quaternion orig_GetLookYaw(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Quaternion hook_GetLookYaw(orig_GetLookYaw orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 orig_GetMoveDir(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate Vector3 hook_GetMoveDir(orig_GetMoveDir orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate BaseAI orig_GetBaseAI(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate BaseAI hook_GetBaseAI(orig_GetBaseAI orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float orig_GetMass(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate float hook_GetMass(orig_GetMass orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetVisible(Character self, bool visible);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetVisible(orig_SetVisible orig, Character self, bool visible);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetTamed(Character self, bool tamed);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetTamed(orig_SetTamed orig, Character self, bool tamed);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RPC_SetTamed(Character self, long sender, bool tamed);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RPC_SetTamed(orig_RPC_SetTamed orig, Character self, long sender, bool tamed);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsTamed_float(Character self, float time);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsTamed_float(orig_IsTamed_float orig, Character self, float time);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsTamed(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsTamed(orig_IsTamed orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SEMan orig_GetSEMan(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate SEMan hook_GetSEMan(orig_GetSEMan orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InInterior(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InInterior(orig_InInterior orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InInterior_Transform(Transform me);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InInterior_Transform(orig_InInterior_Transform orig, Transform me);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_InInterior_Vector3(Vector3 position);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_InInterior_Vector3(orig_InInterior_Vector3 orig, Vector3 position);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_SetDPSDebug(bool enabled);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_SetDPSDebug(orig_SetDPSDebug orig, bool enabled);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool orig_IsDPSDebugEnabled();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate bool hook_IsDPSDebugEnabled(orig_IsDPSDebugEnabled orig);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_TakeOff(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_TakeOff(orig_TakeOff orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_Land(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_Land(orig_Land orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_FreezeFrame(Character self, float duration);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_FreezeFrame(orig_FreezeFrame orig, Character self, float duration);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_RPC_FreezeFrame(Character self, long sender, float duration);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_RPC_FreezeFrame(orig_RPC_FreezeFrame orig, Character self, long sender, float duration);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_Increment(Character self, LiquidType type);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_Increment(orig_Increment orig, Character self, LiquidType type);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int orig_Decrement(Character self, LiquidType type);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate int hook_Decrement(orig_Decrement orig, Character self, LiquidType type);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_ctor(Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_ctor(orig_ctor orig, Character self);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void orig_cctor();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public delegate void hook_cctor(orig_cctor orig);

		public static event hook_Awake Awake
		{
			add
			{
				HookEndpointManager.Add<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Awake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnEnable OnEnable
		{
			add
			{
				HookEndpointManager.Add<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnEnable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDisable OnDisable
		{
			add
			{
				HookEndpointManager.Add<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDisable>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetupMaxHealth SetupMaxHealth
		{
			add
			{
				HookEndpointManager.Add<hook_SetupMaxHealth>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetupMaxHealth>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Start Start
		{
			add
			{
				HookEndpointManager.Add<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Start>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDestroy OnDestroy
		{
			add
			{
				HookEndpointManager.Add<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDestroy>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetLevel SetLevel
		{
			add
			{
				HookEndpointManager.Add<hook_SetLevel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetLevel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetLevel GetLevel
		{
			add
			{
				HookEndpointManager.Add<hook_GetLevel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetLevel>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_IsPlayer IsPlayer
		{
			add
			{
				HookEndpointManager.Add<hook_IsPlayer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_IsPlayer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetFaction GetFaction
		{
			add
			{
				HookEndpointManager.Add<hook_GetFaction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetFaction>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetGroup GetGroup
		{
			add
			{
				HookEndpointManager.Add<hook_GetGroup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetGroup>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CustomFixedUpdate CustomFixedUpdate
		{
			add
			{
				HookEndpointManager.Add<hook_CustomFixedUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CustomFixedUpdate>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateLayer UpdateLayer
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateLayer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateLayer>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UnderWorldCheck UnderWorldCheck
		{
			add
			{
				HookEndpointManager.Add<hook_UnderWorldCheck>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UnderWorldCheck>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateSmoke UpdateSmoke
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateSmoke>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateSmoke>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateContinousEffects UpdateContinousEffects
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateContinousEffects>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateContinousEffects>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetupContinuousEffect SetupContinuousEffect
		{
			add
			{
				HookEndpointManager.Add<hook_SetupContinuousEffect>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetupContinuousEffect>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnSwimming OnSwimming
		{
			add
			{
				HookEndpointManager.Add<hook_OnSwimming>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnSwimming>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnSneaking OnSneaking
		{
			add
			{
				HookEndpointManager.Add<hook_OnSneaking>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnSneaking>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnJump OnJump
		{
			add
			{
				HookEndpointManager.Add<hook_OnJump>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnJump>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_TakeInput TakeInput
		{
			add
			{
				HookEndpointManager.Add<hook_TakeInput>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_TakeInput>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetSlideAngle GetSlideAngle
		{
			add
			{
				HookEndpointManager.Add<hook_GetSlideAngle>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetSlideAngle>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_HaveRider HaveRider
		{
			add
			{
				HookEndpointManager.Add<hook_HaveRider>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_HaveRider>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ApplySlide ApplySlide
		{
			add
			{
				HookEndpointManager.Add<hook_ApplySlide>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ApplySlide>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateMotion UpdateMotion
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateMotion>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateMotion>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_SetTakeInputDelay SetTakeInputDelay
		{
			add
			{
				HookEndpointManager.Add<hook_SetTakeInputDelay>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_SetTakeInputDelay>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateDebugFly UpdateDebugFly
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateDebugFly>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateDebugFly>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateSwimming UpdateSwimming
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateSwimming>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateSwimming>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateFlying UpdateFlying
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateFlying>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateFlying>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateWalking UpdateWalking
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateWalking>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateWalking>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_IsSneaking IsSneaking
		{
			add
			{
				HookEndpointManager.Add<hook_IsSneaking>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_IsSneaking>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetSlopeAngle GetSlopeAngle
		{
			add
			{
				HookEndpointManager.Add<hook_GetSlopeAngle>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetSlopeAngle>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddPushbackForce AddPushbackForce
		{
			add
			{
				HookEndpointManager.Add<hook_AddPushbackForce>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddPushbackForce>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ApplyPushback_HitData ApplyPushback_HitData
		{
			add
			{
				HookEndpointManager.Add<hook_ApplyPushback_HitData>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ApplyPushback_HitData>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ApplyPushback_Vector3_float ApplyPushback_Vector3_float
		{
			add
			{
				HookEndpointManager.Add<hook_ApplyPushback_Vector3_float>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ApplyPushback_Vector3_float>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdatePushback UpdatePushback
		{
			add
			{
				HookEndpointManager.Add<hook_UpdatePushback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdatePushback>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ApplyGroundForce ApplyGroundForce
		{
			add
			{
				HookEndpointManager.Add<hook_ApplyGroundForce>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ApplyGroundForce>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateRotation UpdateRotation
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateRotation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateRotation>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateGroundTilt UpdateGroundTilt
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateGroundTilt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateGroundTilt>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetGroundHeight GetGroundHeight
		{
			add
			{
				HookEndpointManager.Add<hook_GetGroundHeight>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetGroundHeight>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_IsWallRunning IsWallRunning
		{
			add
			{
				HookEndpointManager.Add<hook_IsWallRunning>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_IsWallRunning>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_IsOnSnow IsOnSnow
		{
			add
			{
				HookEndpointManager.Add<hook_IsOnSnow>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_IsOnSnow>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Heal Heal
		{
			add
			{
				HookEndpointManager.Add<hook_Heal>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Heal>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RPC_Heal RPC_Heal
		{
			add
			{
				HookEndpointManager.Add<hook_RPC_Heal>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RPC_Heal>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetTopPoint GetTopPoint
		{
			add
			{
				HookEndpointManager.Add<hook_GetTopPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetTopPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetRadius GetRadius
		{
			add
			{
				HookEndpointManager.Add<hook_GetRadius>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetRadius>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetHeight GetHeight
		{
			add
			{
				HookEndpointManager.Add<hook_GetHeight>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetHeight>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetHeadPoint GetHeadPoint
		{
			add
			{
				HookEndpointManager.Add<hook_GetHeadPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetHeadPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetEyePoint GetEyePoint
		{
			add
			{
				HookEndpointManager.Add<hook_GetEyePoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetEyePoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetCenterPoint GetCenterPoint
		{
			add
			{
				HookEndpointManager.Add<hook_GetCenterPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetCenterPoint>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetDestructibleType GetDestructibleType
		{
			add
			{
				HookEndpointManager.Add<hook_GetDestructibleType>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetDestructibleType>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_FindWeakSpotIndex FindWeakSpotIndex
		{
			add
			{
				HookEndpointManager.Add<hook_FindWeakSpotIndex>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_FindWeakSpotIndex>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetWeakSpot GetWeakSpot
		{
			add
			{
				HookEndpointManager.Add<hook_GetWeakSpot>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetWeakSpot>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Damage Damage
		{
			add
			{
				HookEndpointManager.Add<hook_Damage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Damage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RPC_Damage RPC_Damage
		{
			add
			{
				HookEndpointManager.Add<hook_RPC_Damage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RPC_Damage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetDamageModifier GetDamageModifier
		{
			add
			{
				HookEndpointManager.Add<hook_GetDamageModifier>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetDamageModifier>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetDamageModifiers GetDamageModifiers
		{
			add
			{
				HookEndpointManager.Add<hook_GetDamageModifiers>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetDamageModifiers>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ApplyDamage ApplyDamage
		{
			add
			{
				HookEndpointManager.Add<hook_ApplyDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ApplyDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DoDamageCameraShake DoDamageCameraShake
		{
			add
			{
				HookEndpointManager.Add<hook_DoDamageCameraShake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DoDamageCameraShake>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_DamageArmorDurability DamageArmorDurability
		{
			add
			{
				HookEndpointManager.Add<hook_DamageArmorDurability>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_DamageArmorDurability>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddFireDamage AddFireDamage
		{
			add
			{
				HookEndpointManager.Add<hook_AddFireDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddFireDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddSpiritDamage AddSpiritDamage
		{
			add
			{
				HookEndpointManager.Add<hook_AddSpiritDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddSpiritDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddPoisonDamage AddPoisonDamage
		{
			add
			{
				HookEndpointManager.Add<hook_AddPoisonDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddPoisonDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddFrostDamage AddFrostDamage
		{
			add
			{
				HookEndpointManager.Add<hook_AddFrostDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddFrostDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddLightningDamage AddLightningDamage
		{
			add
			{
				HookEndpointManager.Add<hook_AddLightningDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddLightningDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddDPS AddDPS
		{
			add
			{
				HookEndpointManager.Add<hook_AddDPS>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddDPS>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_CalculateDPS CalculateDPS
		{
			add
			{
				HookEndpointManager.Add<hook_CalculateDPS>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_CalculateDPS>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetStaggerPercentage GetStaggerPercentage
		{
			add
			{
				HookEndpointManager.Add<hook_GetStaggerPercentage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetStaggerPercentage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetStaggerTreshold GetStaggerTreshold
		{
			add
			{
				HookEndpointManager.Add<hook_GetStaggerTreshold>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetStaggerTreshold>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_AddStaggerDamage AddStaggerDamage
		{
			add
			{
				HookEndpointManager.Add<hook_AddStaggerDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_AddStaggerDamage>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateStagger UpdateStagger
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateStagger>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateStagger>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_Stagger Stagger
		{
			add
			{
				HookEndpointManager.Add<hook_Stagger>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_Stagger>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_RPC_Stagger RPC_Stagger
		{
			add
			{
				HookEndpointManager.Add<hook_RPC_Stagger>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_RPC_Stagger>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ApplyArmorDamageMods ApplyArmorDamageMods
		{
			add
			{
				HookEndpointManager.Add<hook_ApplyArmorDamageMods>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ApplyArmorDamageMods>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_GetBodyArmor GetBodyArmor
		{
			add
			{
				HookEndpointManager.Add<hook_GetBodyArmor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_GetBodyArmor>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_BlockAttack BlockAttack
		{
			add
			{
				HookEndpointManager.Add<hook_BlockAttack>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_BlockAttack>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnDamaged OnDamaged
		{
			add
			{
				HookEndpointManager.Add<hook_OnDamaged>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnDamaged>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_OnCollisionStay OnCollisionStay
		{
			add
			{
				HookEndpointManager.Add<hook_OnCollisionStay>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_OnCollisionStay>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_UpdateGroundContact UpdateGroundContact
		{
			add
			{
				HookEndpointManager.Add<hook_UpdateGroundContact>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_UpdateGroundContact>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
		}

		public static event hook_ResetGroundContact ResetGroundContact
		{
			add
			{
				HookEndpointManager.Add<hook_ResetGroundContact>(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/), (Delegate)value);
			}
			remove
			{
				HookEndpointManager.Remove<hook_ResetGroundContact>(MethodBase.GetMethodFromHandle((RuntimeMethodHa

BepInEx/plugins/mods_from_nexus-CraftBuildSmeltCookFuelPullFromContainers/CraftFromContainers.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace CraftFromContainers;

[BepInPlugin("aedenthorn.CraftFromContainers", "Craft From Containers", "3.1.2")]
public class BepInExPlugin : BaseUnityPlugin
{
	public class ConnectionParams
	{
		public GameObject connection = null;

		public Vector3 stationPos;
	}

	[HarmonyPatch(typeof(FejdStartup), "Awake")]
	private static class FejdStartup_Awake_Patch
	{
		private static void Postfix(FejdStartup __instance)
		{
			if (modEnabled.Value)
			{
				CheckOdinsQOLConfig();
			}
		}
	}

	[HarmonyPatch(typeof(Container), "Awake")]
	private static class Container_Awake_Patch
	{
		private static void Postfix(Container __instance, ZNetView ___m_nview)
		{
			((MonoBehaviour)context).StartCoroutine(AddContainer(__instance, ___m_nview));
		}
	}

	[HarmonyPatch(typeof(Container), "OnDestroyed")]
	private static class Container_OnDestroyed_Patch
	{
		private static void Prefix(Container __instance)
		{
			containerList.Remove(__instance);
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "Update")]
	private static class InventoryGui_Update_Patch
	{
		private static void Prefix(InventoryGui __instance, Animator ___m_animator)
		{
			if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && wasAllowed != AllowByKey() && ___m_animator.GetBool("visible"))
			{
				AccessTools.Method(typeof(InventoryGui), "UpdateCraftingPanel", (Type[])null, (Type[])null).Invoke(__instance, new object[1] { false });
			}
		}
	}

	[HarmonyPatch(typeof(Fireplace), "Interact")]
	private static class Fireplace_Interact_Patch
	{
		private static bool Prefix(Fireplace __instance, Humanoid user, bool hold, ref bool __result, ZNetView ___m_nview)
		{
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			__result = true;
			bool flag = CheckKeyHeld(fillAllModKey.Value);
			Inventory inventory = user.GetInventory();
			if (!AllowByKey() || hold || inventory == null || (inventory.HaveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name) && !flag))
			{
				return true;
			}
			if (!___m_nview.HasOwner())
			{
				___m_nview.ClaimOwnership();
			}
			if (flag && inventory.HaveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name))
			{
				int num = (int)Mathf.Min(__instance.m_maxFuel - (float)Mathf.CeilToInt(___m_nview.GetZDO().GetFloat("fuel", 0f)), (float)inventory.CountItems(__instance.m_fuelItem.m_itemData.m_shared.m_name, -1));
				inventory.RemoveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, num, -1);
				typeof(Inventory).GetMethod("Changed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(inventory, new object[0]);
				for (int i = 0; i < num; i++)
				{
					___m_nview.InvokeRPC("AddFuel", new object[0]);
				}
				((Character)user).Message((MessageType)2, Localization.instance.Localize("$msg_fireadding", new string[1] { __instance.m_fuelItem.m_itemData.m_shared.m_name }), 0, (Sprite)null);
				__result = false;
			}
			if (!inventory.HaveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name) && (float)Mathf.CeilToInt(___m_nview.GetZDO().GetFloat("fuel", 0f)) < __instance.m_maxFuel)
			{
				List<Container> nearbyContainers = GetNearbyContainers(((Component)__instance).transform.position);
				foreach (Container item2 in nearbyContainers)
				{
					ItemData item = item2.GetInventory().GetItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, -1, false);
					if (item == null || !((float)Mathf.CeilToInt(___m_nview.GetZDO().GetFloat("fuel", 0f)) < __instance.m_maxFuel))
					{
						continue;
					}
					if (fuelDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item.m_dropPrefab).name))
					{
						Dbgl($"container at {((Component)item2).transform.position} has {item.m_stack} {((Object)item.m_dropPrefab).name} but it's forbidden by config");
						continue;
					}
					int num2 = ((!flag) ? 1 : ((int)Mathf.Min(__instance.m_maxFuel - (float)Mathf.CeilToInt(___m_nview.GetZDO().GetFloat("fuel", 0f)), (float)item.m_stack)));
					Dbgl($"container at {((Component)item2).transform.position} has {item.m_stack} {((Object)item.m_dropPrefab).name}, taking {num2}");
					item2.GetInventory().RemoveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, num2, -1);
					typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item2, new object[0]);
					if (__result)
					{
						((Character)user).Message((MessageType)2, Localization.instance.Localize("$msg_fireadding", new string[1] { __instance.m_fuelItem.m_itemData.m_shared.m_name }), 0, (Sprite)null);
					}
					for (int j = 0; j < num2; j++)
					{
						___m_nview.InvokeRPC("AddFuel", new object[0]);
					}
					__result = false;
					if (flag && !((float)Mathf.CeilToInt(___m_nview.GetZDO().GetFloat("fuel", 0f)) >= __instance.m_maxFuel))
					{
						continue;
					}
					return false;
				}
			}
			return __result;
		}
	}

	[HarmonyPatch(typeof(CookingStation), "OnAddFuelSwitch")]
	private static class CookingStation_OnAddFuelSwitch_Patch
	{
		private static bool Prefix(CookingStation __instance, ref bool __result, Humanoid user, ItemData item, ZNetView ___m_nview)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			Dbgl("looking for fuel");
			if (!modEnabled.Value || !AllowByKey() || item != null || (float)((object)__instance).GetType().GetMethod("GetFuel", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[0]) > (float)(__instance.m_maxFuel - 1) || user.GetInventory().HaveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name))
			{
				return true;
			}
			Dbgl("missing fuel in player inventory");
			List<Container> nearbyContainers = GetNearbyContainers(((Component)__instance).transform.position);
			foreach (Container item3 in nearbyContainers)
			{
				ItemData item2 = item3.GetInventory().GetItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, -1, false);
				if (item2 != null)
				{
					if (!fuelDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item2.m_dropPrefab).name))
					{
						Dbgl($"container at {((Component)item3).transform.position} has {item2.m_stack} {((Object)item2.m_dropPrefab).name}, taking one");
						item3.GetInventory().RemoveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, 1, -1);
						typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item3, new object[0]);
						((Character)user).Message((MessageType)2, "$msg_added " + __instance.m_fuelItem.m_itemData.m_shared.m_name, 0, (Sprite)null);
						___m_nview.InvokeRPC("AddFuel", Array.Empty<object>());
						__result = true;
						return false;
					}
					Dbgl($"container at {((Component)item3).transform.position} has {item2.m_stack} {((Object)item2.m_dropPrefab).name} but it's forbidden by config");
				}
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(CookingStation), "FindCookableItem")]
	private static class CookingStation_FindCookableItem_Patch
	{
		private static void Postfix(CookingStation __instance, ref ItemData __result)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			Dbgl("looking for cookable");
			if (!modEnabled.Value || !AllowByKey() || __result != null || (__instance.m_requireFire && !(bool)typeof(CookingStation).GetMethod("IsFireLit", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[0])) || (int)typeof(CookingStation).GetMethod("GetFreeSlot", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[0]) == -1)
			{
				return;
			}
			Dbgl("missing cookable in player inventory");
			List<Container> nearbyContainers = GetNearbyContainers(((Component)__instance).transform.position);
			foreach (ItemConversion item2 in __instance.m_conversion)
			{
				foreach (Container item3 in nearbyContainers)
				{
					ItemData item = item3.GetInventory().GetItem(item2.m_from.m_itemData.m_shared.m_name, -1, false);
					if (item != null)
					{
						if (!oreDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item.m_dropPrefab).name))
						{
							Dbgl($"container at {((Component)item3).transform.position} has {item.m_stack} {((Object)item.m_dropPrefab).name}, taking one");
							__result = item;
							item3.GetInventory().RemoveItem(item2.m_from.m_itemData.m_shared.m_name, 1, -1);
							typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item3, new object[0]);
							return;
						}
						Dbgl($"container at {((Component)item3).transform.position} has {item.m_stack} {((Object)item.m_dropPrefab).name} but it's forbidden by config");
					}
				}
			}
		}
	}

	[HarmonyPatch(typeof(Smelter), "UpdateHoverTexts")]
	private static class Smelter_UpdateHoverTexts_Patch
	{
		private static void Postfix(Smelter __instance)
		{
			if (!modEnabled.Value)
			{
				return;
			}
			string value = fillAllModKey.Value;
			if (value != null && value.Length > 0)
			{
				if (__instance.m_addOreSwitch?.m_hoverText != null)
				{
					Switch addOreSwitch = __instance.m_addOreSwitch;
					addOreSwitch.m_hoverText = addOreSwitch.m_hoverText + "\n[<color=yellow><b>" + fillAllModKey.Value + "+$KEY_Use</b></color>] " + __instance.m_addOreTooltip + " max";
				}
				if (__instance.m_addWoodSwitch?.m_hoverText != null)
				{
					Switch addWoodSwitch = __instance.m_addWoodSwitch;
					addWoodSwitch.m_hoverText = addWoodSwitch.m_hoverText + "\n[<color=yellow><b>" + fillAllModKey.Value + "+$KEY_Use</b></color>] $piece_smelter_add max";
				}
			}
		}
	}

	[HarmonyPatch(typeof(Smelter), "OnAddOre")]
	private static class Smelter_OnAddOre_Patch
	{
		private static bool Prefix(Smelter __instance, Humanoid user, ItemData item, ZNetView ___m_nview)
		{
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0427: Unknown result type (might be due to invalid IL or missing references)
			bool flag = CheckKeyHeld(fillAllModKey.Value);
			if (!modEnabled.Value || (!AllowByKey() && !flag) || item != null || Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>() >= __instance.m_maxOre)
			{
				return true;
			}
			Inventory inventory = user.GetInventory();
			foreach (ItemConversion item4 in __instance.m_conversion)
			{
				if (inventory.HaveItem(item4.m_from.m_itemData.m_shared.m_name) && !flag)
				{
					return true;
				}
			}
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			List<Container> nearbyContainers = GetNearbyContainers(((Component)__instance).transform.position);
			foreach (ItemConversion item5 in __instance.m_conversion)
			{
				if (Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>() >= __instance.m_maxOre || (dictionary.Any() && !flag))
				{
					break;
				}
				string name = item5.m_from.m_itemData.m_shared.m_name;
				if (flag && inventory.HaveItem(name))
				{
					ItemData item2 = inventory.GetItem(name, -1, false);
					if (oreDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item2.m_dropPrefab).name))
					{
						Dbgl($"player has {item2.m_stack} {((Object)item2.m_dropPrefab).name} but it's forbidden by config");
						continue;
					}
					int num = ((!flag) ? 1 : Mathf.Min(__instance.m_maxOre - Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>(), inventory.CountItems(name, -1)));
					if (!dictionary.ContainsKey(name))
					{
						dictionary[name] = 0;
					}
					dictionary[name] += num;
					inventory.RemoveItem(item5.m_from.m_itemData.m_shared.m_name, num, -1);
					for (int i = 0; i < num; i++)
					{
						___m_nview.InvokeRPC("AddOre", new object[1] { ((Object)item2.m_dropPrefab).name });
					}
					((Character)user).Message((MessageType)1, $"$msg_added {num} {name}", 0, (Sprite)null);
					if (Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>() >= __instance.m_maxOre)
					{
						break;
					}
				}
				foreach (Container item6 in nearbyContainers)
				{
					ItemData item3 = item6.GetInventory().GetItem(name, -1, false);
					if (item3 == null)
					{
						continue;
					}
					if (oreDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item3.m_dropPrefab).name))
					{
						Dbgl($"container at {((Component)item6).transform.position} has {item3.m_stack} {((Object)item3.m_dropPrefab).name} but it's forbidden by config");
						continue;
					}
					int num2 = ((!flag) ? 1 : Mathf.Min(__instance.m_maxOre - Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>(), item6.GetInventory().CountItems(name, -1)));
					if (!dictionary.ContainsKey(name))
					{
						dictionary[name] = 0;
					}
					dictionary[name] += num2;
					Dbgl($"container at {((Component)item6).transform.position} has {item3.m_stack} {((Object)item3.m_dropPrefab).name}, taking {num2}");
					item6.GetInventory().RemoveItem(name, num2, -1);
					typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item6, new object[0]);
					for (int j = 0; j < num2; j++)
					{
						___m_nview.InvokeRPC("AddOre", new object[1] { ((Object)item3.m_dropPrefab).name });
					}
					((Character)user).Message((MessageType)1, $"$msg_added {num2} {name}", 0, (Sprite)null);
					if (Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>() < __instance.m_maxOre && flag)
					{
						continue;
					}
					break;
				}
			}
			if (!dictionary.Any())
			{
				((Character)user).Message((MessageType)2, "$msg_noprocessableitems", 0, (Sprite)null);
			}
			else
			{
				List<string> list = new List<string>();
				foreach (KeyValuePair<string, int> item7 in dictionary)
				{
					list.Add($"$msg_added {item7.Value} {item7.Key}");
				}
				((Character)user).Message((MessageType)2, string.Join("\n", list), 0, (Sprite)null);
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(Smelter), "OnAddFuel")]
	private static class Smelter_OnAddFuel_Patch
	{
		private static bool Prefix(Smelter __instance, ref bool __result, ZNetView ___m_nview, Humanoid user, ItemData item)
		{
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			bool flag = CheckKeyHeld(fillAllModKey.Value);
			Inventory inventory = user.GetInventory();
			if (!modEnabled.Value || (!AllowByKey() && !flag) || item != null || inventory == null || (inventory.HaveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name) && !flag))
			{
				return true;
			}
			__result = true;
			int num = 0;
			if ((float)typeof(Smelter).GetMethod("GetFuel", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[0]) > (float)(__instance.m_maxFuel - 1))
			{
				((Character)user).Message((MessageType)2, "$msg_itsfull", 0, (Sprite)null);
				__result = false;
				return false;
			}
			if (flag && inventory.HaveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name))
			{
				int num2 = (int)Mathf.Min((float)__instance.m_maxFuel - (float)typeof(Smelter).GetMethod("GetFuel", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[0]), (float)inventory.CountItems(__instance.m_fuelItem.m_itemData.m_shared.m_name, -1));
				inventory.RemoveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, num2, -1);
				for (int i = 0; i < num2; i++)
				{
					___m_nview.InvokeRPC("AddFuel", new object[0]);
				}
				num += num2;
				((Character)user).Message((MessageType)1, Localization.instance.Localize("$msg_fireadding", new string[1] { __instance.m_fuelItem.m_itemData.m_shared.m_name }), 0, (Sprite)null);
				__result = false;
			}
			List<Container> nearbyContainers = GetNearbyContainers(((Component)__instance).transform.position);
			foreach (Container item3 in nearbyContainers)
			{
				ItemData item2 = item3.GetInventory().GetItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, -1, false);
				if (item2 == null)
				{
					continue;
				}
				if (fuelDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item2.m_dropPrefab).name))
				{
					Dbgl($"container at {((Component)item3).transform.position} has {item2.m_stack} {((Object)item2.m_dropPrefab).name} but it's forbidden by config");
					continue;
				}
				int num3 = ((!flag) ? 1 : ((int)Mathf.Min((float)__instance.m_maxFuel - (float)typeof(Smelter).GetMethod("GetFuel", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[0]), (float)item2.m_stack)));
				Dbgl($"container at {((Component)item3).transform.position} has {item2.m_stack} {((Object)item2.m_dropPrefab).name}, taking {num3}");
				item3.GetInventory().RemoveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, num3, -1);
				typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item3, new object[0]);
				for (int j = 0; j < num3; j++)
				{
					___m_nview.InvokeRPC("AddFuel", new object[0]);
				}
				num += num3;
				((Character)user).Message((MessageType)1, "$msg_added " + __instance.m_fuelItem.m_itemData.m_shared.m_name, 0, (Sprite)null);
				__result = false;
				if (flag && Mathf.CeilToInt(___m_nview.GetZDO().GetFloat("fuel", 0f)) < __instance.m_maxFuel)
				{
					continue;
				}
				return false;
			}
			if (num == 0)
			{
				((Character)user).Message((MessageType)2, "$msg_noprocessableitems", 0, (Sprite)null);
			}
			else
			{
				((Character)user).Message((MessageType)2, $"$msg_added {num} {__instance.m_fuelItem.m_itemData.m_shared.m_name}", 0, (Sprite)null);
			}
			return __result;
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
	private static class InventoryGui_SetupRequirement_Patch
	{
		private static void Postfix(InventoryGui __instance, Transform elementRoot, Requirement req, Player player, bool craft, int quality)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			if (!modEnabled.Value || !AllowByKey() || !((Object)(object)req.m_resItem != (Object)null))
			{
				return;
			}
			int num = ((Humanoid)player).GetInventory().CountItems(req.m_resItem.m_itemData.m_shared.m_name, -1);
			int amount = req.GetAmount(quality);
			if (amount <= 0)
			{
				return;
			}
			Text component = ((Component)((Component)elementRoot).transform.Find("res_amount")).GetComponent<Text>();
			if (num < amount)
			{
				foreach (Container nearbyContainer in GetNearbyContainers(((Component)Player.m_localPlayer).transform.position))
				{
					num += nearbyContainer.GetInventory().CountItems(req.m_resItem.m_itemData.m_shared.m_name, -1);
				}
				if (num >= amount)
				{
					((Graphic)component).color = ((Mathf.Sin(Time.time * 10f) > 0f) ? flashColor.Value : unFlashColor.Value);
				}
			}
			if (resourceString.Value.Trim().Length > 0)
			{
				component.text = string.Format(resourceString.Value, num, amount);
			}
			else
			{
				component.text = amount.ToString();
			}
			component.resizeTextForBestFit = true;
		}
	}

	private static class InventoryGui_UpdateRecipeList_Patch
	{
		private static void Postfix(InventoryGui __instance, List<GameObject> ___m_recipeList)
		{
			if (!modEnabled.Value || !AllowByKey() || ___m_recipeList.Count == 0)
			{
				return;
			}
			foreach (GameObject ___m_recipe in ___m_recipeList)
			{
			}
		}
	}

	[HarmonyPatch(typeof(Player), "HaveRequirementItems", new Type[]
	{
		typeof(Recipe),
		typeof(bool),
		typeof(int)
	})]
	private static class HaveRequirementItems_Patch
	{
		private static void Postfix(Player __instance, ref bool __result, Recipe piece, bool discover, int qualityLevel, HashSet<string> ___m_knownMaterial)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if ((!modEnabled.Value | __result) || discover || !AllowByKey())
			{
				return;
			}
			List<Container> nearbyContainers = GetNearbyContainers(((Component)__instance).transform.position);
			Requirement[] resources = piece.m_resources;
			foreach (Requirement val in resources)
			{
				if (!Object.op_Implicit((Object)(object)val.m_resItem))
				{
					continue;
				}
				int amount = val.GetAmount(qualityLevel);
				int num = ((Humanoid)__instance).GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1);
				if (num >= amount)
				{
					continue;
				}
				foreach (Container item in nearbyContainers)
				{
					num += item.GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1);
				}
				if (num < amount)
				{
					return;
				}
			}
			__result = true;
		}
	}

	[HarmonyPatch(typeof(Player), "UpdateKnownRecipesList")]
	private static class UpdateKnownRecipesList_Patch
	{
		private static void Prefix()
		{
			skip = true;
		}

		private static void Postfix()
		{
			skip = false;
		}
	}

	[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
	{
		typeof(Piece),
		typeof(RequirementMode)
	})]
	private static class HaveRequirements_Patch
	{
		private static void Postfix(Player __instance, ref bool __result, Piece piece, RequirementMode mode, HashSet<string> ___m_knownMaterial, Dictionary<string, int> ___m_knownStations)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Invalid comparison between Unknown and I4
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Invalid comparison between Unknown and I4
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Invalid comparison between Unknown and I4
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Invalid comparison between Unknown and I4
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			if ((!modEnabled.Value | __result) || skip || __instance == null)
			{
				return;
			}
			Transform transform = ((Component)__instance).transform;
			if (!((transform != null) ? new Vector3?(transform.position) : null).HasValue || !AllowByKey())
			{
				return;
			}
			if (Object.op_Implicit((Object)(object)piece.m_craftingStation))
			{
				if ((int)mode == 1 || (int)mode == 2)
				{
					if (!___m_knownStations.ContainsKey(piece.m_craftingStation.m_name))
					{
						return;
					}
				}
				else if (!Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(piece.m_craftingStation.m_name, ((Component)__instance).transform.position)))
				{
					return;
				}
			}
			if (piece.m_dlc.Length > 0 && !DLCMan.instance.IsDLCInstalled(piece.m_dlc))
			{
				return;
			}
			List<Container> nearbyContainers = GetNearbyContainers(((Component)__instance).transform.position);
			Requirement[] resources = piece.m_resources;
			foreach (Requirement val in resources)
			{
				if (!Object.op_Implicit((Object)(object)val.m_resItem) || val.m_amount <= 0)
				{
					continue;
				}
				if ((int)mode == 1)
				{
					if (!___m_knownMaterial.Contains(val.m_resItem.m_itemData.m_shared.m_name))
					{
						return;
					}
				}
				else if ((int)mode == 2)
				{
					if (((Humanoid)__instance).GetInventory().HaveItem(val.m_resItem.m_itemData.m_shared.m_name))
					{
						continue;
					}
					bool flag = false;
					foreach (Container item in nearbyContainers)
					{
						if (item.GetInventory().HaveItem(val.m_resItem.m_itemData.m_shared.m_name))
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						return;
					}
				}
				else
				{
					if ((int)mode != 0 || ((Humanoid)__instance).GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1) >= val.m_amount)
					{
						continue;
					}
					int num = ((Humanoid)__instance).GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1);
					foreach (Container item2 in nearbyContainers)
					{
						try
						{
							num += item2.GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1);
							if (num >= val.m_amount)
							{
								break;
							}
						}
						catch
						{
						}
					}
					if (num < val.m_amount)
					{
						return;
					}
				}
			}
			__result = true;
		}
	}

	[HarmonyPatch(typeof(Player), "ConsumeResources")]
	private static class ConsumeResources_Patch
	{
		private static bool Prefix(Player __instance, Requirement[] requirements, int qualityLevel)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			if (!modEnabled.Value || !AllowByKey())
			{
				return true;
			}
			Inventory inventory = ((Humanoid)__instance).GetInventory();
			List<Container> nearbyContainers = GetNearbyContainers(((Component)__instance).transform.position);
			foreach (Requirement val in requirements)
			{
				if (!Object.op_Implicit((Object)(object)val.m_resItem))
				{
					continue;
				}
				int amount = val.GetAmount(qualityLevel);
				if (amount <= 0)
				{
					continue;
				}
				string name = val.m_resItem.m_itemData.m_shared.m_name;
				int num = inventory.CountItems(name, -1);
				Dbgl($"have {num}/{amount} {name} in player inventory");
				inventory.RemoveItem(name, Math.Min(num, amount), -1);
				if (num >= amount)
				{
					continue;
				}
				foreach (Container item2 in nearbyContainers)
				{
					Inventory inventory2 = item2.GetInventory();
					int num2 = Mathf.Min(inventory2.CountItems(name, -1), amount - num);
					Dbgl($"Container at {((Component)item2).transform.position} has {inventory2.CountItems(name, -1)}");
					if (num2 == 0)
					{
						continue;
					}
					for (int j = 0; j < inventory2.GetAllItems().Count; j++)
					{
						ItemData item = inventory2.GetItem(j);
						if (item.m_shared.m_name == name)
						{
							Dbgl($"Container has a total items count of {inventory2.GetAllItems().Count}");
							Dbgl($"Got stack of {item.m_stack} {name}");
							int num3 = Mathf.Min(item.m_stack, amount - num);
							if (num3 == item.m_stack)
							{
								inventory2.RemoveItem(j);
								j--;
							}
							else
							{
								item.m_stack -= num3;
							}
							num += num3;
							Dbgl($"total amount is now {num}/{amount} {name}");
							if (num >= amount)
							{
								Dbgl("Got enough, breaking");
								break;
							}
						}
					}
					Dbgl("Saving container");
					typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item2, new object[0]);
					Dbgl("Setting inventory changed");
					typeof(Inventory).GetMethod("Changed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(inventory2, new object[0]);
					if (num < amount)
					{
						continue;
					}
					Dbgl("consumed enough " + name);
					break;
				}
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
	private static class UpdatePlacementGhost_Patch
	{
		private static void Postfix(Player __instance, bool flashGuardStone)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			if (!modEnabled.Value || !showGhostConnections.Value)
			{
				return;
			}
			FieldInfo field = typeof(Player).GetField("m_placementGhost", BindingFlags.Instance | BindingFlags.NonPublic);
			GameObject val = ((!(field != null)) ? ((GameObject)null) : ((GameObject)field.GetValue(__instance)));
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Container component = val.GetComponent<Container>();
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			FieldInfo field2 = typeof(CraftingStation).GetField("m_allStations", BindingFlags.Static | BindingFlags.NonPublic);
			List<CraftingStation> list = ((field2 != null) ? ((List<CraftingStation>)field2.GetValue(null)) : null);
			if ((Object)(object)connectionVfxPrefab == (Object)null)
			{
				GameObject[] array = Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[];
				foreach (GameObject val2 in array)
				{
					if (((Object)val2).name == "vfx_ExtensionConnection")
					{
						connectionVfxPrefab = val2;
						break;
					}
				}
			}
			if ((Object)(object)connectionVfxPrefab == (Object)null || list == null)
			{
				return;
			}
			bool flag = false;
			foreach (CraftingStation item in list)
			{
				int num = ConnectionExists(item);
				bool flag2 = num != -1;
				if (Vector3.Distance(((Component)item).transform.position, val.transform.position) < m_range.Value)
				{
					flag = true;
					Vector3 connectionEffectPoint = item.GetConnectionEffectPoint();
					Vector3 val3 = val.transform.position + Vector3.up * ghostConnectionStartOffset.Value;
					ConnectionParams connectionParams = null;
					if (!flag2)
					{
						connectionParams = new ConnectionParams();
						connectionParams.stationPos = item.GetConnectionEffectPoint();
						connectionParams.connection = Object.Instantiate<GameObject>(connectionVfxPrefab, connectionEffectPoint, Quaternion.identity);
					}
					else
					{
						connectionParams = containerConnections[num];
					}
					if ((Object)(object)connectionParams.connection != (Object)null)
					{
						Vector3 val4 = val3 - connectionEffectPoint;
						Quaternion rotation = Quaternion.LookRotation(((Vector3)(ref val4)).normalized);
						connectionParams.connection.transform.position = connectionEffectPoint;
						connectionParams.connection.transform.rotation = rotation;
						connectionParams.connection.transform.localScale = new Vector3(1f, 1f, ((Vector3)(ref val4)).magnitude);
					}
					if (!flag2)
					{
						containerConnections.Add(connectionParams);
					}
				}
				else if (flag2)
				{
					Object.Destroy((Object)(object)containerConnections[num].connection);
					containerConnections.RemoveAt(num);
				}
			}
			if (flag && (Object)(object)context != (Object)null)
			{
				((MonoBehaviour)context).CancelInvoke("StopConnectionEffects");
				((MonoBehaviour)context).Invoke("StopConnectionEffects", ghostConnectionRemovalDelay.Value);
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "OnCraftPressed")]
	private static class DoCrafting_Patch
	{
		private static bool Prefix(InventoryGui __instance, KeyValuePair<Recipe, ItemData> ___m_selectedRecipe, ItemData ___m_craftUpgradeItem)
		{
			if (!modEnabled.Value || !AllowByKey() || !CheckKeyHeld(pullItemsKey.Value) || (Object)(object)___m_selectedRecipe.Key == (Object)null)
			{
				return true;
			}
			int num = ((___m_craftUpgradeItem == null) ? 1 : (___m_craftUpgradeItem.m_quality + 1));
			if (num > ___m_selectedRecipe.Key.m_item.m_itemData.m_shared.m_maxQuality)
			{
				return true;
			}
			Dbgl("pulling resources to player inventory for crafting item " + ___m_selectedRecipe.Key.m_item.m_itemData.m_shared.m_name);
			PullResources(Player.m_localPlayer, ___m_selectedRecipe.Key.m_resources, num);
			return false;
		}
	}

	[HarmonyPatch(typeof(Player), "UpdatePlacement")]
	private static class UpdatePlacement_Patch
	{
		private static bool Prefix(Player __instance, bool takeInput, float dt, PieceTable ___m_buildPieces, GameObject ___m_placementGhost)
		{
			if (!modEnabled.Value || !AllowByKey() || !CheckKeyHeld(pullItemsKey.Value) || !((Character)__instance).InPlaceMode() || !takeInput || Hud.IsPieceSelectionVisible())
			{
				return true;
			}
			if (ZInput.GetButtonDown("Attack") || ZInput.GetButtonDown("JoyPlace"))
			{
				Piece selectedPiece = ___m_buildPieces.GetSelectedPiece();
				if ((Object)(object)selectedPiece != (Object)null)
				{
					if (selectedPiece.m_repairPiece)
					{
						return true;
					}
					if ((Object)(object)___m_placementGhost != (Object)null && (int)typeof(Player).GetField("m_placementStatus", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(__instance) == 0)
					{
						Dbgl("pulling resources to player inventory for piece " + ((Object)selectedPiece).name);
						PullResources(__instance, selectedPiece.m_resources, 0);
					}
				}
				return false;
			}
			return true;
		}
	}

	private static class HaveRequirements_Patch2_broken
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Expected O, but got Unknown
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected O, but got Unknown
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Expected O, but got Unknown
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Expected O, but got Unknown
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Expected O, but got Unknown
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			for (int i = 0; i < list.Count; i++)
			{
				CodeInstruction val = list[i];
				if (!(val.opcode == OpCodes.Callvirt))
				{
					continue;
				}
				string text = ((object)val).ToString();
				if (!text.Contains("IsDLCInstalled"))
				{
					continue;
				}
				int num = -1;
				for (int j = i + 1; j < i + 5; j++)
				{
					if (list[j].opcode == OpCodes.Ret)
					{
						num = j;
						break;
					}
				}
				if (num != -1)
				{
					int num2 = num + 1;
					List<Label> labels = list[num2].labels;
					list.RemoveRange(num2, list.Count - num2);
					CodeInstruction val2 = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
					val2.labels = labels;
					list.Add(val2);
					list.Add(new CodeInstruction(OpCodes.Ldarg_1, (object)null));
					list.Add(new CodeInstruction(OpCodes.Ldarg_2, (object)null));
					list.Add(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
					list.Add(new CodeInstruction(OpCodes.Ldfld, (object)AccessTools.Field(typeof(Humanoid), "m_inventory")));
					list.Add(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
					list.Add(new CodeInstruction(OpCodes.Ldfld, (object)AccessTools.Field(typeof(Player), "m_knownMaterial")));
					list.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(BepInExPlugin), "HaveRequiredItemCount", (Type[])null, (Type[])null)));
					list.Add(new CodeInstruction(OpCodes.Ret, (object)null));
					break;
				}
				Dbgl(">>> FAILED to find targeted code for HaveRequirements transpiler patch!!! Mod will not work!");
			}
			return list;
		}
	}

	[HarmonyPatch(typeof(Terminal), "InputText")]
	private static class InputText_Patch
	{
		private static bool Prefix(Terminal __instance)
		{
			if (!modEnabled.Value)
			{
				return true;
			}
			string text = __instance.m_input.text;
			if (text.ToLower().Equals("craftfromcontainers reset"))
			{
				((BaseUnityPlugin)context).Config.Reload();
				((BaseUnityPlugin)context).Config.Save();
				__instance.AddString(text);
				__instance.AddString("Craft From Containers config reloaded");
				return false;
			}
			return true;
		}
	}

	private static bool wasAllowed;

	private static List<ConnectionParams> containerConnections = new List<ConnectionParams>();

	private static GameObject connectionVfxPrefab = null;

	public static ConfigEntry<bool> showGhostConnections;

	public static ConfigEntry<float> ghostConnectionStartOffset;

	public static ConfigEntry<float> ghostConnectionRemovalDelay;

	public static ConfigEntry<float> m_range;

	public static ConfigEntry<Color> flashColor;

	public static ConfigEntry<Color> unFlashColor;

	public static ConfigEntry<string> resourceString;

	public static ConfigEntry<string> pulledMessage;

	public static ConfigEntry<string> fuelDisallowTypes;

	public static ConfigEntry<string> oreDisallowTypes;

	public static ConfigEntry<string> pullItemsKey;

	public static ConfigEntry<string> preventModKey;

	public static ConfigEntry<string> fillAllModKey;

	public static ConfigEntry<bool> switchPrevent;

	public static ConfigEntry<bool> ignoreShipContainers;

	public static ConfigEntry<bool> ignoreWagonContainers;

	public static ConfigEntry<bool> ignoreWoodChests;

	public static ConfigEntry<bool> ignorePrivateChests;

	public static ConfigEntry<bool> ignoreBlackMetalChests;

	public static ConfigEntry<bool> ignoreReinforcedChests;

	public static ConfigEntry<bool> modEnabled;

	public static ConfigEntry<bool> isDebug;

	public static ConfigEntry<int> nexusID;

	public static List<Container> containerList = new List<Container>();

	public static bool odinsQolInstalled;

	public static float itemStackSizeMultiplier;

	public static float itemWeightReduction;

	public static Vector3 lastPosition = Vector3.positiveInfinity;

	public static List<Container> cachedContainerList = new List<Container>();

	private static BepInExPlugin context = null;

	private static bool skip;

	public static void Dbgl(string str = "", bool pref = true)
	{
		if (isDebug.Value)
		{
			Debug.Log((object)((pref ? (typeof(BepInExPlugin).Namespace + " ") : "") + str));
		}
	}

	private void Awake()
	{
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		context = this;
		modEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable this mod");
		isDebug = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "IsDebug", true, "Show debug messages in log");
		nexusID = ((BaseUnityPlugin)this).Config.Bind<int>("General", "NexusID", 40, "Nexus mod ID for updates");
		m_range = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ContainerRange", 10f, "The maximum range from which to pull items from");
		resourceString = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ResourceCostString", "{0}/{1}", "String used to show required and available resources. {0} is replaced by how much is available, and {1} is replaced by how much is required. Set to nothing to leave it as default.");
		flashColor = ((BaseUnityPlugin)this).Config.Bind<Color>("General", "FlashColor", Color.yellow, "Resource amounts will flash to this colour when coming from containers");
		unFlashColor = ((BaseUnityPlugin)this).Config.Bind<Color>("General", "UnFlashColor", Color.white, "Resource amounts will flash from this colour when coming from containers (set both colors to the same color for no flashing)");
		pulledMessage = ((BaseUnityPlugin)this).Config.Bind<string>("General", "PulledMessage", "Pulled items to inventory", "Message to show after pulling items to player inventory");
		fuelDisallowTypes = ((BaseUnityPlugin)this).Config.Bind<string>("General", "FuelDisallowTypes", "RoundLog,FineWood", "Types of item to disallow as fuel (i.e. anything that is consumed), comma-separated.");
		oreDisallowTypes = ((BaseUnityPlugin)this).Config.Bind<string>("General", "OreDisallowTypes", "RoundLog,FineWood", "Types of item to disallow as ore (i.e. anything that is transformed), comma-separated).");
		showGhostConnections = ((BaseUnityPlugin)this).Config.Bind<bool>("Station Connections", "ShowConnections", false, "If true, will display connections to nearby workstations within range when building containers");
		ghostConnectionStartOffset = ((BaseUnityPlugin)this).Config.Bind<float>("Station Connections", "ConnectionStartOffset", 1.25f, "Height offset for the connection VFX start position");
		ghostConnectionRemovalDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Station Connections", "ConnectionRemoveDelay", 0.05f, "");
		switchPrevent = ((BaseUnityPlugin)this).Config.Bind<bool>("Hot Keys", "SwitchPrevent", false, "if true, holding down the PreventModKey modifier key will allow this mod's behaviour; if false, holding down the key will prevent it.");
		preventModKey = ((BaseUnityPlugin)this).Config.Bind<string>("Hot Keys", "PreventModKey", "left alt", "Modifier key to toggle fuel and ore filling behaviour when down. Use https://docs.unity3d.com/Manual/ConventionalGameInput.html");
		pullItemsKey = ((BaseUnityPlugin)this).Config.Bind<string>("Hot Keys", "PullItemsKey", "left ctrl", "Holding down this key while crafting or building will pull resources into your inventory instead of building. Use https://docs.unity3d.com/Manual/ConventionalGameInput.html");
		fillAllModKey = ((BaseUnityPlugin)this).Config.Bind<string>("Hot Keys", "FillAllModKey", "left shift", "Modifier key to pull all available fuel or ore when down. Use https://docs.unity3d.com/Manual/ConventionalGameInput.html");
		ignoreShipContainers = ((BaseUnityPlugin)this).Config.Bind<bool>("Container Types", "IgnoreShipContainers", false, "If true, will ignore this type of container.");
		ignoreWagonContainers = ((BaseUnityPlugin)this).Config.Bind<bool>("Container Types", "IgnoreWagonContainers", false, "If true, will ignore this type of container.");
		ignoreWoodChests = ((BaseUnityPlugin)this).Config.Bind<bool>("Container Types", "IgnoreWoodChests", false, "If true, will ignore this type of container.");
		ignorePrivateChests = ((BaseUnityPlugin)this).Config.Bind<bool>("Container Types", "IgnorePrivateChests", false, "If true, will ignore this type of container.");
		ignoreBlackMetalChests = ((BaseUnityPlugin)this).Config.Bind<bool>("Container Types", "IgnoreBlackMetalChests", false, "If true, will ignore this type of container.");
		ignoreReinforcedChests = ((BaseUnityPlugin)this).Config.Bind<bool>("Container Types", "IgnoreReinforcedChests", false, "If true, will ignore this type of container.");
		wasAllowed = !switchPrevent.Value;
		Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		Dbgl("Mod awake");
	}

	private void LateUpdate()
	{
		wasAllowed = AllowByKey();
		skip = false;
	}

	private static bool AllowByKey()
	{
		if (CheckKeyHeld(preventModKey.Value))
		{
			return switchPrevent.Value;
		}
		return !switchPrevent.Value;
	}

	private void OnDestroy()
	{
		StopConnectionEffects();
	}

	private static bool CheckKeyHeld(string value, bool req = true)
	{
		try
		{
			return Input.GetKey(value.ToLower());
		}
		catch
		{
			return !req;
		}
	}

	public static List<Container> GetNearbyContainers(Vector3 center)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		List<Container> list = new List<Container>();
		if (Player.m_localPlayer == null)
		{
			return list;
		}
		if (Vector3.Distance(center, lastPosition) < 0.5f)
		{
			return cachedContainerList;
		}
		MethodInfo methodInfo = AccessTools.Method(typeof(Container), "CheckAccess", (Type[])null, (Type[])null);
		foreach (Container container in containerList)
		{
			if ((Object)(object)container != (Object)null && (Object)(object)((Component)container).transform != (Object)null && (m_range.Value <= 0f || Vector3.Distance(center, ((Component)container).transform.position) < m_range.Value) && AllowContainerType(container) && (bool)methodInfo.Invoke(container, new object[1] { Player.m_localPlayer.GetPlayerID() }) && !container.IsInUse() && (Object)(object)((Component)container).GetComponentInParent<Piece>() != (Object)null && container.GetInventory() != null && (!container.m_checkGuardStone || PrivateArea.CheckAccess(((Component)container).transform.position, 0f, false, false)))
			{
				list.Add(container);
			}
		}
		Dbgl($"Got {list.Count} containers.");
		lastPosition = center;
		cachedContainerList = list;
		return list;
	}

	private static bool AllowContainerType(Container __instance)
	{
		Transform parent = ((Component)__instance).gameObject.transform.parent;
		Ship val = ((parent != null) ? ((Component)parent).GetComponent<Ship>() : null);
		return (!ignoreShipContainers.Value || val == null) && (!ignoreWagonContainers.Value || __instance.m_wagon == null) && (!ignoreWoodChests.Value || !((Object)__instance).name.StartsWith("piece_chest_wood(")) && (!ignorePrivateChests.Value || !((Object)__instance).name.StartsWith("piece_chest_private(")) && (!ignoreBlackMetalChests.Value || !((Object)__instance).name.StartsWith("piece_chest_blackmetal(")) && (!ignoreReinforcedChests.Value || !((Object)__instance).name.StartsWith("piece_chest("));
	}

	public static IEnumerator AddContainer(Container container, ZNetView nview)
	{
		yield return null;
		try
		{
			int num;
			if (container.GetInventory() != null)
			{
				if (((nview != null) ? nview.GetZDO() : null) != null)
				{
					num = ((((Object)container).name.StartsWith("piece_") || ((Object)container).name.StartsWith("Container") || nview.GetZDO().GetLong(StringExtensionMethods.GetStableHashCode("creator"), 0L) != 0) ? 1 : 0);
					goto IL_00ad;
				}
			}
			num = 0;
			goto IL_00ad;
			IL_00ad:
			if (num != 0)
			{
				Dbgl("Adding " + ((Object)container).name);
				containerList.Add(container);
			}
		}
		catch
		{
		}
	}

	public static int ConnectionExists(CraftingStation station)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		foreach (ConnectionParams containerConnection in containerConnections)
		{
			if (Vector3.Distance(containerConnection.stationPos, station.GetConnectionEffectPoint()) < 0.1f)
			{
				return containerConnections.IndexOf(containerConnection);
			}
		}
		return -1;
	}

	public void StopConnectionEffects()
	{
		if (containerConnections.Count > 0)
		{
			foreach (ConnectionParams containerConnection in containerConnections)
			{
				Object.Destroy((Object)(object)containerConnection.connection);
			}
		}
		containerConnections.Clear();
	}

	private static void PullResources(Player player, Requirement[] resources, int qualityLevel)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory();
		List<Container> nearbyContainers = GetNearbyContainers(((Component)Player.m_localPlayer).transform.position);
		foreach (Requirement val in resources)
		{
			if (Object.op_Implicit((Object)(object)val.m_resItem))
			{
				int amount = val.GetAmount(qualityLevel);
				if (amount <= 0)
				{
					continue;
				}
				string name = val.m_resItem.m_itemData.m_shared.m_name;
				int num = 0;
				foreach (Container item2 in nearbyContainers)
				{
					Inventory inventory2 = item2.GetInventory();
					int num2 = Mathf.Min(inventory2.CountItems(name, -1), amount - num);
					Dbgl($"Container at {((Component)item2).transform.position} has {inventory2.CountItems(name, -1)}");
					if (num2 == 0)
					{
						continue;
					}
					for (int j = 0; j < inventory2.GetAllItems().Count; j++)
					{
						ItemData item = inventory2.GetItem(j);
						if (!(item.m_shared.m_name == name))
						{
							continue;
						}
						Dbgl($"Got stack of {item.m_stack} {name}");
						int num3 = Mathf.Min(item.m_stack, amount - num);
						if (!inventory.HaveEmptySlot())
						{
							num3 = Math.Min(Traverse.Create((object)inventory).Method("FindFreeStackSpace", new object[1] { item.m_shared.m_name }).GetValue<int>(), num3);
						}
						Dbgl($"Sending {num3} {name} to player");
						ItemData val2 = item.Clone();
						val2.m_stack = num3;
						if (odinsQolInstalled)
						{
							if (itemStackSizeMultiplier > 0f)
							{
								val2.m_shared.m_weight = ApplyModifierValue(val2.m_shared.m_weight, itemWeightReduction);
								if (val2.m_shared.m_maxStackSize > 1 && itemStackSizeMultiplier >= 1f)
								{
									val2.m_shared.m_maxStackSize = (int)ApplyModifierValue(val.m_resItem.m_itemData.m_shared.m_maxStackSize, itemStackSizeMultiplier);
								}
							}
						}
						else
						{
							val2.m_shared.m_maxStackSize = val.m_resItem.m_itemData.m_shared.m_maxStackSize;
						}
						inventory.AddItem(val2);
						if (num3 == item.m_stack)
						{
							inventory2.RemoveItem(j);
						}
						else
						{
							item.m_stack -= num3;
						}
						num += num3;
						Dbgl($"total amount is now {num}/{amount} {name}");
						if (num >= amount)
						{
							break;
						}
					}
					((object)item2).GetType().GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item2, new object[0]);
					((object)inventory2).GetType().GetMethod("Changed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(inventory2, new object[0]);
					if (num < amount)
					{
						continue;
					}
					Dbgl("pulled enough " + name);
					break;
				}
			}
			string value = pulledMessage.Value;
			if (value != null && value.Length > 0)
			{
				((Character)player).Message((MessageType)2, pulledMessage.Value, 0, (Sprite)null);
			}
		}
	}

	public static bool HaveRequiredItemCount(Player player, Piece piece, RequirementMode mode, Inventory inventory, HashSet<string> knownMaterial)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected I4, but got Unknown
		List<Container> nearbyContainers = GetNearbyContainers(((Component)player).transform.position);
		Requirement[] resources = piece.m_resources;
		foreach (Requirement val in resources)
		{
			if (!Object.op_Implicit((Object)(object)val.m_resItem) || val.m_amount <= 0)
			{
				continue;
			}
			switch ((int)mode)
			{
			case 0:
			{
				int num = inventory.CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1);
				int num2 = num;
				if (num2 >= val.m_amount)
				{
					break;
				}
				bool flag2 = false;
				foreach (Container item in nearbyContainers)
				{
					try
					{
						num2 += item.GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1);
						if (num2 >= val.m_amount)
						{
							flag2 = true;
							break;
						}
					}
					catch
					{
					}
				}
				if (!flag2)
				{
					return false;
				}
				break;
			}
			case 1:
				if (!knownMaterial.Contains(val.m_resItem.m_itemData.m_shared.m_name))
				{
					return false;
				}
				break;
			case 2:
			{
				if (inventory.HaveItem(val.m_resItem.m_itemData.m_shared.m_name))
				{
					break;
				}
				bool flag = false;
				foreach (Container item2 in nearbyContainers)
				{
					if (item2.GetInventory().HaveItem(val.m_resItem.m_itemData.m_shared.m_name))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					return false;
				}
				break;
			}
			}
		}
		return true;
	}

	public static void CheckOdinsQOLConfig()
	{
		itemStackSizeMultiplier = 0f;
		itemWeightReduction = 0f;
		Dictionary<string, PluginInfo> pluginInfos = Chainloader.PluginInfos;
		foreach (PluginInfo value in pluginInfos.Values)
		{
			if (!(((value != null) ? value.Metadata.GUID : null) == "com.odinplusqol.mod"))
			{
				continue;
			}
			odinsQolInstalled = modEnabled.Value;
			Debug.Log((object)"Found OdinPlusQoL");
			foreach (ConfigDefinition key in value.Instance.Config.Keys)
			{
				if (key.Key == "Item Stack Increase")
				{
					itemStackSizeMultiplier = (float)value.Instance.Config[key].BoxedValue;
				}
				if (key.Key == "Item Weight Increase")
				{
					itemWeightReduction = (float)value.Instance.Config[key].BoxedValue;
				}
			}
		}
	}

	public static float ApplyModifierValue(float targetValue, float value)
	{
		if (value <= -100f)
		{
			value = -100f;
		}
		if (value >= 0f)
		{
			return targetValue + targetValue / 100f * value;
		}
		return targetValue - targetValue / 100f * (value * -1f);
	}
}

BepInEx/plugins/Mokutan-ValheimSimpleAutoSort/ValheimAutoSort.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ValheimAutoSort")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ValheimAutoSort")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("255b30dc-f8ee-4a36-bd87-b815b6255fe2")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ValheimAutoSort;

[BepInPlugin("ch.elusia.plugins.valheim.autosort", "Valheim Auto Sort", "1.0.7")]
public class ValheimAutoSort : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Container), "Awake")]
	private class Conatiner_Awake
	{
		private static void Postfix(Container __instance, ZNetView ___m_nview)
		{
			if (!isEnabled.Value)
			{
				return;
			}
			try
			{
				if (((__instance != null) ? __instance.GetInventory() : null) != null && (Object)(object)__instance.m_wagon == (Object)null && ((___m_nview != null) ? ___m_nview.GetZDO() : null) != null && (!__instance.m_name.StartsWith("Storage") || ___m_nview.GetZDO().GetLong(StringExtensionMethods.GetStableHashCode("creator"), 0L) != 0))
				{
					allContainers.Add(__instance);
				}
			}
			catch
			{
			}
		}
	}

	public static List<Container> allContainers = new List<Container>();

	public static HashSet<string> SortItems = new HashSet<string>();

	private static ValheimAutoSort _instance;

	public static ConfigEntry<bool> isEnabled;

	public static ConfigEntry<string> ItemsToSort;

	public static ConfigEntry<bool> OnlySortWhenOnlyItem;

	public static ConfigEntry<float> MaxDistanceofContainer;

	public static ConfigEntry<string> SortKey;

	public static ConfigEntry<bool> OnlySortOneItemPerClick;

	public static ConfigEntry<bool> isDebugging;

	private void Awake()
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Expected O, but got Unknown
		_instance = this;
		LoadConfig();
		if (isEnabled.Value)
		{
			Harmony val = new Harmony("ch.elusia.plugins.valheim.autosort");
			val.PatchAll();
		}
	}

	private void LoadConfig()
	{
		isEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "Enabled", true, "Is plugin enabled?");
		ItemsToSort = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "ItemsToSort", "Dandelion,Stone,Wood,DeerHide,GreydwarfEye,Resin,Raspberry,Blueberries,Cloudberry,Bloodbag,Entrails,Coal,RawMeat,BoneFragments,Carrot,Chain,Chitin,Crystal,DeerMeat,DragonTear,Feathers,WolfClaw,WolfHairBundle,Flax,Barley,BarleyFlour,Flint,FreezeGland,Guck,Honey,LeatherScraps,LinenThread,LoxMeat,LoxPelt,Mushroom,NeckTail,Needle,Obsidian,Ooze,FishRaw,JuteRed,Root,SerpentMeat,SurtlingCore,Tar,Thistle,TrollHide,Turnip,WolfFang,WolfMeat,WolfPelt,MushroomYellow,FineWood,RoundLog,ElderBark,Pukeberries", "List of items to sort if possible.");
		OnlySortWhenOnlyItem = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "OnlySortWhenOnlyItem", true, "Only sort items when it's the only type in container.");
		MaxDistanceofContainer = ((BaseUnityPlugin)this).Config.Bind<float>("Settings", "MaxDistanceofContainer", 10f, "Max distance of containers for sorting in.");
		SortKey = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "SortKey", "o", "Key to sort the listed items.");
		OnlySortOneItemPerClick = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "OnlySortOneItemPerClick", false, "Only sort one item (stack) per click.");
		isDebugging = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "Debugging", false, "Enable debug output");
		string[] array = ItemsToSort.Value.Split(new char[2] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
		foreach (string item in array)
		{
			SortItems.Add(item);
		}
	}

	public void Update()
	{
		if (!isEnabled.Value || !Input.GetKeyDown(SortKey.Value) || !((Object)(object)Player.m_localPlayer != (Object)null))
		{
			return;
		}
		Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory();
		if (((inventory != null) ? inventory.GetAllItems() : null) == null)
		{
			return;
		}
		Inventory inventory2 = ((Humanoid)Player.m_localPlayer).GetInventory();
		List<ItemData> list = inventory2.GetAllItems().ToList();
		foreach (ItemData item in list)
		{
			bool flag = false;
			if (SortItems.Contains(((Object)item.m_dropPrefab).name))
			{
				if (isDebugging.Value)
				{
					Debug.Log((object)("item: " + ((Object)item.m_dropPrefab).name + " Count: " + item.m_stack));
				}
				foreach (Container item2 in GetContainerInRange())
				{
					bool flag2 = true;
					bool flag3 = false;
					for (int i = 0; i < item2.GetInventory().NrOfItems(); i++)
					{
						if (((Object)item2.GetInventory().GetItem(i).m_dropPrefab).name == ((Object)item.m_dropPrefab).name)
						{
							flag3 = true;
						}
						else
						{
							flag2 = false;
						}
					}
					if (flag2 && flag3 && OnlySortWhenOnlyItem.Value)
					{
						ItemData val = item.Clone();
						if (isDebugging.Value)
						{
							Debug.Log((object)("container only contains item: " + ((Object)item.m_dropPrefab).name));
						}
						if (isDebugging.Value)
						{
							Debug.Log((object)("item stack size befor transfer: " + item.m_stack));
						}
						flag = true;
						if (MoveItems(item2, inventory2, item))
						{
							break;
						}
						if (isDebugging.Value)
						{
							Debug.Log((object)("item stack size after transfer: " + item.m_stack));
						}
					}
					else if (flag3 && !OnlySortWhenOnlyItem.Value)
					{
						if (isDebugging.Value)
						{
							Debug.Log((object)("container contains item: " + ((Object)item.m_dropPrefab).name));
						}
						if (isDebugging.Value)
						{
							Debug.Log((object)("item stack size befor transfer: " + item.m_stack));
						}
						flag = true;
						if (MoveItems(item2, inventory2, item))
						{
							break;
						}
						if (isDebugging.Value)
						{
							Debug.Log((object)("item stack size after transfer: " + item.m_stack));
						}
					}
				}
			}
			if (OnlySortOneItemPerClick.Value && flag)
			{
				break;
			}
		}
	}

	public List<Container> GetContainerInRange()
	{
		//IL_0078: 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)
		List<Container> list = new List<Container>();
		foreach (Container allContainer in allContainers)
		{
			if (isDebugging.Value && allContainer.IsInUse())
			{
				Debug.Log((object)("container in use: " + ((Object)allContainer).name));
			}
			if ((Object)(object)allContainer != (Object)null && (Object)(object)Player.m_localPlayer != (Object)null && !allContainer.IsInUse() && Vector3.Distance(((Component)Player.m_localPlayer).transform.position, ((Component)allContainer).transform.position) < MaxDistanceofContainer.Value)
			{
				Traverse val = Traverse.Create((object)allContainer);
				if (val.Method("CheckAccess", new object[1] { Player.m_localPlayer.GetPlayerID() }).GetValue<bool>())
				{
					list.Add(allContainer);
				}
				else if (isDebugging.Value)
				{
					Debug.Log((object)("no access to container: " + ((Object)allContainer).name));
				}
			}
		}
		return list;
	}

	private bool MoveItems(Container container, Inventory playerInventory, ItemData item)
	{
		bool result = false;
		if (container.GetInventory().AddItem(item))
		{
			playerInventory.RemoveItem(item);
			result = true;
		}
		Traverse val = Traverse.Create((object)container.GetInventory());
		val.Method("Changed", Array.Empty<object>());
		Traverse val2 = Traverse.Create((object)container.GetInventory());
		val2.Method("Changed", Array.Empty<object>());
		return result;
	}
}

BepInEx/plugins/mtnewton-BiggerPickupRadius/BiggerPickupRadius.dll

Decompiled 8 months ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BiggerPickupRadius")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BiggerPickupRadius")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5be87e6f-506b-4810-b0c5-c014204bfa0c")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace BiggerPickupRadius;

[BepInPlugin("net.mtnewton.biggerpickupradius", "BiggerPickupRadius", "1.1.3")]
[HarmonyPatch]
public class BiggerPickupRadiusPlugin : BaseUnityPlugin
{
	private const string GUID = "net.mtnewton.biggerpickupradius";

	private const string NAME = "BiggerPickupRadius";

	private const string VERSION = "1.1.3";

	private static ManualLogSource logger;

	private static ConfigEntry<uint> radius;

	private void Awake()
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		logger = ((BaseUnityPlugin)this).Logger;
		radius = ((BaseUnityPlugin)this).Config.Bind<uint>("BiggerPickupRadius", "Radius", 6u, "Player pickup radius. Game default is 2");
		new Harmony("net.mtnewton.biggerpickupradius").PatchAll();
		logger.LogInfo((object)"BiggerPickupRadius loaded.");
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(Player), "Awake")]
	private static void SetPickupRadius(Player __instance)
	{
		logger.LogInfo((object)__instance.m_autoPickupRange);
		__instance.m_autoPickupRange = radius.Value;
		logger.LogInfo((object)("Player pickup range set to " + radius.Value));
	}
}

BepInEx/plugins/mtnewton-ItemStacks/ItemStacks.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ItemStacks")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ItemStacks")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("b9020f6f-c5ea-4f1a-a114-ad1a1fe1f44c")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyVersion("1.0.0.0")]
internal sealed class ConfigurationManagerAttributes
{
	public bool? ShowRangeAsPercent;

	public Action<ConfigEntryBase> CustomDrawer;

	public bool? Browsable;

	public string Category;

	public object DefaultValue;

	public bool? HideDefaultButton;

	public bool? HideSettingName;

	public string Description;

	public string DispName;

	public int? Order;

	public bool? ReadOnly;

	public bool? IsAdvanced;

	public Func<object, string> ObjToStr;

	public Func<string, object> StrToObj;
}
namespace ItemStacks;

internal class ItemTracker
{
	public string ItemName { get; }

	public int OriginalStackSize { get; }

	public float OriginalWeight { get; }

	private ConfigEntry<int> ItemStackSizeConfig { get; }

	private ConfigEntry<float> ItemWeightConfig { get; }

	public ItemTracker(ItemDrop item)
	{
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_011b: Expected O, but got Unknown
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Expected O, but got Unknown
		ItemName = GetItemName(item);
		OriginalStackSize = item.m_itemData.m_shared.m_maxStackSize;
		OriginalWeight = item.m_itemData.m_shared.m_weight;
		if (item.m_itemData.m_shared.m_maxStackSize > 1)
		{
			ItemStackSizeConfig = ItemStacksPlugin.config.Bind<int>("ItemStacks.ItemStackSize", ItemName + "_stack_size", 0, new ConfigDescription("Set above 0 to use this value instead of the stack size multiplier\n" + $"Game default: {OriginalStackSize}", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = true
				}
			}));
		}
		ItemWeightConfig = ItemStacksPlugin.config.Bind<float>("ItemStacks.ItemWeight", ItemName + "_weight", 0f, new ConfigDescription("Set above 0 to use this value instead of the weight multiplier\n" + $"Game default: {OriginalWeight}", (AcceptableValueBase)null, new object[1]
		{
			new ConfigurationManagerAttributes
			{
				IsAdvanced = true
			}
		}));
	}

	public void SetStackSize(float multiplier, ItemDrop item)
	{
		int value = ItemStackSizeConfig.Value;
		int num = ((value > 0) ? value : Mathf.Clamp((int)Math.Round((float)OriginalStackSize * multiplier), 1, int.MaxValue));
		item.m_itemData.m_shared.m_maxStackSize = num;
		ItemStacksPlugin.logger.LogDebug((object)$"{ItemName} OriginalStackSize:{OriginalStackSize} SetTo:{num}");
	}

	public void SetWeight(float multiplier, ItemDrop item)
	{
		float value = ItemWeightConfig.Value;
		float num = ((value > 0f) ? value : Mathf.Clamp(OriginalWeight * multiplier, 0f, 2.1474836E+09f));
		item.m_itemData.m_shared.m_weight = num;
		ItemStacksPlugin.logger.LogDebug((object)$"{ItemName} OriginalWeight:{OriginalWeight} SetTo:{num}");
	}

	private string GetItemName(ItemDrop item)
	{
		if (item.m_itemData.m_shared.m_name.StartsWith("$item_"))
		{
			return item.m_itemData.m_shared.m_name.Substring(6, item.m_itemData.m_shared.m_name.Length - 6);
		}
		return null;
	}
}
[BepInPlugin("net.mtnewton.itemstacks", "ItemStacks", "1.2.0")]
[HarmonyPatch]
public class ItemStacksPlugin : BaseUnityPlugin
{
	public const string GUID = "net.mtnewton.itemstacks";

	public const string NAME = "ItemStacks";

	public const string VERSION = "1.2.0";

	public static ManualLogSource logger;

	public static ConfigFile config;

	private static ConfigEntry<bool> stackSizeEnabledConfig;

	private static ConfigEntry<float> stackSizeMultiplierConfig;

	private static ConfigEntry<bool> weightEnabledConfig;

	private static ConfigEntry<float> weightMultiplierConfig;

	private static readonly Dictionary<string, ItemTracker> itemTrackers = new Dictionary<string, ItemTracker>();

	private void Awake()
	{
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Expected O, but got Unknown
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Expected O, but got Unknown
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		logger = ((BaseUnityPlugin)this).Logger;
		config = ((BaseUnityPlugin)this).Config;
		stackSizeEnabledConfig = config.Bind<bool>("ItemStacks.ItemStackSize", "enabled", true, new ConfigDescription("Should item stack size be modified?", (AcceptableValueBase)null, new object[1]
		{
			new ConfigurationManagerAttributes
			{
				Order = 1
			}
		}));
		weightEnabledConfig = config.Bind<bool>("ItemStacks.ItemWeight", "enabled", true, new ConfigDescription("Should item weight be modified?", (AcceptableValueBase)null, new object[1]
		{
			new ConfigurationManagerAttributes
			{
				Order = 1
			}
		}));
		stackSizeMultiplierConfig = config.Bind<float>("ItemStacks.ItemMultipliers", "stack_size_multiplier", 10f, "Multiply the original item stack size by this value\nMinimum resulting stack size is 1\nOverwritten by individual item _stack_size values.");
		weightMultiplierConfig = config.Bind<float>("ItemStacks.ItemMultipliers", "weight_multiplier", 0.1f, "Multiply the original item weight by this value\nOverwritten by individual item _weight values.");
		new Harmony("net.mtnewton.itemstacks").PatchAll();
		logger.LogInfo((object)"ItemStacks loaded.");
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	private static void ModifyItemStackSizeAndWeight(ObjectDB __instance)
	{
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		bool value = stackSizeEnabledConfig.Value;
		float multiplier = Mathf.Clamp(stackSizeMultiplierConfig.Value, 0f, 2.1474836E+09f);
		bool value2 = weightEnabledConfig.Value;
		float multiplier2 = Mathf.Clamp(weightMultiplierConfig.Value, 0f, 2.1474836E+09f);
		if (!(value || value2))
		{
			return;
		}
		ItemType[] array = (ItemType[])Enum.GetValues(typeof(ItemType));
		foreach (ItemType val in array)
		{
			foreach (ItemDrop allItem in __instance.GetAllItems(val, ""))
			{
				if (allItem.m_itemData.m_shared.m_name.StartsWith("$item_"))
				{
					ItemTracker itemTracker = GetItemTracker(allItem);
					if (value && itemTracker.OriginalStackSize > 1)
					{
						itemTracker.SetStackSize(multiplier, allItem);
					}
					if (value2)
					{
						itemTracker.SetWeight(multiplier2, allItem);
					}
				}
			}
		}
	}

	private static ItemTracker GetItemTracker(ItemDrop item)
	{
		if (itemTrackers.TryGetValue(item.m_itemData.m_shared.m_name, out var value))
		{
			return value;
		}
		value = new ItemTracker(item);
		itemTrackers.Add(item.m_itemData.m_shared.m_name, value);
		return value;
	}
}

BepInEx/plugins/Nextek-SpeedyPaths/SpeedyPaths.dll

Decompiled 8 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using AuthoritativeConfig;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using SpeedyPaths.Properties;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("SpeedyPaths")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("SpeedyPaths")]
[assembly: AssemblyTitle("SpeedyPaths")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace AuthoritativeConfig
{
	public class Config
	{
		private static Config _instance;

		public Dictionary<string, ConfigBaseEntry> _configEntries;

		public BaseUnityPlugin _mod;

		private static ConfigEntry<bool> _ServerIsAuthoritative;

		private static bool _DefaultBindAuthority;

		public static ManualLogSource Logger;

		public static Config Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new Config();
				}
				return _instance;
			}
			set
			{
			}
		}

		public static ZNet ZNet => ZNet.instance;

		public static string GUID => Instance._mod.Info.Metadata.GUID;

		public static string RPC_SYNC_GUID => "AuthoritativeConfig_" + GUID;

		public void init(BaseUnityPlugin mod, bool defaultBindServerAuthority = false)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			_mod = mod;
			Logger = new ManualLogSource(RPC_SYNC_GUID);
			Logger.Sources.Add((ILogSource)(object)Logger);
			_configEntries = new Dictionary<string, ConfigBaseEntry>();
			_DefaultBindAuthority = defaultBindServerAuthority;
			_ServerIsAuthoritative = _mod.Config.Bind<bool>("ServerAuthoritativeConfig", "ServerIsAuthoritative", true, "<Server Only> Forces Clients to use Server defined configs.");
			Harmony.CreateAndPatchAll(typeof(Config), (string)null);
			Logger.LogInfo((object)"Initialized Server Authoritative Config Manager.");
		}

		[HarmonyPatch(typeof(Game), "Start")]
		[HarmonyPostfix]
		private static void RegisterSyncConfigRPC()
		{
			Logger.LogInfo((object)("Authoritative Config Registered -> " + RPC_SYNC_GUID));
			ZRoutedRpc.instance.Register<ZPackage>(RPC_SYNC_GUID, (Action<long, ZPackage>)RPC_SyncServerConfig);
			foreach (ConfigBaseEntry value in Instance._configEntries.Values)
			{
				value.ClearServerValue();
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPostfix]
		private static void RequestConfigFromServer()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			if (!ZNet.IsServer() && (int)ZNet.GetConnectionStatus() == 2)
			{
				long? num = AccessTools.Method(typeof(ZRoutedRpc), "GetServerPeerID", (Type[])null, (Type[])null).Invoke(ZRoutedRpc.instance, null) as long?;
				ZRoutedRpc.instance.InvokeRoutedRPC(num.Value, RPC_SYNC_GUID, new object[1] { (object)new ZPackage() });
				Logger.LogInfo((object)("Authoritative Config Registered -> " + RPC_SYNC_GUID));
				Debug.Log((object)(Instance._mod.Info.Metadata.Name + ": Authoritative Config Requested -> " + RPC_SYNC_GUID));
			}
			else if (!ZNet.IsServer())
			{
				Logger.LogWarning((object)"Failed to Request Configs. Bad Peer? Too Early?");
			}
		}

		public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null, bool? serverAuthoritative = null)
		{
			ConfigEntry<T> configEntry = new ConfigEntry<T>(_mod.Config.Bind<T>(section, key, defaultValue, configDescription), serverAuthoritative.HasValue ? serverAuthoritative.Value : _DefaultBindAuthority);
			_configEntries[((object)configEntry.BaseEntry.Definition).ToString()] = configEntry;
			return configEntry;
		}

		public ConfigEntry<T> Bind<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null, bool? serverAuthoritative = null)
		{
			ConfigEntry<T> configEntry = new ConfigEntry<T>(_mod.Config.Bind<T>(configDefinition, defaultValue, configDescription), serverAuthoritative.HasValue ? serverAuthoritative.Value : _DefaultBindAuthority);
			_configEntries[((object)configEntry.BaseEntry.Definition).ToString()] = configEntry;
			return configEntry;
		}

		public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, string description, bool? serverAuthoritative = null)
		{
			ConfigEntry<T> configEntry = new ConfigEntry<T>(_mod.Config.Bind<T>(section, key, defaultValue, description), serverAuthoritative.HasValue ? serverAuthoritative.Value : _DefaultBindAuthority);
			_configEntries[((object)configEntry.BaseEntry.Definition).ToString()] = configEntry;
			return configEntry;
		}

		public static void SendConfigToClient(long sender)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			if (!ZNet.IsServer())
			{
				return;
			}
			ZPackage val = new ZPackage();
			int num = 0;
			foreach (KeyValuePair<string, ConfigBaseEntry> configEntry in Instance._configEntries)
			{
				if (configEntry.Value.ServerAuthoritative)
				{
					val.Write(configEntry.Key);
					val.Write(configEntry.Value.BaseEntry.GetSerializedValue());
					num++;
					Logger.LogInfo((object)("Sending Config " + configEntry.Key + ": " + configEntry.Value.BaseEntry.GetSerializedValue()));
				}
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(sender, RPC_SYNC_GUID, new object[1] { val });
			Logger.LogInfo((object)$"Sent {num} config pairs to client {sender}");
		}

		public static void ReadConfigPkg(ZPackage pkg)
		{
			if (ZNet.IsServer())
			{
				return;
			}
			int num = 0;
			while (pkg.GetPos() != pkg.Size())
			{
				string text = pkg.ReadString();
				string text2 = pkg.ReadString();
				num++;
				if (Instance._configEntries.ContainsKey(text))
				{
					Instance._configEntries[text].SetSerializedValue(text2);
					Logger.LogInfo((object)("Applied Server Authoritative config pair => " + text + ": " + text2));
				}
				else
				{
					Logger.LogError((object)("Recieved config key we dont have locally. Possible Version Mismatch. " + text + ": " + text2));
				}
			}
			Logger.LogInfo((object)$"Applied {num} config pairs");
		}

		public static void RPC_SyncServerConfig(long sender, ZPackage pkg)
		{
			if (ZNet.IsServer() && _ServerIsAuthoritative.Value)
			{
				SendConfigToClient(sender);
			}
			else if (!ZNet.IsServer() && pkg != null && pkg.Size() > 0 && AccessTools.Method(typeof(ZRoutedRpc), "GetServerPeerID", (Type[])null, (Type[])null).Invoke(ZRoutedRpc.instance, null) as long? == sender)
			{
				ReadConfigPkg(pkg);
			}
		}
	}
	public class ConfigBaseEntry
	{
		protected object _serverValue;

		public ConfigEntryBase BaseEntry;

		public bool ServerAuthoritative;

		protected bool _didError;

		internal ConfigBaseEntry(ConfigEntryBase configEntry, bool serverAuthoritative)
		{
			BaseEntry = configEntry;
			ServerAuthoritative = serverAuthoritative;
		}

		public void SetSerializedValue(string value)
		{
			try
			{
				_serverValue = TomlTypeConverter.ConvertToValue(value, BaseEntry.SettingType);
				_didError = false;
			}
			catch (Exception ex)
			{
				Config.Logger.LogWarning((object)$"Config value of setting \"{BaseEntry.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
			}
		}

		public void ClearServerValue()
		{
			_serverValue = null;
			_didError = false;
		}
	}
	public class ConfigEntry<T> : ConfigBaseEntry
	{
		private ConfigEntry<T> _configEntry;

		public T ServerValue => (T)_serverValue;

		public T Value
		{
			get
			{
				if (ServerAuthoritative && !Config.ZNet.IsServer())
				{
					if (_serverValue != null)
					{
						return ServerValue;
					}
					if (!_didError)
					{
						Config.Logger.LogWarning((object)("No Recieved value for Server Authoritative Config. " + ((object)BaseEntry.Definition).ToString() + ". Falling Back to Client Config."));
						_didError = true;
					}
					return _configEntry.Value;
				}
				return _configEntry.Value;
			}
			set
			{
				_configEntry.Value = value;
			}
		}

		internal ConfigEntry(ConfigEntry<T> configEntry, bool serverAuthoritative)
			: base((ConfigEntryBase)(object)configEntry, serverAuthoritative)
		{
			_configEntry = configEntry;
		}
	}
}
namespace SpeedyPaths
{
	[BepInPlugin("nex.SpeedyPaths", "Speedy Paths Mod", "1.0.8")]
	public class SpeedyPathsClientMod : BaseUnityPlugin
	{
		public enum GroundType
		{
			Untamed,
			PathDirt,
			PathStone,
			Cultivated,
			StructureWood,
			StructureHardWood,
			StructureStone,
			StructureIron,
			StructureMarble
		}

		private static Dictionary<GroundType, ConfigEntry<float>> _speedModifiers = new Dictionary<GroundType, ConfigEntry<float>>();

		private static Dictionary<GroundType, ConfigEntry<float>> _staminaModifiers = new Dictionary<GroundType, ConfigEntry<float>>();

		private static Dictionary<Biome, ConfigEntry<float>> _untamedSpeedModifiers = new Dictionary<Biome, ConfigEntry<float>>();

		private static Dictionary<Biome, ConfigEntry<float>> _untamedStaminaModifiers = new Dictionary<Biome, ConfigEntry<float>>();

		private static ConfigEntry<bool> _showHudStatus;

		private static ConfigEntry<string> _hudStatusText;

		private static ConfigEntry<bool> _hudDynamicStatusText;

		private static ConfigEntry<bool> _hudShowEffectPercent;

		private static List<ConfigEntry<float>> _hudPosIconThresholds = new List<ConfigEntry<float>>();

		private static List<ConfigEntry<float>> _hudNegIconThresholds = new List<ConfigEntry<float>>();

		private static ConfigEntry<float> _groundSensorUpdateInterval;

		private static ConfigEntry<int> _groundSensorRadius;

		private static Dictionary<GroundType, ConfigEntry<string>> _groundTypeStrings = new Dictionary<GroundType, ConfigEntry<string>>();

		private static Dictionary<Biome, ConfigEntry<string>> _biomeTypeStrings = new Dictionary<Biome, ConfigEntry<string>>();

		private static int m_pieceLayer;

		private static object[] _worldToVertexArgs = new object[3]
		{
			Vector3.zero,
			null,
			null
		};

		private static List<Sprite> _speedSprites = new List<Sprite>();

		private AssetBundle _speedyassets;

		private static float m_sensorTime;

		private static GroundType m_cachedGroundType;

		public static ManualLogSource Logger;

		private static float _activeSpeedModifier = 1f;

		private static float _activeStaminaModifier = 1f;

		private static string _activeStatusText;

		private static Sprite _activeStatusSprite;

		private static StatusEffect _pathBuffSEDummy;

		private static float _prevModValue = 1f;

		public Config Config
		{
			get
			{
				return Config.Instance;
			}
			set
			{
			}
		}

		private void Awake()
		{
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_054e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0554: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0616: Unknown result type (might be due to invalid IL or missing references)
			Logger = ((BaseUnityPlugin)this).Logger;
			_speedyassets = AssetBundle.LoadFromMemory(Resources.speedyassets);
			if (!Object.op_Implicit((Object)(object)_speedyassets))
			{
				Logger.LogError((object)"Failed to read AssetBundle stream");
				return;
			}
			Config.init((BaseUnityPlugin)(object)this, defaultBindServerAuthority: true);
			_hudDynamicStatusText = Config.Bind("Hud", "EnableDynamicStatusText", defaultValue: true, "Show surface type text as status effect name", false);
			_hudShowEffectPercent = Config.Bind("Hud", "ShowStatusEffectPercent", defaultValue: true, "Show the status effect buff/debuff %", false);
			_showHudStatus = Config.Bind("Hud", "ShowStatusIcon", defaultValue: true, "Show the speedypaths status icon in the hud", false);
			_hudStatusText = Config.Bind("Hud", "StatusText", "Speedy Path", "Text shown above the status icon", false);
			_hudPosIconThresholds.Add(Config.Bind("Hud", "BuffIcon +1", 1f, "Speed buff threshold to show lvl 1 buff icon"));
			_hudPosIconThresholds.Add(Config.Bind("Hud", "BuffIcon +2", 1.39f, "Speed buff threshold to show lvl 2 buff icon"));
			_hudNegIconThresholds.Add(Config.Bind("Hud", "DebuffIcon -1", 1f, "Speed buff threshold to show lvl 1 debuff icon"));
			_hudNegIconThresholds.Add(Config.Bind("Hud", "DebuffIcon -2", 0.79f, "Speed buff threshold to show lvl 2 debuff icon"));
			_groundSensorUpdateInterval = Config.Bind("Performance", "Ground Sensor Interval", 1f, "Interval between in seconds between ground type checks. Lower number, more accute ground detection.", true);
			_groundSensorRadius = Config.Bind("Performance", "Ground Sensor Radius", 1, "Radius of ground pixels to sample when checking under the player", true);
			_speedModifiers[GroundType.PathDirt] = Config.Bind("SpeedModifiers", "DirtPathSpeed", 1.15f, "Modifier for speed while on dirt paths");
			_speedModifiers[GroundType.PathStone] = Config.Bind("SpeedModifiers", "StonePathSpeed", 1.4f, "Modifier for speed while on stone paths");
			_speedModifiers[GroundType.Cultivated] = Config.Bind("SpeedModifiers", "CultivatedSpeed", 1f, "Modifier for speed while on Cultivated land");
			_speedModifiers[GroundType.StructureWood] = Config.Bind("SpeedModifiers", "StructureWoodSpeed", 1.15f, "Modifier for speed while on wood structures");
			_speedModifiers[GroundType.StructureHardWood] = Config.Bind("SpeedModifiers", "StructureHardWoodSpeed", 1.15f, "Modifier for speed while on core wood structures");
			_speedModifiers[GroundType.StructureStone] = Config.Bind("SpeedModifiers", "StructureStoneSpeed", 1.4f, "Modifier for speed while on stone structures");
			_speedModifiers[GroundType.StructureIron] = Config.Bind("SpeedModifiers", "StructureIronSpeed", 1.4f, "Modifier for speed while on ironwood structures");
			_speedModifiers[GroundType.StructureMarble] = Config.Bind("SpeedModifiers", "StructureMarbleSpeed", 1.4f, "Modifier for speed while on black marble structures");
			_staminaModifiers[GroundType.PathDirt] = Config.Bind("StaminaModifiers", "DirtPathStamina", 0.8f, "Modifier for stamina while on dirt paths");
			_staminaModifiers[GroundType.PathStone] = Config.Bind("StaminaModifiers", "StonePathStamina", 0.7f, "Modifier for stamina while on stone paths");
			_staminaModifiers[GroundType.Cultivated] = Config.Bind("StaminaModifiers", "CultivatedStamina", 1f, "Modifier for stamina while on Cultivated land");
			_staminaModifiers[GroundType.StructureWood] = Config.Bind("StaminaModifiers", "StructureWoodStamina", 0.8f, "Modifier for stamina while on wood structures");
			_staminaModifiers[GroundType.StructureHardWood] = Config.Bind("StaminaModifiers", "StructureHardWoodStamina", 0.8f, "Modifier for stamina while on core wood structures");
			_staminaModifiers[GroundType.StructureStone] = Config.Bind("StaminaModifiers", "StructureStoneStamina", 0.7f, "Modifier for stamina while on stone structures");
			_staminaModifiers[GroundType.StructureIron] = Config.Bind("StaminaModifiers", "StructureIronStamina", 0.7f, "Modifier for stamina while on ironwood structures");
			_staminaModifiers[GroundType.StructureMarble] = Config.Bind("StaminaModifiers", "StructureMarbleStamina", 0.7f, "Modifier for stamina while on black marble  structures");
			foreach (Biome value in Enum.GetValues(typeof(Biome)))
			{
				Biome key = value;
				_untamedSpeedModifiers[key] = Config.Bind("SpeedModifiers_Biomes", "Untamed_" + ((object)(Biome)(ref key)).ToString() + "_Speed", 1f, "Speed modifier for uncleared ground in " + ((object)(Biome)(ref key)).ToString() + " Biomes");
				_untamedStaminaModifiers[key] = Config.Bind("StaminaModifiers_Biomes", "Untamed_" + ((object)(Biome)(ref key)).ToString() + "_Stamina", 1f, "Stamina modifier for uncleared ground in " + ((object)(Biome)(ref key)).ToString() + " Biomes");
				_biomeTypeStrings[key] = Config.Bind("Strings", "Biome_" + ((object)(Biome)(ref key)).ToString(), "default", "Dynamic status mapping for " + ((object)(Biome)(ref key)).ToString() + " groundcover. 'default' uses localized biome name.");
			}
			_groundTypeStrings[GroundType.PathDirt] = Config.Bind("Strings", "PathDirt", "Dirt Path", "Dynamic status mapping for dirt paths");
			_groundTypeStrings[GroundType.PathStone] = Config.Bind("Strings", "PathStone", "Stone Path", "Dynamic status mapping for  stone paths");
			_groundTypeStrings[GroundType.Cultivated] = Config.Bind("Strings", "Cultivated", "Cultivated", "Dynamic status mapping for Cultivated land");
			_groundTypeStrings[GroundType.StructureWood] = Config.Bind("Strings", "StructureWood", "Wood", "Dynamic status mapping for wood structures");
			_groundTypeStrings[GroundType.StructureHardWood] = Config.Bind("Strings", "StructureHardWood", "Hardwood", "Dynamic status mapping for core wood structures");
			_groundTypeStrings[GroundType.StructureStone] = Config.Bind("Strings", "StructureStone", "Stone", "MDynamic status mapping for stone structures");
			_groundTypeStrings[GroundType.StructureIron] = Config.Bind("Strings", "StructureIron", "Iron", "Dynamic status mapping for ironwood structures");
			_groundTypeStrings[GroundType.StructureMarble] = Config.Bind("Strings", "StructureMarble", "Marble", "Dynamic status mapping for black marble structures");
			if (m_pieceLayer == 0)
			{
				m_pieceLayer = LayerMask.NameToLayer("piece");
			}
			_speedSprites.Add(_speedyassets.LoadAsset<Sprite>("assets/nex.speedypaths/speedypaths_1.png"));
			_speedSprites.Add(_speedyassets.LoadAsset<Sprite>("assets/nex.speedypaths/speedypaths_2.png"));
			_speedSprites.Add(_speedyassets.LoadAsset<Sprite>("assets/nex.speedypaths/speedypaths_n1.png"));
			_speedSprites.Add(_speedyassets.LoadAsset<Sprite>("assets/nex.speedypaths/speedypaths_n2.png"));
			m_sensorTime = 0f;
			m_cachedGroundType = GroundType.Untamed;
			Harmony.CreateAndPatchAll(typeof(SpeedyPathsClientMod), (string)null);
		}

		[HarmonyPatch(typeof(Player), "FixedUpdate")]
		[HarmonyPrefix]
		private static void UpdateModifiers(Player __instance)
		{
			m_sensorTime -= Time.fixedDeltaTime;
			if (!((Object)(object)Player.m_localPlayer == (Object)(object)__instance) || ((Character)__instance).IsDead())
			{
				return;
			}
			UpdateGroundTypeCache(__instance);
			_activeSpeedModifier = GetSpeedyPathModifier(__instance);
			_activeStaminaModifier = GetSpeedyPathStaminaModifier(__instance);
			if (_activeSpeedModifier > 1f)
			{
				for (int i = 0; i < _hudPosIconThresholds.Count; i++)
				{
					if (_activeSpeedModifier > _hudPosIconThresholds[i].Value)
					{
						_activeStatusSprite = _speedSprites[i];
					}
				}
				return;
			}
			for (int j = 0; j < _hudNegIconThresholds.Count; j++)
			{
				if (_activeSpeedModifier < _hudNegIconThresholds[j].Value)
				{
					_activeStatusSprite = _speedSprites[_hudPosIconThresholds.Count + j];
				}
			}
		}

		[HarmonyPatch(typeof(Player), "CheckRun")]
		[HarmonyPrefix]
		private static void CheckRunPrefixStaminaMod(Player __instance, out float __state)
		{
			__state = __instance.m_runStaminaDrain;
			__instance.m_runStaminaDrain *= _activeStaminaModifier;
		}

		[HarmonyPatch(typeof(Player), "CheckRun")]
		[HarmonyPostfix]
		private static void CheckRunPostfixStaminaMod(Player __instance, float __state)
		{
			__instance.m_runStaminaDrain = __state;
		}

		[HarmonyPatch(typeof(Player), "GetJogSpeedFactor")]
		[HarmonyPostfix]
		private static void JogSpeedPathFactor(Player __instance, ref float __result)
		{
			__result *= _activeSpeedModifier;
		}

		[HarmonyPatch(typeof(Player), "GetRunSpeedFactor")]
		[HarmonyPostfix]
		private static void RunSpeedPathFactor(Player __instance, ref float __result)
		{
			__result *= _activeSpeedModifier;
		}

		[HarmonyPatch(typeof(Hud), "UpdateStatusEffects")]
		[HarmonyPrefix]
		private static void UpdatePathIcon(Hud __instance, List<StatusEffect> statusEffects)
		{
			if (((Character)Player.m_localPlayer).IsDead() || !_showHudStatus.Value || _activeSpeedModifier == 1f)
			{
				return;
			}
			if ((Object)(object)_pathBuffSEDummy == (Object)null)
			{
				ScriptableObject obj = ScriptableObject.CreateInstance(typeof(StatusEffect));
				_pathBuffSEDummy = (StatusEffect)(object)((obj is StatusEffect) ? obj : null);
			}
			_pathBuffSEDummy.m_name = (_hudDynamicStatusText.Value ? _activeStatusText : _hudStatusText.Value);
			_pathBuffSEDummy.m_icon = _activeStatusSprite;
			if (_activeSpeedModifier != 1f)
			{
				if (_activeSpeedModifier != _prevModValue)
				{
					_pathBuffSEDummy.m_isNew = true;
				}
				statusEffects.Add(_pathBuffSEDummy);
			}
			_prevModValue = _activeSpeedModifier;
		}

		[HarmonyPatch(typeof(StatusEffect), "GetIconText")]
		[HarmonyPostfix]
		private static void SpeedyPathsStatusEffect_GetIconText(StatusEffect __instance, ref string __result)
		{
			if ((Object)(object)__instance == (Object)(object)_pathBuffSEDummy && _hudShowEffectPercent.Value)
			{
				__result = (_activeSpeedModifier - 1f).ToString("P0");
			}
		}

		private static float GetSpeedyPathModifier(Player player)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			if (!((Character)player).IsSwimming() && !((Character)player).InInterior())
			{
				if (_speedModifiers.ContainsKey(m_cachedGroundType))
				{
					_activeStatusText = _groundTypeStrings[m_cachedGroundType].Value;
					return _speedModifiers[m_cachedGroundType].Value;
				}
				Biome key = player.GetCurrentBiome();
				if (!_untamedSpeedModifiers.ContainsKey(key))
				{
					Logger.LogWarning((object)("New biome " + ((object)(Biome)(ref key)).ToString() + ". Unsure how to Handle. Falling back to None."));
					key = (Biome)0;
				}
				_activeStatusText = "$biome_" + ((object)(Biome)(ref key)).ToString().ToLower();
				if (_biomeTypeStrings.ContainsKey(key) && _biomeTypeStrings[key].Value != "default")
				{
					_activeStatusText = _biomeTypeStrings[key].Value;
				}
				return _untamedSpeedModifiers[key].Value;
			}
			return 1f;
		}

		private static float GetSpeedyPathStaminaModifier(Player player)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: 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_0071: Unknown result type (might be due to invalid IL or missing references)
			if (!((Character)player).IsSwimming() && !((Character)player).InInterior())
			{
				if (_staminaModifiers.ContainsKey(m_cachedGroundType))
				{
					return _staminaModifiers[m_cachedGroundType].Value;
				}
				Biome key = player.GetCurrentBiome();
				if (!_untamedStaminaModifiers.ContainsKey(key))
				{
					Logger.LogWarning((object)("New biome " + ((object)(Biome)(ref key)).ToString() + ". Unsure how to Handle. Falling back to None."));
					key = (Biome)0;
				}
				return _untamedStaminaModifiers[key].Value;
			}
			return 1f;
		}

		private static void UpdateGroundTypeCache(Player player)
		{
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected I4, but got Unknown
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			if (m_sensorTime > 0f)
			{
				return;
			}
			m_sensorTime = _groundSensorUpdateInterval.Value;
			Collider lastGroundCollider = ((Character)player).GetLastGroundCollider();
			if (Object.op_Implicit((Object)(object)lastGroundCollider))
			{
				if (((Component)lastGroundCollider).gameObject.layer == m_pieceLayer)
				{
					WearNTear componentInParent = ((Component)lastGroundCollider).GetComponentInParent<WearNTear>();
					if (Object.op_Implicit((Object)(object)componentInParent))
					{
						MaterialType materialType = componentInParent.m_materialType;
						switch ((int)materialType)
						{
						case 0:
							m_cachedGroundType = GroundType.StructureWood;
							return;
						case 1:
							m_cachedGroundType = GroundType.StructureStone;
							return;
						case 3:
							m_cachedGroundType = GroundType.StructureHardWood;
							return;
						case 2:
							m_cachedGroundType = GroundType.StructureIron;
							return;
						case 4:
							m_cachedGroundType = GroundType.StructureMarble;
							return;
						}
					}
				}
				Heightmap component = ((Component)lastGroundCollider).GetComponent<Heightmap>();
				if ((Object)(object)component != (Object)null)
				{
					object value = Traverse.Create((object)component).Field("m_paintMask").GetValue();
					Texture2D val = (Texture2D)((value is Texture2D) ? value : null);
					_worldToVertexArgs[0] = Traverse.Create((object)player).Field("m_lastGroundPoint").GetValue() as Vector3?;
					AccessTools.Method(typeof(Heightmap), "WorldToVertex", (Type[])null, (Type[])null).Invoke(component, _worldToVertexArgs);
					int value2 = _groundSensorRadius.Value;
					Color val2 = default(Color);
					int num = Math.Max((int)_worldToVertexArgs[1] - value2, 0);
					int num2 = value2 * 2;
					if (num2 + (int)_worldToVertexArgs[1] >= ((Texture)val).width)
					{
						num2 = ((Texture)val).width - num - 1;
					}
					int num3 = Math.Max((int)_worldToVertexArgs[2] - value2, 0);
					int num4 = value2 * 2;
					if (num4 + (int)_worldToVertexArgs[2] >= ((Texture)val).height)
					{
						num4 = ((Texture)val).height - num3 - 1;
					}
					Color[] pixels = val.GetPixels(num, num3, num2, num4, 0);
					Color[] array = pixels;
					foreach (Color val3 in array)
					{
						val2 += val3;
					}
					((Color)(ref val2))..ctor(val2.r / (float)pixels.Length, val2.g / (float)pixels.Length, val2.b / (float)pixels.Length);
					if (val2.b > 0.4f)
					{
						m_cachedGroundType = GroundType.PathStone;
						return;
					}
					if (val2.r > 0.4f)
					{
						m_cachedGroundType = GroundType.PathDirt;
						return;
					}
					if (val2.g > 0.4f)
					{
						m_cachedGroundType = GroundType.Cultivated;
						return;
					}
				}
			}
			m_cachedGroundType = GroundType.Untamed;
		}
	}
}
namespace SpeedyPaths.Properties
{
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Resources
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					resourceMan = new ResourceManager("SpeedyPaths.Properties.Resources", typeof(Resources).Assembly);
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal static byte[] speedyassets => (byte[])ResourceManager.GetObject("speedyassets", resourceCulture);

		internal Resources()
		{
		}
	}
}

BepInEx/plugins/Nexus-AutoFuel/AutoFuel.dll

Decompiled 8 months ago
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("AutoFuel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AutoFuel")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("87660053-76cb-449e-9ab1-e750f55a0b4d")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.5.2", FrameworkDisplayName = ".NET Framework 4.5.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace AutoFuel;

[BepInPlugin("aedenthorn.AutoFuel", "Auto Fuel", "0.6.0")]
public class BepInExPlugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Smelter), "FixedUpdate")]
	private static class Smelter_FixedUpdate_Patch
	{
		private static void Postfix(Smelter __instance, ZNetView ___m_nview)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0528: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a5: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer) || !isOn.Value)
			{
				return;
			}
			int num = __instance.m_maxOre - Traverse.Create((object)__instance).Method("GetQueueSize", new object[0]).GetValue<int>();
			int num2 = __instance.m_maxFuel - Mathf.CeilToInt(___m_nview.GetZDO().GetFloat("fuel", 0f));
			List<Container> nearbyContainers = GetNearbyContainers(((Component)__instance).transform.position);
			Vector3 val = ((Component)__instance).transform.position + Vector3.up;
			Collider[] array = Physics.OverlapSphere(val, dropRange.Value, LayerMask.GetMask(new string[1] { "item" }));
			foreach (Collider val2 in array)
			{
				if (!Object.op_Implicit((Object)(object)((val2 != null) ? val2.attachedRigidbody : null)))
				{
					continue;
				}
				ItemDrop component = ((Component)val2.attachedRigidbody).GetComponent<ItemDrop>();
				if (component == null)
				{
					continue;
				}
				ZNetView component2 = ((Component)component).GetComponent<ZNetView>();
				if (((component2 != null) ? new bool?(component2.IsValid()) : null) != true)
				{
					continue;
				}
				string prefabName = GetPrefabName(((Object)((Component)component).gameObject).name);
				foreach (ItemConversion item3 in __instance.m_conversion)
				{
					if (!(component.m_itemData.m_shared.m_name == item3.m_from.m_itemData.m_shared.m_name) || num <= 0 || oreDisallowTypes.Value.Split(new char[1] { ',' }).Contains(prefabName))
					{
						continue;
					}
					Dbgl("auto adding ore " + prefabName + " from ground");
					int num3 = Mathf.Min(component.m_itemData.m_stack, num);
					num -= num3;
					for (int j = 0; j < num3; j++)
					{
						if (component.m_itemData.m_stack <= 1)
						{
							if (___m_nview.GetZDO() == null)
							{
								Object.Destroy((Object)(object)((Component)component).gameObject);
							}
							else
							{
								ZNetScene.instance.Destroy(((Component)component).gameObject);
							}
							___m_nview.InvokeRPC("AddOre", new object[1] { prefabName });
							break;
						}
						ItemData itemData = component.m_itemData;
						itemData.m_stack--;
						___m_nview.InvokeRPC("AddOre", new object[1] { prefabName });
						Traverse.Create((object)component).Method("Save", new object[0]).GetValue();
					}
				}
				if (!Object.op_Implicit((Object)(object)__instance.m_fuelItem) || !(component.m_itemData.m_shared.m_name == __instance.m_fuelItem.m_itemData.m_shared.m_name) || num2 <= 0 || fuelDisallowTypes.Value.Split(new char[1] { ',' }).Contains(prefabName))
				{
					continue;
				}
				Dbgl("auto adding fuel " + prefabName + " from ground");
				int num4 = Mathf.Min(component.m_itemData.m_stack, num2);
				num2 -= num4;
				for (int k = 0; k < num4; k++)
				{
					if (component.m_itemData.m_stack <= 1)
					{
						if (___m_nview.GetZDO() == null)
						{
							Object.Destroy((Object)(object)((Component)component).gameObject);
						}
						else
						{
							ZNetScene.instance.Destroy(((Component)component).gameObject);
						}
						___m_nview.InvokeRPC("AddFuel", new object[0]);
						break;
					}
					ItemData itemData2 = component.m_itemData;
					itemData2.m_stack--;
					___m_nview.InvokeRPC("AddFuel", new object[0]);
					Traverse.Create((object)component).Method("Save", new object[0]).GetValue();
				}
			}
			foreach (Container item4 in nearbyContainers)
			{
				foreach (ItemConversion item5 in __instance.m_conversion)
				{
					ItemData item = item4.GetInventory().GetItem(item5.m_from.m_itemData.m_shared.m_name);
					if (item != null && num > 0)
					{
						num--;
						if (!oreDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item.m_dropPrefab).name))
						{
							Dbgl($"container at {((Component)item4).transform.position} has {item.m_stack} {((Object)item.m_dropPrefab).name}, taking one");
							object[] array2 = new object[1];
							GameObject dropPrefab = item.m_dropPrefab;
							array2[0] = ((dropPrefab != null) ? ((Object)dropPrefab).name : null);
							___m_nview.InvokeRPC("AddOre", array2);
							item4.GetInventory().RemoveItem(item5.m_from.m_itemData.m_shared.m_name, 1);
							typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item4, new object[0]);
							typeof(Inventory).GetMethod("Changed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item4.GetInventory(), new object[0]);
						}
					}
				}
				if (!Object.op_Implicit((Object)(object)__instance.m_fuelItem) || num2 <= 0)
				{
					continue;
				}
				ItemData item2 = item4.GetInventory().GetItem(__instance.m_fuelItem.m_itemData.m_shared.m_name);
				if (item2 != null)
				{
					num2--;
					if (!fuelDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item2.m_dropPrefab).name))
					{
						Dbgl($"container at {((Component)item4).transform.position} has {item2.m_stack} {((Object)item2.m_dropPrefab).name}, taking one");
						___m_nview.InvokeRPC("AddFuel", new object[0]);
						item4.GetInventory().RemoveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, 1);
						typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item4, new object[0]);
						typeof(Inventory).GetMethod("Changed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item4.GetInventory(), new object[0]);
					}
				}
			}
		}
	}

	[HarmonyPatch(typeof(Console), "InputText")]
	private static class InputText_Patch
	{
		private static bool Prefix(Console __instance)
		{
			if (!modEnabled.Value)
			{
				return true;
			}
			string text = __instance.m_input.text;
			if (text.ToLower().Equals("autofuel reset"))
			{
				((BaseUnityPlugin)context).Config.Reload();
				((BaseUnityPlugin)context).Config.Save();
				Traverse.Create((object)__instance).Method("AddString", new object[1] { text }).GetValue();
				Traverse.Create((object)__instance).Method("AddString", new object[1] { "AutoFuel config reloaded" }).GetValue();
				return false;
			}
			return true;
		}
	}

	private static readonly bool isDebug;

	public static ConfigEntry<float> dropRange;

	public static ConfigEntry<float> containerRange;

	public static ConfigEntry<string> fuelDisallowTypes;

	public static ConfigEntry<string> oreDisallowTypes;

	public static ConfigEntry<string> toggleKey;

	public static ConfigEntry<string> toggleString;

	public static ConfigEntry<bool> isOn;

	public static ConfigEntry<bool> modEnabled;

	public static ConfigEntry<int> nexusID;

	private static BepInExPlugin context;

	public static void Dbgl(string str = "", bool pref = true)
	{
		if (isDebug)
		{
			Debug.Log((object)((pref ? (typeof(BepInExPlugin).Namespace + " ") : "") + str));
		}
	}

	private void Awake()
	{
		context = this;
		dropRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "DropRange", 5f, "The maximum range to pull dropped fuel");
		containerRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ContainerRange", 5f, "The maximum range to pull fuel from containers");
		fuelDisallowTypes = ((BaseUnityPlugin)this).Config.Bind<string>("General", "FuelDisallowTypes", "RoundLog,FineWood", "Types of item to disallow as fuel (i.e. anything that is consumed), comma-separated.");
		oreDisallowTypes = ((BaseUnityPlugin)this).Config.Bind<string>("General", "OreDisallowTypes", "RoundLog,FineWood", "Types of item to disallow as ore (i.e. anything that is transformed), comma-separated).");
		toggleString = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ToggleString", "Auto Fuel: {0}", "Text to show on toggle. {0} is replaced with true/false");
		toggleKey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ToggleKey", "", "Key to toggle behaviour. Leave blank to disable the toggle key.");
		isOn = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "IsOn", true, "Behaviour is currently on or not");
		modEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable this mod");
		nexusID = ((BaseUnityPlugin)this).Config.Bind<int>("General", "NexusID", 159, "Nexus mod ID for updates");
		if (modEnabled.Value)
		{
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		}
	}

	private void Update()
	{
		if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !Console.IsVisible())
		{
			Chat instance = Chat.instance;
			if ((instance == null || !instance.HasFocus()) && CheckKeyDown(toggleKey.Value))
			{
				isOn.Value = !isOn.Value;
				((BaseUnityPlugin)this).Config.Save();
				((Character)Player.m_localPlayer).Message((MessageType)2, string.Format(toggleString.Value, isOn.Value), 0, (Sprite)null);
			}
		}
	}

	private static bool CheckKeyDown(string value)
	{
		try
		{
			return Input.GetKeyDown(value.ToLower());
		}
		catch
		{
			return false;
		}
	}

	private static string GetPrefabName(string name)
	{
		char[] anyOf = new char[2] { '(', ' ' };
		int num = name.IndexOfAny(anyOf);
		if (num >= 0)
		{
			return name.Substring(0, num);
		}
		return name;
	}

	public static List<Container> GetNearbyContainers(Vector3 center)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			List<Container> list = new List<Container>();
			Collider[] array = Physics.OverlapSphere(center, Mathf.Max(containerRange.Value, 0f), LayerMask.GetMask(new string[1] { "piece" }));
			foreach (Collider val in array)
			{
				Transform parent = ((Component)val).transform.parent;
				object obj;
				if (parent == null)
				{
					obj = null;
				}
				else
				{
					Transform parent2 = parent.parent;
					if (parent2 == null)
					{
						obj = null;
					}
					else
					{
						GameObject gameObject = ((Component)parent2).gameObject;
						obj = ((gameObject != null) ? gameObject.GetComponent<Container>() : null);
					}
				}
				Container val2 = (Container)obj;
				if (val2 == null)
				{
					continue;
				}
				ZNetView component = ((Component)val2).GetComponent<ZNetView>();
				if (((component != null) ? new bool?(component.IsValid()) : null) == true && val2 != null)
				{
					Transform transform = ((Component)val2).transform;
					if (((transform != null) ? new Vector3?(transform.position) : null).HasValue && (((Object)val2).name.StartsWith("piece_chest") || ((Object)val2).name.StartsWith("Container")) && val2.GetInventory() != null)
					{
						list.Add(val2);
					}
				}
			}
			return list;
		}
		catch
		{
			return new List<Container>();
		}
	}
}

BepInEx/plugins/OdinPlus-Clutter/Clutter/Clutter.dll

Decompiled 8 months ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using BepInEx;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("JotunnModStub")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JotunnModStub")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")]
[assembly: AssemblyFileVersion("0.1.5")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.5.0")]
namespace Clutter;

[BepInPlugin("com.plumga.Clutter", "Clutter", "0.1.5")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
internal class Clutter : BaseUnityPlugin
{
	public const string PluginGUID = "com.plumga.Clutter";

	public const string PluginName = "Clutter";

	public const string PluginVersion = "0.1.5";

	private AssetBundle assetclutter;

	private AssetBundle assetdeco;

	private AssetBundle assetfurniture;

	private AssetBundle assetkitchen;

	private AssetBundle assetsculptures;

	private AssetBundle new1;

	private AssetBundle new2;

	private AssetBundle assetevilshit;

	private AssetBundle assetnewcluttermarch2022;

	private void Awake()
	{
		LoadAssets();
		LoadTable();
		basket();
		bucketdeco();
		bucketbigdeco();
		candlebottle();
		candlelantern();
		candlelit2();
		candlesnake();
		candle();
		candlelit();
		diary();
		diarypage();
		bluebook();
		bluebookhoriz();
		redbook();
		redbookhoriz();
		quillandink();
		quillandparchment();
		scroll1();
		scroll2();
		scroll3();
		scroll4();
		scroll5();
		picframe1();
		picframe2();
		picframe3();
		picframe4();
		deer();
		lox();
		wolf();
		soap();
		pipe();
		comb();
		straw();
		winebottle();
		BarberPole();
		grave();
		bonepile();
		bones1();
		bones2();
		bones3();
		bones4();
		skull();
		itemstandhoriz();
		itemstandvert();
		itemstandspear();
		itemstandstake();
		coolchair();
		stool();
		swing();
		swingingswing();
		roundtable();
		tablewithcloth();
		fancychest();
		stonechest();
		shelf();
		shelfwbooks();
		shelfwbooksdouble();
		weaponrack();
		weaponrackfull();
		altar();
		altarwcandle();
		tub();
		tubfull();
		winerack();
		clock();
		birdhouse();
		bowl();
		bowlbig();
		plate();
		platebig();
		mug1();
		mug2();
		pan();
		pot();
		spoon();
		mortarpestle();
		rollingpin();
		fondue();
		picnicbasket();
		sculptowl();
		sculptpelican();
		sculptdeer();
		sculptelk();
		sculptcrow();
		sculptheron();
		sculptwolf();
		sculpthorse();
		statuecorgi();
		statuedeer();
		statueevillarge();
		statueevilsmall();
		statuehare();
		statueseed();
		bookstorage();
		bookstoragepublic();
		fancychestpublic();
		stonechestpublic();
		hweb();
		tweb();
		vweb();
		journal();
		openbook();
		poetrybook1H();
		poetrybook1V();
		poetrybook2H();
		poetrybook2V();
		stackedbooks1();
		stackedbooks2();
		globe1();
		globe2();
		map1();
		map2();
		map3();
		dragonstatuesmall();
		dragonstatuelarge();
		Bdragonstatuesmall();
		Bdragonstatuelarge();
		LargeSign();
		CelticIdol1();
		CelticIdol1Small();
		CelticIdol2();
		CelticIdol3();
		CelticIdol4();
		CelticIdol5();
		CelticIdol6();
		CelticIdol7();
		CelticIdol8();
		CelticIdol9();
		CelticIdol10();
		CelticIdol11();
		CelticIdol12();
		LokiSculpture();
		OdinSculpture();
		BloodyShelf();
		BloodyTable();
		BloodyRag();
		DevilWindow();
		FishSkele();
		HandPrint();
		Pentagram();
		PentagramVert();
		PentagramVertSM();
		PicFrame();
		PicFrameBig();
		SkullCandle();
		SkullCandle2();
		DeerHead();
		ArmBook();
		LeatherBook();
		OpenBook();
		MagicBooks();
		OuijaBook();
		Couch1();
		Couch2();
		Couch3();
		Couch4();
		CouchBed1();
		CouchBed2();
		NewShelf();
		RectTable();
		WallShelf();
		BearsPainting();
		VanGogh();
		BlueBook();
		GreenBook();
		RedBook();
		Pillow1();
		Pillow2();
		Pillow3();
		FlintBowl();
	}

	private void LoadAssets()
	{
		assetclutter = AssetUtils.LoadAssetBundleFromResources("clutter", typeof(Clutter).Assembly);
		assetdeco = AssetUtils.LoadAssetBundleFromResources("deco", typeof(Clutter).Assembly);
		assetfurniture = AssetUtils.LoadAssetBundleFromResources("furniture", typeof(Clutter).Assembly);
		assetkitchen = AssetUtils.LoadAssetBundleFromResources("kitchen", typeof(Clutter).Assembly);
		assetsculptures = AssetUtils.LoadAssetBundleFromResources("sculptures", typeof(Clutter).Assembly);
		new1 = AssetUtils.LoadAssetBundleFromResources("new1", typeof(Clutter).Assembly);
		new2 = AssetUtils.LoadAssetBundleFromResources("new2", typeof(Clutter).Assembly);
		assetevilshit = AssetUtils.LoadAssetBundleFromResources("evilshit", typeof(Clutter).Assembly);
		assetnewcluttermarch2022 = AssetUtils.LoadAssetBundleFromResources("newcluttermarch2022", typeof(Clutter).Assembly);
	}

	private void LoadTable()
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Expected O, but got Unknown
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		GameObject val = assetclutter.LoadAsset<GameObject>("_ClutterPieceTable");
		PieceTableConfig val2 = new PieceTableConfig();
		val2.CanRemovePieces = true;
		val2.UseCategories = false;
		val2.UseCustomCategories = true;
		val2.CustomCategories = new string[4] { "Sculptures", "Kitchen", "Decor", "Amenities" };
		CustomPieceTable val3 = new CustomPieceTable(val, val2);
		PieceManager.Instance.AddPieceTable(val3);
		LoadClutterTool();
	}

	private void LoadClutterTool()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Expected O, but got Unknown
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Expected O, but got Unknown
		GameObject val = assetclutter.LoadAsset<GameObject>("$PlumgaClutterTool");
		ItemConfig val2 = new ItemConfig();
		val2.Amount = 1;
		val2.CraftingStation = "piece_workbench";
		val2.RepairStation = "piece_workbench";
		val2.MinStationLevel = 1;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				AmountPerLevel = 1
			}
		};
		CustomItem val3 = new CustomItem(val, true, val2);
		ItemManager.Instance.AddItem(val3);
	}

	private void LargeSign()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_largesign");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 5,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, false, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol1()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol1");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol1Small()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol1small");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 15,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol2()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol2");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol3()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol3");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol4()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol4");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol5()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol5");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol6()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol6");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol7()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol7");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol8()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol8");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol9()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol9");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol10()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol10");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol11()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol11");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void CelticIdol12()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_celticidol12");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void LokiSculpture()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_lokistatue");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Iron",
				Amount = 20,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void OdinSculpture()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new2.LoadAsset<GameObject>("$custompiece_odinstatue");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Iron",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void bookstorage()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_booksecretstorage");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Amenities";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void bookstoragepublic()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_booksecretstorage_public");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Amenities";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void fancychestpublic()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_fancychest_public");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Amenities";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "FineWood",
				Amount = 5,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Bronze",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void stonechestpublic()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_stonechest_public");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Amenities";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Stone",
				Amount = 5,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Bronze",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void hweb()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_horizontalweb");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "BoneFragments",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void tweb()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_tunnelweb");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "BoneFragments",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void vweb()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_verticalweb");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "BoneFragments",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void journal()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_journal");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, false, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void openbook()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_openbook");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void poetrybook1H()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_poetrybook1H");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void poetrybook1V()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_poetrybook1V");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void poetrybook2H()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_poetrybook2H");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void poetrybook2V()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_poetrybook2V");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void stackedbooks1()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_stackedpoetrybooks1");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 6,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void stackedbooks2()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_stackedpoetrybooks2");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 6,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void globe1()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_globe1");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 3,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void globe2()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Expected O, but got Unknown
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_globe2");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 6,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Iron",
				Amount = 4,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void map1()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_map1");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void map2()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_map2");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void map3()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_map3");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 4,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void dragonstatuesmall()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//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_0079: 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_008b: Expected O, but got Unknown
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_dragonstatuesmall");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Bronze",
				Amount = 10,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Copper",
				Amount = 10,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void dragonstatuelarge()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//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_0079: 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_008b: Expected O, but got Unknown
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_dragonstatuelarge");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Bronze",
				Amount = 25,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Copper",
				Amount = 25,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void Bdragonstatuesmall()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_blackdragonstatuesmall");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Iron",
				Amount = 10,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void Bdragonstatuelarge()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0066: Expected O, but got Unknown
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Expected O, but got Unknown
		GameObject val = new1.LoadAsset<GameObject>("$custompiece_blackdragonstatuelarge");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Sculptures";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Iron",
				Amount = 30,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void basket()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_basket");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void bucketdeco()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_bucket");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 3,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "BronzeNails",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void bucketbigdeco()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_bucketbig");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 5,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "BronzeNails",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void candlebottle()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_candlebottle");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Honey",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Flint",
				Amount = 5,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void candlelantern()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_candlelantern");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Honey",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Flint",
				Amount = 5,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, false, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void candlelit2()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_candlelit2");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Honey",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Flint",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void candlesnake()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_candlesnake");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Honey",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Flint",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void candle()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_dunmr_candle");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Honey",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void candlelit()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_dunmr_candlelit");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Honey",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Flint",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void diary()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_diary");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, false, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void diarypage()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_diarypage");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, false, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void bluebook()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_dunmr_bookblue");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void bluebookhoriz()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_dunmr_bookblue_horiz");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void redbook()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_dunmr_bookred");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void redbookhoriz()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_dunmr_bookred_horiz");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void quillandink()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_quillandink");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Feathers",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void quillandparchment()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Expected O, but got Unknown
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_quillandparchment");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "Feathers",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void scroll1()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_scroll1");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void scroll2()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_scroll2");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void scroll3()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_scroll3");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void scroll4()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_scroll4");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void scroll5()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_scroll5");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void picframe1()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_pictureframe1");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "BronzeNails",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void picframe2()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_pictureframe2");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "BronzeNails",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void picframe3()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_pictureframe3");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "BronzeNails",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void picframe4()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_pictureframe4");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "BronzeNails",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void deer()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_rug_deer_tablecloth");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "DeerHide",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void lox()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_rug_fur_tablecloth");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "LoxPelt",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void wolf()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_rug_wolf_tablecloth");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "WolfPelt",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void soap()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_0089: Expected O, but got Unknown
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_soap");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
		{
			new RequirementConfig
			{
				Item = "Coal",
				Amount = 1,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "RawMeat",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void pipe()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		GameObject val = assetdeco.LoadAsset<GameObject>("$custompiece_pipe");
		PieceConfig val2 = new PieceConfig();
		val2.PieceTable = "_ClutterPieceTable";
		val2.Category = "Decor";
		val2.AllowedInDungeons = false;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
		{
			new RequirementConfig
			{
				Item = "Wood",
				Amount = 2,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, true, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	private void comb()
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to inva

BepInEx/plugins/OdinPlus-CraftyCartsRemake/CraftyCartsRemake.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using PieceManager;
using ServerSync;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("CraftyCarts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("CraftyCarts")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9E0F9E39-EC09-4482-B9FA-9793AEF54F10")]
[assembly: AssemblyFileVersion("3.1.0")]
[assembly: AssemblyCompany("Azumatt/RoloPogo")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.1.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<eacda59c-4af7-49ef-b72a-d82267bb812d>Embedded]
	internal sealed class <eacda59c-4af7-49ef-b72a-d82267bb812d>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<eacda59c-4af7-49ef-b72a-d82267bb812d>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <76454529-a769-42a6-a71c-ea642218f04f>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <76454529-a769-42a6-a71c-ea642218f04f>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <76454529-a769-42a6-a71c-ea642218f04f>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<eacda59c-4af7-49ef-b72a-d82267bb812d>Embedded]
	internal sealed class <8a37fe5c-47e1-4257-9589-07ee12084834>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <8a37fe5c-47e1-4257-9589-07ee12084834>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace PieceManager
{
	[PublicAPI]
	public enum CraftingTable
	{
		None,
		[InternalName("piece_workbench")]
		Workbench,
		[InternalName("piece_cauldron")]
		Cauldron,
		[InternalName("forge")]
		Forge,
		[InternalName("piece_artisanstation")]
		ArtisanTable,
		[InternalName("piece_stonecutter")]
		StoneCutter,
		[InternalName("piece_magetable")]
		MageTable,
		[InternalName("blackforge")]
		BlackForge,
		Custom
	}
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	public class InternalName : Attribute
	{
		public readonly string internalName;

		public InternalName(string internalName)
		{
			this.internalName = internalName;
		}
	}
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[PublicAPI]
	public class ExtensionList
	{
		public readonly List<ExtensionConfig> ExtensionStations = new List<ExtensionConfig>();

		public void Set(CraftingTable table, int maxStationDistance = 5)
		{
			ExtensionStations.Add(new ExtensionConfig
			{
				Table = table,
				maxStationDistance = maxStationDistance
			});
		}

		public void Set(string customTable, int maxStationDistance = 5)
		{
			ExtensionStations.Add(new ExtensionConfig
			{
				Table = CraftingTable.Custom,
				custom = customTable,
				maxStationDistance = maxStationDistance
			});
		}
	}
	public struct ExtensionConfig
	{
		public CraftingTable Table;

		public float maxStationDistance;

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
		public string custom;
	}
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[PublicAPI]
	public class CraftingStationList
	{
		public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>();

		public void Set(CraftingTable table)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = table
			});
		}

		public void Set(string customTable)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = CraftingTable.Custom,
				custom = customTable
			});
		}
	}
	public struct CraftingStationConfig
	{
		public CraftingTable Table;

		public int level;

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
		public string custom;
	}
	[PublicAPI]
	public enum BuildPieceCategory
	{
		Misc = 0,
		Crafting = 1,
		Building = 2,
		Furniture = 3,
		All = 100,
		Custom = 99
	}
	[PublicAPI]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	public class RequiredResourcesList
	{
		public readonly List<Requirement> Requirements = new List<Requirement>();

		public void Add(string item, int amount, bool recover)
		{
			Requirements.Add(new Requirement
			{
				itemName = item,
				amount = amount,
				recover = recover
			});
		}
	}
	public struct Requirement
	{
		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(1)]
		public string itemName;

		public int amount;

		public bool recover;
	}
	public struct SpecialProperties
	{
		[Description("Admins should be the only ones that can build this piece.")]
		public bool AdminOnly;

		[Description("Turns off generating a config for this build piece.")]
		public bool NoConfig;
	}
	[PublicAPI]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	public class BuildingPieceCategory
	{
		public BuildPieceCategory Category;

		public string custom = "";

		public void Set(BuildPieceCategory category)
		{
			Category = category;
		}

		public void Set(string customCategory)
		{
			Category = BuildPieceCategory.Custom;
			custom = customCategory;
		}
	}
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	[PublicAPI]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	public class PieceTool
	{
		public readonly HashSet<string> Tools = new HashSet<string>();

		public void Add(string tool)
		{
			Tools.Add(tool);
		}
	}
	[PublicAPI]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	public class BuildPiece
	{
		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
		internal class PieceConfig
		{
			public ConfigEntry<string> craft;

			public ConfigEntry<BuildPieceCategory> category;

			public ConfigEntry<string> customCategory;

			public ConfigEntry<string> tools;

			public ConfigEntry<CraftingTable> extensionTable;

			public ConfigEntry<string> customExtentionTable;

			public ConfigEntry<float> maxStationDistance;

			public ConfigEntry<CraftingTable> table;

			public ConfigEntry<string> customTable;
		}

		[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
			[UsedImplicitly]
			public string Category;

			[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(new byte[] { 2, 1 })]
			[UsedImplicitly]
			public Action<ConfigEntryBase> CustomDrawer;
		}

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
		private class SerializedRequirements
		{
			public readonly List<Requirement> Reqs;

			public SerializedRequirements(List<Requirement> reqs)
			{
				Reqs = reqs;
			}

			public SerializedRequirements(string reqs)
			{
				Reqs = reqs.Split(new char[1] { ',' }).Select([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (string r) =>
				{
					string[] array = r.Split(new char[1] { ':' });
					Requirement result = default(Requirement);
					result.itemName = array[0];
					result.amount = ((array.Length <= 1 || !int.TryParse(array[1], out var result2)) ? 1 : result2);
					bool result3 = default(bool);
					result.recover = array.Length <= 2 || !bool.TryParse(array[2], out result3) || result3;
					return result;
				}).ToList();
			}

			public override string ToString()
			{
				return string.Join(",", Reqs.Select([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}:{r.recover}"));
			}

			public static Requirement[] toPieceReqs(SerializedRequirements craft)
			{
				return craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func<Requirement, string>)([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (Requirement r) => r.itemName), (Func<Requirement, Requirement>)([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (Requirement r) =>
				{
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					//IL_001d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0024: Unknown result type (might be due to invalid IL or missing references)
					//IL_0031: Expected O, but got Unknown
					ItemDrop val = ResItem(r);
					return (val != null) ? new Requirement
					{
						m_amount = r.amount,
						m_resItem = val,
						m_recover = r.recover
					} : ((Requirement)null);
				})).Values.Where([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (Requirement v) => v != null).ToArray();
				[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(2)]
				static ItemDrop ResItem(Requirement r)
				{
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(r.itemName);
					ItemDrop obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
					if ((Object)(object)obj == (Object)null)
					{
						Debug.LogWarning((object)("The required item '" + r.itemName + "' does not exist."));
					}
					return obj;
				}
			}
		}

		internal static readonly List<BuildPiece> registeredPieces = new List<BuildPiece>();

		internal static Dictionary<BuildPiece, PieceConfig> pieceConfigs = new Dictionary<BuildPiece, PieceConfig>();

		[Description("Disables generation of the configs for your pieces. This is global, this turns it off for all pieces in your mod.")]
		public static bool ConfigurationEnabled = true;

		public readonly GameObject Prefab;

		[Description("Specifies the resources needed to craft the piece.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the building piece should need.")]
		public readonly RequiredResourcesList RequiredItems = new RequiredResourcesList();

		[Description("Sets the category for the building piece.")]
		public readonly BuildingPieceCategory Category = new BuildingPieceCategory();

		[Description("Specifies the tool needed to build your piece.\nUse .Add to add a tool.")]
		public readonly PieceTool Tool = new PieceTool();

		[Description("Specifies the crafting station needed to build your piece.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.")]
		public CraftingStationList Crafting = new CraftingStationList();

		[Description("Makes this piece a station extension")]
		public ExtensionList Extension = new ExtensionList();

		[Description("Change the extended/special properties of your build piece.")]
		public SpecialProperties SpecialProperties;

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
		private LocalizeKey _name;

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
		private LocalizeKey _description;

		internal string[] activeTools;

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
		private static object configManager;

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
		private static Localization _english;

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
		internal static BaseUnityPlugin _plugin = null;

		private static bool hasConfigSync = true;

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
		private static object _configSync;

		public LocalizeKey Name
		{
			get
			{
				LocalizeKey name = _name;
				if (name != null)
				{
					return name;
				}
				Piece component = Prefab.GetComponent<Piece>();
				if (component.m_name.StartsWith("$"))
				{
					_name = new LocalizeKey(component.m_name);
				}
				else
				{
					string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_");
					_name = new LocalizeKey(text).English(component.m_name);
					component.m_name = text;
				}
				return _name;
			}
		}

		public LocalizeKey Description
		{
			get
			{
				LocalizeKey description = _description;
				if (description != null)
				{
					return description;
				}
				Piece component = Prefab.GetComponent<Piece>();
				if (component.m_description.StartsWith("$"))
				{
					_description = new LocalizeKey(component.m_description);
				}
				else
				{
					string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_") + "_description";
					_description = new LocalizeKey(text).English(component.m_description);
					component.m_description = text;
				}
				return _description;
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		internal static BaseUnityPlugin plugin
		{
			get
			{
				//IL_009f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a9: Expected O, but got Unknown
				if (_plugin != null)
				{
					return _plugin;
				}
				IEnumerable<TypeInfo> source;
				try
				{
					source = Assembly.GetExecutingAssembly().DefinedTypes.ToList();
				}
				catch (ReflectionTypeLoadException ex)
				{
					source = from t in ex.Types
						where t != null
						select t.GetTypeInfo();
				}
				_plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
				return _plugin;
			}
		}

		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)]
		private static object configSync
		{
			[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(2)]
			get
			{
				if (_configSync != null || !hasConfigSync)
				{
					return _configSync;
				}
				Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
				if ((object)type != null)
				{
					_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " PieceManager");
					type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
					type.GetProperty("IsLocked").SetValue(_configSync, true);
				}
				else
				{
					hasConfigSync = false;
				}
				return _configSync;
			}
		}

		public BuildPiece(string assetBundleFileName, string prefabName, string folderName = "assets")
			: this(PiecePrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName)
		{
		}

		public BuildPiece(AssetBundle bundle, string prefabName)
		{
			Prefab = PiecePrefabManager.RegisterPrefab(bundle, prefabName);
			registeredPieces.Add(this);
		}

		internal static void Patch_FejdStartup(FejdStartup __instance)
		{
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Expected O, but got Unknown
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f2: Expected O, but got Unknown
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e3: Expected O, but got Unknown
			//IL_0537: Unknown result type (might be due to invalid IL or missing references)
			//IL_0541: Expected O, but got Unknown
			//IL_07fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0804: Expected O, but got Unknown
			//IL_05a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b1: Expected O, but got Unknown
			//IL_0648: Unknown result type (might be due to invalid IL or missing references)
			//IL_0652: Expected O, but got Unknown
			//IL_086a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0874: Expected O, but got Unknown
			Type configManagerType = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager");
			configManager = ((configManagerType == null) ? null : Chainloader.ManagerObject.GetComponent(configManagerType));
			foreach (BuildPiece registeredPiece in registeredPieces)
			{
				registeredPiece.activeTools = registeredPiece.Tool.Tools.DefaultIfEmpty("Hammer").ToArray();
			}
			if (!ConfigurationEnabled)
			{
				return;
			}
			bool saveOnConfigSet = plugin.Config.SaveOnConfigSet;
			plugin.Config.SaveOnConfigSet = false;
			foreach (BuildPiece registeredPiece2 in registeredPieces)
			{
				BuildPiece piece = registeredPiece2;
				if (piece.SpecialProperties.NoConfig)
				{
					continue;
				}
				PieceConfig pieceConfig2 = (pieceConfigs[piece] = new PieceConfig());
				PieceConfig cfg = pieceConfig2;
				Piece piecePrefab = piece.Prefab.GetComponent<Piece>();
				string pieceName = piecePrefab.m_name;
				string englishName = new Regex("['[\"\\]]").Replace(english.Localize(pieceName), "").Trim();
				string localizedName = Localization.instance.Localize(pieceName).Trim();
				int order = 0;
				cfg.category = config(englishName, "Build Table Category", piece.Category.Category, new ConfigDescription("Build Category where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1]
				{
					new ConfigurationManagerAttributes
					{
						Order = (order -= 1),
						Category = localizedName
					}
				}));
				ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes
				{
					Order = (order -= 1),
					Browsable = (cfg.category.Value == BuildPieceCategory.Custom),
					Category = localizedName
				};
				cfg.customCategory = config(englishName, "Custom Build Category", piece.Category.custom, new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
				cfg.category.SettingChanged += BuildTableConfigChanged;
				cfg.customCategory.SettingChanged += BuildTableConfigChanged;
				if (cfg.category.Value == BuildPieceCategory.Custom)
				{
					piecePrefab.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value);
				}
				else
				{
					piecePrefab.m_category = (PieceCategory)cfg.category.Value;
				}
				cfg.tools = config(englishName, "Tools", string.Join(", ", piece.activeTools), new ConfigDescription("Comma separated list of tools where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
				piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' })
					select s.Trim()).ToArray();
				cfg.tools.SettingChanged += [<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (object _, EventArgs _) =>
				{
					Inventory[] source = (from c in Player.s_players.Select([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsOfType<Container>()
							select c.GetInventory())
						where c != null
						select c).ToArray();
					Dictionary<string, List<PieceTable>> dictionary = (from kv in (from i in (from p in ObjectDB.instance.m_items
								select p.GetComponent<ItemDrop>() into c
								where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent<ZNetView>())
								select c).Concat(ItemDrop.s_instances)
							select new KeyValuePair<string, ItemData>(Utils.GetPrefabName(((Component)i).gameObject), i.m_itemData)).Concat(from i in source.SelectMany([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (Inventory i) => i.GetAllItems())
							select new KeyValuePair<string, ItemData>(((Object)i.m_dropPrefab).name, i))
						where Object.op_Implicit((Object)(object)kv.Value.m_shared.m_buildPieces)
						group kv by kv.Key).ToDictionary([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (IGrouping<string, KeyValuePair<string, ItemData>> g) => g.Key, [<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (IGrouping<string, KeyValuePair<string, ItemData>> g) => g.Select([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (KeyValuePair<string, ItemData> kv) => kv.Value.m_shared.m_buildPieces).Distinct().ToList());
					string[] array5 = piece.activeTools;
					foreach (string key in array5)
					{
						if (dictionary.TryGetValue(key, out var value2))
						{
							foreach (PieceTable item3 in value2)
							{
								item3.m_pieces.Remove(piece.Prefab);
							}
						}
					}
					piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' })
						select s.Trim()).ToArray();
					if (Object.op_Implicit((Object)(object)ObjectDB.instance))
					{
						array5 = piece.activeTools;
						foreach (string key2 in array5)
						{
							if (dictionary.TryGetValue(key2, out var value3))
							{
								foreach (PieceTable item4 in value3)
								{
									if (!item4.m_pieces.Contains(piece.Prefab))
									{
										item4.m_pieces.Add(piece.Prefab);
									}
								}
							}
						}
						if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces))
						{
							((Humanoid)Player.m_localPlayer).SetPlaceMode(Player.m_localPlayer.m_buildPieces);
						}
					}
				};
				StationExtension pieceExtensionComp;
				List<ConfigurationManagerAttributes> hideWhenNoneAttributes2;
				if (piece.Extension.ExtensionStations.Count > 0)
				{
					pieceExtensionComp = piece.Prefab.GetOrAddComponent<StationExtension>();
					PieceConfig pieceConfig3 = cfg;
					string group = englishName;
					CraftingTable table = piece.Extension.ExtensionStations.First().Table;
					string text = "Crafting station that " + localizedName + " extends.";
					object[] array = new object[1];
					ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes();
					int num = order - 1;
					order = num;
					configurationManagerAttributes.Order = num;
					array[0] = configurationManagerAttributes;
					pieceConfig3.extensionTable = config(group, "Extends Station", table, new ConfigDescription(text, (AcceptableValueBase)null, array));
					cfg.customExtentionTable = config(englishName, "Custom Extend Station", piece.Extension.ExtensionStations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
					PieceConfig pieceConfig4 = cfg;
					string group2 = englishName;
					float maxStationDistance = piece.Extension.ExtensionStations.First().maxStationDistance;
					string text2 = "Distance from the station that " + localizedName + " can be placed.";
					object[] array2 = new object[1];
					ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes();
					num = order - 1;
					order = num;
					configurationManagerAttributes2.Order = num;
					array2[0] = configurationManagerAttributes2;
					pieceConfig4.maxStationDistance = config(group2, "Max Station Distance", maxStationDistance, new ConfigDescription(text2, (AcceptableValueBase)null, array2));
					hideWhenNoneAttributes2 = new List<ConfigurationManagerAttributes>();
					cfg.extensionTable.SettingChanged += ExtensionTableConfigChanged;
					cfg.customExtentionTable.SettingChanged += ExtensionTableConfigChanged;
					cfg.maxStationDistance.SettingChanged += ExtensionTableConfigChanged;
					ConfigurationManagerAttributes configurationManagerAttributes3 = new ConfigurationManagerAttributes();
					num = order - 1;
					order = num;
					configurationManagerAttributes3.Order = num;
					configurationManagerAttributes3.Browsable = cfg.extensionTable.Value != CraftingTable.None;
					ConfigurationManagerAttributes item = configurationManagerAttributes3;
					hideWhenNoneAttributes2.Add(item);
				}
				List<ConfigurationManagerAttributes> hideWhenNoneAttributes;
				if (piece.Crafting.Stations.Count > 0)
				{
					hideWhenNoneAttributes = new List<ConfigurationManagerAttributes>();
					PieceConfig pieceConfig5 = cfg;
					string group3 = englishName;
					CraftingTable table2 = piece.Crafting.Stations.First().Table;
					string text3 = "Crafting station where " + localizedName + " is available.";
					object[] array3 = new object[1];
					ConfigurationManagerAttributes configurationManagerAttributes4 = new ConfigurationManagerAttributes();
					int num = order - 1;
					order = num;
					configurationManagerAttributes4.Order = num;
					array3[0] = configurationManagerAttributes4;
					pieceConfig5.table = config(group3, "Crafting Station", table2, new ConfigDescription(text3, (AcceptableValueBase)null, array3));
					cfg.customTable = config(englishName, "Custom Crafting Station", piece.Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes }));
					cfg.table.SettingChanged += TableConfigChanged;
					cfg.customTable.SettingChanged += TableConfigChanged;
					ConfigurationManagerAttributes configurationManagerAttributes5 = new ConfigurationManagerAttributes();
					num = order - 1;
					order = num;
					configurationManagerAttributes5.Order = num;
					configurationManagerAttributes5.Browsable = cfg.table.Value != CraftingTable.None;
					ConfigurationManagerAttributes item2 = configurationManagerAttributes5;
					hideWhenNoneAttributes.Add(item2);
				}
				cfg.craft = itemConfig("Crafting Costs", new SerializedRequirements(piece.RequiredItems.Requirements).ToString(), "Item costs to craft " + localizedName);
				cfg.craft.SettingChanged += [<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (Object.op_Implicit((Object)(object)ObjectDB.instance) && (Object)(object)ObjectDB.instance.GetItemPrefab("Wood") != (Object)null)
					{
						Requirement[] resources = SerializedRequirements.toPieceReqs(new SerializedRequirements(cfg.craft.Value));
						piecePrefab.m_resources = resources;
						Piece[] array4 = Object.FindObjectsOfType<Piece>();
						foreach (Piece val in array4)
						{
							if (val.m_name == pieceName)
							{
								val.m_resources = resources;
							}
						}
					}
				};
				void BuildTableConfigChanged(object o, EventArgs e)
				{
					//IL_0059: Unknown result type (might be due to invalid IL or missing references)
					//IL_0037: Unknown result type (might be due to invalid IL or missing references)
					//IL_003c: Unknown result type (might be due to invalid IL or missing references)
					if (registeredPieces.Count > 0)
					{
						if (cfg.category.Value == BuildPieceCategory.Custom)
						{
							piecePrefab.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value);
						}
						else
						{
							piecePrefab.m_category = (PieceCategory)cfg.category.Value;
						}
						if (Object.op_Implicit((Object)(object)Hud.instance))
						{
							PiecePrefabManager.CreateCategoryTabs();
						}
					}
					customTableAttributes.Browsable = cfg.category.Value == BuildPieceCategory.Custom;
					ReloadConfigDisplay();
				}
				void ExtensionTableConfigChanged(object o, EventArgs e)
				{
					if (piece.RequiredItems.Requirements.Count > 0)
					{
						if (cfg.extensionTable.Value == CraftingTable.Custom)
						{
							StationExtension obj2 = pieceExtensionComp;
							GameObject prefab2 = ZNetScene.instance.GetPrefab(cfg.customExtentionTable.Value);
							obj2.m_craftingStation = ((prefab2 != null) ? prefab2.GetComponent<CraftingStation>() : null);
						}
						else
						{
							pieceExtensionComp.m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(cfg.extensionTable.Value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>();
						}
						pieceExtensionComp.m_maxStationDistance = cfg.maxStationDistance.Value;
					}
					customTableAttributes.Browsable = cfg.extensionTable.Value == CraftingTable.Custom;
					foreach (ConfigurationManagerAttributes item5 in hideWhenNoneAttributes2)
					{
						item5.Browsable = cfg.extensionTable.Value != CraftingTable.None;
					}
					ReloadConfigDisplay();
					plugin.Config.Save();
				}
				void TableConfigChanged(object o, EventArgs e)
				{
					if (piece.RequiredItems.Requirements.Count > 0)
					{
						switch (cfg.table.Value)
						{
						case CraftingTable.None:
							piecePrefab.m_craftingStation = null;
							break;
						case CraftingTable.Custom:
						{
							Piece obj = piecePrefab;
							GameObject prefab = ZNetScene.instance.GetPrefab(cfg.customTable.Value);
							obj.m_craftingStation = ((prefab != null) ? prefab.GetComponent<CraftingStation>() : null);
							break;
						}
						default:
							piecePrefab.m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(cfg.table.Value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>();
							break;
						}
					}
					customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom;
					foreach (ConfigurationManagerAttributes item6 in hideWhenNoneAttributes)
					{
						item6.Browsable = cfg.table.Value != CraftingTable.None;
					}
					ReloadConfigDisplay();
					plugin.Config.Save();
				}
				ConfigEntry<string> itemConfig(string name, string value, string desc)
				{
					//IL_0054: Unknown result type (might be due to invalid IL or missing references)
					//IL_005e: Expected O, but got Unknown
					ConfigurationManagerAttributes configurationManagerAttributes6 = new ConfigurationManagerAttributes
					{
						CustomDrawer = DrawConfigTable,
						Order = (order -= 1),
						Category = localizedName
					};
					return config(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes6 }));
				}
			}
			if (saveOnConfigSet)
			{
				plugin.Config.SaveOnConfigSet = true;
				plugin.Config.Save();
			}
			void ReloadConfigDisplay()
			{
				configManagerType?.GetMethod("BuildSettingList").Invoke(configManager, Array.Empty<object>());
			}
		}

		[HarmonyPriority(700)]
		internal static void Patch_ObjectDBInit(ObjectDB __instance)
		{
			if ((Object)(object)__instance.GetItemPrefab("Wood") == (Object)null)
			{
				return;
			}
			foreach (BuildPiece registeredPiece in registeredPieces)
			{
				pieceConfigs.TryGetValue(registeredPiece, out var value);
				registeredPiece.Prefab.GetComponent<Piece>().m_resources = SerializedRequirements.toPieceReqs((value == null) ? new SerializedRequirements(registeredPiece.RequiredItems.Requirements) : new SerializedRequirements(value.craft.Value));
				foreach (ExtensionConfig extensionStation in registeredPiece.Extension.ExtensionStations)
				{
					switch ((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.Table : value.extensionTable.Value)
					{
					case CraftingTable.None:
						registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = null;
						break;
					case CraftingTable.Custom:
					{
						GameObject prefab = ZNetScene.instance.GetPrefab((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.custom : value.customExtentionTable.Value);
						if (prefab != null)
						{
							registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = prefab.GetComponent<CraftingStation>();
						}
						else
						{
							Debug.LogWarning((object)("Custom crafting station '" + ((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.custom : value.customExtentionTable.Value) + "' does not exist"));
						}
						break;
					}
					default:
						if (value != null && value.table.Value == CraftingTable.None)
						{
							registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = null;
						}
						else
						{
							registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.Table : value.extensionTable.Value).ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>();
						}
						break;
					}
				}
				foreach (CraftingStationConfig station in registeredPiece.Crafting.Stations)
				{
					switch ((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.Table : value.table.Value)
					{
					case CraftingTable.None:
						registeredPiece.Prefab.GetComponent<Piece>().m_craftingStation = null;
						break;
					case CraftingTable.Custom:
					{
						GameObject prefab2 = ZNetScene.instance.GetPrefab((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.custom : value.customTable.Value);
						if (prefab2 != null)
						{
							registeredPiece.Prefab.GetComponent<Piece>().m_craftingStation = prefab2.GetComponent<CraftingStation>();
						}
						else
						{
							Debug.LogWarning((object)("Custom crafting station '" + ((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.custom : value.customTable.Value) + "' does not exist"));
						}
						break;
					}
					default:
						if (value != null && value.table.Value == CraftingTable.None)
						{
							registeredPiece.Prefab.GetComponent<Piece>().m_craftingStation = null;
						}
						else
						{
							registeredPiece.Prefab.GetComponent<Piece>().m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.Table : value.table.Value).ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>();
						}
						break;
					}
				}
			}
		}

		public void Snapshot(float lightIntensity = 1.3f, Quaternion? cameraRotation = null)
		{
			SnapshotPiece(Prefab, lightIntensity, cameraRotation);
		}

		internal void SnapshotPiece(GameObject prefab, float lightIntensity = 1.3f, Quaternion? cameraRotation = null)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Expected O, but got Unknown
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0390: Unknown result type (might be due to invalid IL or missing references)
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)prefab == (Object)null) && (prefab.GetComponentsInChildren<Renderer>().Any() || prefab.GetComponentsInChildren<MeshFilter>().Any()))
			{
				Camera component = new GameObject("CameraIcon", new Type[1] { typeof(Camera) }).GetComponent<Camera>();
				component.backgroundColor = Color.clear;
				component.clearFlags = (CameraClearFlags)2;
				((Component)component).transform.position = new Vector3(10000f, 10000f, 10000f);
				((Component)component).transform.rotation = (Quaternion)(((??)cameraRotation) ?? Quaternion.Euler(0f, 180f, 0f));
				component.fieldOfView = 0.5f;
				component.farClipPlane = 100000f;
				component.cullingMask = 8;
				Light component2 = new GameObject("LightIcon", new Type[1] { typeof(Light) }).GetComponent<Light>();
				((Component)component2).transform.position = new Vector3(10000f, 10000f, 10000f);
				((Component)component2).transform.rotation = Quaternion.Euler(5f, 180f, 5f);
				component2.type = (LightType)1;
				component2.cullingMask = 8;
				component2.intensity = lightIntensity;
				GameObject val = Object.Instantiate<GameObject>(prefab);
				Transform[] componentsInChildren = val.GetComponentsInChildren<Transform>();
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Component)componentsInChildren[i]).gameObject.layer = 3;
				}
				val.transform.position = Vector3.zero;
				val.transform.rotation = Quaternion.Euler(23f, 51f, 25.8f);
				((Object)val).name = ((Object)prefab).name;
				MeshRenderer[] componentsInChildren2 = val.GetComponentsInChildren<MeshRenderer>();
				Vector3 val2 = componentsInChildren2.Aggregate(Vector3.positiveInfinity, [<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (Vector3 cur, MeshRenderer renderer) =>
				{
					//IL_0000: Unknown result type (might be due to invalid IL or missing references)
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_000a: Unknown result type (might be due to invalid IL or missing references)
					//IL_000f: Unknown result type (might be due to invalid IL or missing references)
					Bounds bounds2 = ((Renderer)renderer).bounds;
					return Vector3.Min(cur, ((Bounds)(ref bounds2)).min);
				});
				Vector3 val3 = componentsInChildren2.Aggregate(Vector3.negativeInfinity, [<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (Vector3 cur, MeshRenderer renderer) =>
				{
					//IL_0000: Unknown result type (might be due to invalid IL or missing references)
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_000a: Unknown result type (might be due to invalid IL or missing references)
					//IL_000f: Unknown result type (might be due to invalid IL or missing references)
					Bounds bounds = ((Renderer)renderer).bounds;
					return Vector3.Max(cur, ((Bounds)(ref bounds)).max);
				});
				val.transform.position = new Vector3(10000f, 10000f, 10000f) - (val2 + val3) / 2f;
				Vector3 val4 = val3 - val2;
				val.AddComponent<TimedDestruction>().Trigger(1f);
				Rect val5 = default(Rect);
				((Rect)(ref val5))..ctor(0f, 0f, 128f, 128f);
				component.targetTexture = RenderTexture.GetTemporary((int)((Rect)(ref val5)).width, (int)((Rect)(ref val5)).height);
				component.fieldOfView = 20f;
				float num = (Mathf.Max(val4.x, val4.y) + 0.1f) / Mathf.Tan(component.fieldOfView * ((float)Math.PI / 180f)) * 1.1f;
				((Component)component).transform.position = new Vector3(10000f, 10000f, 10000f) + new Vector3(0f, 0f, num);
				component.Render();
				RenderTexture active = RenderTexture.active;
				RenderTexture.active = component.targetTexture;
				Texture2D val6 = new Texture2D((int)((Rect)(ref val5)).width, (int)((Rect)(ref val5)).height, (TextureFormat)4, false);
				val6.ReadPixels(new Rect(0f, 0f, (float)(int)((Rect)(ref val5)).width, (float)(int)((Rect)(ref val5)).height), 0, 0);
				val6.Apply();
				RenderTexture.active = active;
				prefab.GetComponent<Piece>().m_icon = Sprite.Create(val6, new Rect(0f, 0f, (float)(int)((Rect)(ref val5)).width, (float)(int)((Rect)(ref val5)).height), Vector2.one / 2f);
				((Component)component2).gameObject.SetActive(false);
				component.targetTexture.Release();
				((Component)component).gameObject.SetActive(false);
				val.SetActive(false);
				Object.DestroyImmediate((Object)(object)val);
				Object.Destroy((Object)(object)component);
				Object.Destroy((Object)(object)component2);
				Object.Destroy((Object)(object)((Component)component).gameObject);
				Object.Destroy((Object)(object)((Component)component2).gameObject);
			}
		}

		private static void DrawConfigTable(ConfigEntryBase cfg)
		{
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Expected O, but got Unknown
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Expected O, but got Unknown
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Expected O, but got Unknown
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Expected O, but got Unknown
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Expected O, but got Unknown
			bool valueOrDefault = cfg.Description.Tags.Select([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (object a) => (!(a.GetType().Name == "ConfigurationManagerAttributes")) ? null : ((bool?)a.GetType().GetField("ReadOnly")?.GetValue(a))).FirstOrDefault((bool? v) => v.HasValue).GetValueOrDefault();
			List<Requirement> list = new List<Requirement>();
			bool flag = false;
			int num = (int)(configManager?.GetType().GetProperty("RightColumnWidth", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(nonPublic: true)
				.Invoke(configManager, Array.Empty<object>()) ?? ((object)130));
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			foreach (Requirement req in new SerializedRequirements((string)cfg.BoxedValue).Reqs)
			{
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				int num2 = req.amount;
				if (int.TryParse(GUILayout.TextField(num2.ToString(), new GUIStyle(GUI.skin.textField)
				{
					fixedWidth = 40f
				}, Array.Empty<GUILayoutOption>()), out var result) && result != num2 && !valueOrDefault)
				{
					num2 = result;
					flag = true;
				}
				string text = GUILayout.TextField(req.itemName, new GUIStyle(GUI.skin.textField)
				{
					fixedWidth = num - 40 - 67 - 21 - 21 - 12
				}, Array.Empty<GUILayoutOption>());
				string text2 = (valueOrDefault ? req.itemName : text);
				flag = flag || text2 != req.itemName;
				bool flag2 = req.recover;
				if (GUILayout.Toggle(req.recover, "Recover", new GUIStyle(GUI.skin.toggle)
				{
					fixedWidth = 67f
				}, Array.Empty<GUILayoutOption>()) != req.recover)
				{
					flag2 = !flag2;
					flag = true;
				}
				if (GUILayout.Button("x", new GUIStyle(GUI.skin.button)
				{
					fixedWidth = 21f
				}, Array.Empty<GUILayoutOption>()) && !valueOrDefault)
				{
					flag = true;
				}
				else
				{
					list.Add(new Requirement
					{
						amount = num2,
						itemName = text2,
						recover = flag2
					});
				}
				if (GUILayout.Button("+", new GUIStyle(GUI.skin.button)
				{
					fixedWidth = 21f
				}, Array.Empty<GUILayoutOption>()) && !valueOrDefault)
				{
					flag = true;
					list.Add(new Requirement
					{
						amount = 1,
						itemName = "",
						recover = false
					});
				}
				GUILayout.EndHorizontal();
			}
			GUILayout.EndVertical();
			if (flag)
			{
				cfg.BoxedValue = new SerializedRequirements(list).ToString();
			}
		}

		private static ConfigEntry<T> config<[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)] T>(string group, string name, T value, ConfigDescription description)
		{
			ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description);
			configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T))
				.Invoke(configSync, new object[1] { val });
			return val;
		}

		private static ConfigEntry<T> config<[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)] T>(string group, string name, T value, string description)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	public static class GoExtensions
	{
		[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
		public static T GetOrAddComponent<[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)] T>(this GameObject gameObject) where T : Component
		{
			return gameObject.GetComponent<T>() ?? gameObject.AddComponent<T>();
		}
	}
	[PublicAPI]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	public class LocalizeKey
	{
		private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

		public readonly string Key;

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

		public LocalizeKey(string key)
		{
			Key = key.Replace("$", "");
		}

		public void Alias(string alias)
		{
			Localizations.Clear();
			if (!alias.Contains("$"))
			{
				alias = "$" + alias;
			}
			Localizations["alias"] = alias;
			Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
		}

		public LocalizeKey English(string key)
		{
			return addForLang("English", key);
		}

		public LocalizeKey Swedish(string key)
		{
			return addForLang("Swedish", key);
		}

		public LocalizeKey French(string key)
		{
			return addForLang("French", key);
		}

		public LocalizeKey Italian(string key)
		{
			return addForLang("Italian", key);
		}

		public LocalizeKey German(string key)
		{
			return addForLang("German", key);
		}

		public LocalizeKey Spanish(string key)
		{
			return addForLang("Spanish", key);
		}

		public LocalizeKey Russian(string key)
		{
			return addForLang("Russian", key);
		}

		public LocalizeKey Romanian(string key)
		{
			return addForLang("Romanian", key);
		}

		public LocalizeKey Bulgarian(string key)
		{
			return addForLang("Bulgarian", key);
		}

		public LocalizeKey Macedonian(string key)
		{
			return addForLang("Macedonian", key);
		}

		public LocalizeKey Finnish(string key)
		{
			return addForLang("Finnish", key);
		}

		public LocalizeKey Danish(string key)
		{
			return addForLang("Danish", key);
		}

		public LocalizeKey Norwegian(string key)
		{
			return addForLang("Norwegian", key);
		}

		public LocalizeKey Icelandic(string key)
		{
			return addForLang("Icelandic", key);
		}

		public LocalizeKey Turkish(string key)
		{
			return addForLang("Turkish", key);
		}

		public LocalizeKey Lithuanian(string key)
		{
			return addForLang("Lithuanian", key);
		}

		public LocalizeKey Czech(string key)
		{
			return addForLang("Czech", key);
		}

		public LocalizeKey Hungarian(string key)
		{
			return addForLang("Hungarian", key);
		}

		public LocalizeKey Slovak(string key)
		{
			return addForLang("Slovak", key);
		}

		public LocalizeKey Polish(string key)
		{
			return addForLang("Polish", key);
		}

		public LocalizeKey Dutch(string key)
		{
			return addForLang("Dutch", key);
		}

		public LocalizeKey Portuguese_European(string key)
		{
			return addForLang("Portuguese_European", key);
		}

		public LocalizeKey Portuguese_Brazilian(string key)
		{
			return addForLang("Portuguese_Brazilian", key);
		}

		public LocalizeKey Chinese(string key)
		{
			return addForLang("Chinese", key);
		}

		public LocalizeKey Japanese(string key)
		{
			return addForLang("Japanese", key);
		}

		public LocalizeKey Korean(string key)
		{
			return addForLang("Korean", key);
		}

		public LocalizeKey Hindi(string key)
		{
			return addForLang("Hindi", key);
		}

		public LocalizeKey Thai(string key)
		{
			return addForLang("Thai", key);
		}

		public LocalizeKey Abenaki(string key)
		{
			return addForLang("Abenaki", key);
		}

		public LocalizeKey Croatian(string key)
		{
			return addForLang("Croatian", key);
		}

		public LocalizeKey Georgian(string key)
		{
			return addForLang("Georgian", key);
		}

		public LocalizeKey Greek(string key)
		{
			return addForLang("Greek", key);
		}

		public LocalizeKey Serbian(string key)
		{
			return addForLang("Serbian", key);
		}

		public LocalizeKey Ukrainian(string key)
		{
			return addForLang("Ukrainian", key);
		}

		private LocalizeKey addForLang(string lang, string value)
		{
			Localizations[lang] = value;
			if (Localization.instance.GetSelectedLanguage() == lang)
			{
				Localization.instance.AddWord(Key, value);
			}
			else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
			{
				Localization.instance.AddWord(Key, value);
			}
			return this;
		}

		[HarmonyPriority(300)]
		internal static void AddLocalizedKeys(Localization __instance, string language)
		{
			foreach (LocalizeKey key in keys)
			{
				string value2;
				if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value))
				{
					__instance.AddWord(key.Key, value);
				}
				else if (key.Localizations.TryGetValue("alias", out value2))
				{
					Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
				}
			}
		}
	}
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	public static class LocalizationCache
	{
		private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

		internal static void LocalizationPostfix(Localization __instance, string language)
		{
			string key = localizations.FirstOrDefault([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key;
			if (key != null)
			{
				localizations.Remove(key);
			}
			if (!localizations.ContainsKey(language))
			{
				localizations.Add(language, __instance);
			}
		}

		public static Localization ForLanguage([<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)] string language = null)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value))
			{
				return value;
			}
			value = new Localization();
			if (language != null)
			{
				value.SetupLanguage(language);
			}
			return value;
		}
	}
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	public class AdminSyncing
	{
		private static bool isServer;

		internal static bool registeredOnClient;

		[HarmonyPriority(700)]
		internal static void AdminStatusSync(ZNet __instance)
		{
			isServer = __instance.IsServer();
			if (BuildPiece._plugin != null)
			{
				if (isServer)
				{
					ZRoutedRpc.instance.Register<ZPackage>(BuildPiece._plugin.Info.Metadata.Name + " PMAdminStatusSync", (Action<long, ZPackage>)RPC_AdminPieceAddRemove);
				}
				else if (!registeredOnClient)
				{
					ZRoutedRpc.instance.Register<ZPackage>(BuildPiece._plugin.Info.Metadata.Name + " PMAdminStatusSync", (Action<long, ZPackage>)RPC_AdminPieceAddRemove);
					registeredOnClient = true;
				}
			}
			if (isServer)
			{
				((MonoBehaviour)ZNet.instance).StartCoroutine(WatchAdminListChanges());
			}
			static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Expected O, but got Unknown
				ZPackage val = new ZPackage();
				val.Write(isAdmin);
				((MonoBehaviour)ZNet.instance).StartCoroutine(sendZPackage(peers, val));
			}
			static IEnumerator WatchAdminListChanges()
			{
				List<string> currentList = new List<string>(ZNet.instance.m_adminList.GetList());
				while (true)
				{
					yield return (object)new WaitForSeconds(30f);
					if (!ZNet.instance.m_adminList.GetList().SequenceEqual(currentList))
					{
						currentList = new List<string>(ZNet.instance.m_adminList.GetList());
						List<ZNetPeer> list = (from p in ZNet.instance.GetPeers()
							where ZNet.instance.ListContainsId(ZNet.instance.m_adminList, p.m_rpc.GetSocket().GetHostName())
							select p).ToList();
						SendAdmin(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false);
						SendAdmin(list, isAdmin: true);
					}
				}
			}
		}

		private static IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] array = package.GetArray();
			if (array != null && array.LongLength > 10000)
			{
				ZPackage val = new ZPackage();
				val.Write(4);
				MemoryStream memoryStream = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal))
				{
					deflateStream.Write(array, 0, array.Length);
				}
				val.Write(memoryStream.ToArray());
				package = val;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select TellPeerAdminStatus(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private static IEnumerator<bool> TellPeerAdminStatus(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc != null)
			{
				SendPackage(package);
			}
			void SendPackage(ZPackage pkg)
			{
				BaseUnityPlugin plugin = BuildPiece._plugin;
				string text = ((plugin != null) ? plugin.Info.Metadata.Name : null) + " PMAdminStatusSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			yield break;
		}

		internal static void RPC_AdminPieceAddRemove(long sender, ZPackage package)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			ZNetPeer peer = ZNet.instance.GetPeer(sender);
			bool flag = false;
			try
			{
				flag = package.ReadBool();
			}
			catch
			{
			}
			if (isServer)
			{
				ZRoutedRpc instance = ZRoutedRpc.instance;
				long everybody = ZRoutedRpc.Everybody;
				BaseUnityPlugin plugin = BuildPiece._plugin;
				instance.InvokeRoutedRPC(everybody, ((plugin != null) ? plugin.Info.Metadata.Name : null) + " PMAdminStatusSync", new object[1] { (object)new ZPackage() });
				if (ZNet.instance.ListContainsId(ZNet.instance.m_adminList, peer.m_rpc.GetSocket().GetHostName()))
				{
					ZPackage val = new ZPackage();
					val.Write(true);
					ZRpc rpc = peer.m_rpc;
					BaseUnityPlugin plugin2 = BuildPiece._plugin;
					rpc.Invoke(((plugin2 != null) ? plugin2.Info.Metadata.Name : null) + " PMAdminStatusSync", new object[1] { val });
				}
				return;
			}
			foreach (BuildPiece registeredPiece in BuildPiece.registeredPieces)
			{
				if (!registeredPiece.SpecialProperties.AdminOnly)
				{
					continue;
				}
				Piece component = registeredPiece.Prefab.GetComponent<Piece>();
				string name = component.m_name;
				Localization.instance.Localize(name).Trim();
				if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || (Object)(object)ObjectDB.instance.GetItemPrefab("Wood") == (Object)null)
				{
					continue;
				}
				Piece[] array = Object.FindObjectsOfType<Piece>();
				foreach (Piece val2 in array)
				{
					if (flag)
					{
						if (val2.m_name == name)
						{
							val2.m_enabled = true;
						}
					}
					else if (val2.m_name == name)
					{
						val2.m_enabled = false;
					}
				}
				List<GameObject> pieces = ObjectDB.instance.GetItemPrefab("Hammer").GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces.m_pieces;
				if (flag)
				{
					if (!pieces.Contains(ZNetScene.instance.GetPrefab(((Object)component).name)))
					{
						pieces.Add(ZNetScene.instance.GetPrefab(((Object)component).name));
					}
				}
				else if (pieces.Contains(ZNetScene.instance.GetPrefab(((Object)component).name)))
				{
					pieces.Remove(ZNetScene.instance.GetPrefab(((Object)component).name));
				}
			}
		}
	}
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	internal class RegisterClientRPCPatch
	{
		private static void Postfix(ZNet __instance, ZNetPeer peer)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			if (!__instance.IsServer())
			{
				ZRpc rpc = peer.m_rpc;
				BaseUnityPlugin plugin = BuildPiece._plugin;
				rpc.Register<ZPackage>(((plugin != null) ? plugin.Info.Metadata.Name : null) + " PMAdminStatusSync", (Action<ZRpc, ZPackage>)RPC_InitialAdminSync);
				return;
			}
			ZPackage val = new ZPackage();
			val.Write(__instance.ListContainsId(__instance.m_adminList, peer.m_rpc.GetSocket().GetHostName()));
			ZRpc rpc2 = peer.m_rpc;
			BaseUnityPlugin plugin2 = BuildPiece._plugin;
			rpc2.Invoke(((plugin2 != null) ? plugin2.Info.Metadata.Name : null) + " PMAdminStatusSync", new object[1] { val });
		}

		private static void RPC_InitialAdminSync(ZRpc rpc, ZPackage package)
		{
			AdminSyncing.RPC_AdminPieceAddRemove(0L, package);
		}
	}
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	public static class PiecePrefabManager
	{
		[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
		private struct BundleId
		{
			[UsedImplicitly]
			public string assetBundleFileName;

			[UsedImplicitly]
			public string folderName;
		}

		private static readonly Dictionary<BundleId, AssetBundle> bundleCache;

		private static readonly List<GameObject> piecePrefabs;

		private static readonly Dictionary<string, PieceCategory> PieceCategories;

		private static readonly Dictionary<string, PieceCategory> OtherPieceCategories;

		private static string hiddenCategoryMagic;

		static PiecePrefabManager()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			//IL_0145: Expected O, but got Unknown
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Expected O, but got Unknown
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Expected O, but got Unknown
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Expected O, but got Unknown
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Expected O, but got Unknown
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Expected O, but got Unknown
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Expected O, but got Unknown
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_0325: Expected O, but got Unknown
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Unknown result type (might be due to invalid IL or missing references)
			//IL_0361: Expected O, but got Unknown
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			//IL_0390: Unknown result type (might be due to invalid IL or missing references)
			//IL_039d: Expected O, but got Unknown
			//IL_039e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d9: Expected O, but got Unknown
			//IL_03da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0408: Unknown result type (might be due to invalid IL or missing references)
			//IL_0415: Expected O, but got Unknown
			//IL_0416: Unknown result type (might be due to invalid IL or missing references)
			//IL_0444: Unknown result type (might be due to invalid IL or missing references)
			//IL_0451: Expected O, but got Unknown
			//IL_0452: Unknown result type (might be due to invalid IL or missing references)
			//IL_0480: Unknown result type (might be due to invalid IL or missing references)
			//IL_048d: Expected O, but got Unknown
			//IL_048e: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c9: Expected O, but got Unknown
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Expected O, but got Unknown
			bundleCache = new Dictionary<BundleId, AssetBundle>();
			piecePrefabs = new List<GameObject>();
			PieceCategories = new Dictionary<string, PieceCategory>();
			OtherPieceCategories = new Dictionary<string, PieceCategory>();
			hiddenCategoryMagic = "(HiddenCategory)";
			Harmony val = new Harmony("org.bepinex.helpers.PieceManager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(BuildPiece), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_ZNetSceneAwake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "UpdateAvailable", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "UpdateAvailable_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "UpdateAvailable", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "UpdateAvailable_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "UpdateAvailable_Postfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "NextCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "NextCategory_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "PrevCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "PrevCategory_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "SetCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "SetCategory_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Hud), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Hud_AwakeCreateTabs", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Enum), "GetValues", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "EnumGetValuesPatch", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Enum), "GetNames", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "EnumGetNamesPatch", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "RefFixPatch_ZNetSceneAwake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(AdminSyncing), "AdminStatusSync", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "CopyOtherDB", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(BuildPiece), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "PrevCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_PieceTable_PrevCategory", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "NextCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_PieceTable_NextCategory", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Player), "SetPlaceMode", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_SetPlaceMode", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		public static AssetBundle RegisterAssetBundle(string assetBundleFileName, string folderName = "assets")
		{
			BundleId bundleId = default(BundleId);
			bundleId.assetBundleFileName = assetBundleFileName;
			bundleId.folderName = folderName;
			BundleId key = bundleId;
			if (!bundleCache.TryGetValue(key, out var value))
			{
				Dictionary<BundleId, AssetBundle> dictionary = bundleCache;
				AssetBundle? obj = ((IEnumerable<AssetBundle>)Resources.FindObjectsOfTypeAll<AssetBundle>()).FirstOrDefault((Func<AssetBundle, bool>)([<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)] (AssetBundle a) => ((Object)a).name == assetBundleFileName)) ?? AssetBundle.LoadFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + folderName + "." + assetBundleFileName));
				AssetBundle result = obj;
				dictionary[key] = obj;
				return result;
			}
			return value;
		}

		public static IEnumerable<GameObject> FixRefs(AssetBundle assetBundle)
		{
			return assetBundle.LoadAllAssets<GameObject>();
		}

		public static GameObject RegisterPrefab(string assetBundleFileName, string prefabName, string folderName = "assets")
		{
			return RegisterPrefab(RegisterAssetBundle(assetBundleFileName, folderName), prefabName);
		}

		public static GameObject RegisterPrefab(AssetBundle assets, string prefabName)
		{
			GameObject val = assets.LoadAsset<GameObject>(prefabName);
			piecePrefabs.Add(val);
			return val;
		}

		public static Sprite RegisterSprite(string assetBundleFileName, string prefabName, string folderName = "assets")
		{
			return RegisterSprite(RegisterAssetBundle(assetBundleFileName, folderName), prefabName);
		}

		public static Sprite RegisterSprite(AssetBundle assets, string prefabName)
		{
			return assets.LoadAsset<Sprite>(prefabName);
		}

		private static void EnumGetValuesPatch(Type enumType, ref Array __result)
		{
			if (!(enumType != typeof(PieceCategory)) && PieceCategories.Count != 0)
			{
				PieceCategory[] array = (PieceCategory[])(object)new PieceCategory[__result.Length + PieceCategories.Count];
				__result.CopyTo(array, 0);
				PieceCategories.Values.CopyTo(array, __result.Length);
				__result = array;
			}
		}

		private static void EnumGetNamesPatch(Type enumType, ref string[] __result)
		{
			if (!(enumType != typeof(PieceCategory)) && PieceCategories.Count != 0)
			{
				__result = CollectionExtensions.AddRangeToArray<string>(__result, PieceCategories.Keys.ToArray());
			}
		}

		public static Dictionary<PieceCategory, string> GetPieceCategoriesMap()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			Array values = Enum.GetValues(typeof(PieceCategory));
			string[] names = Enum.GetNames(typeof(PieceCategory));
			Dictionary<PieceCategory, string> dictionary = new Dictionary<PieceCategory, string>();
			for (int i = 0; i < values.Length; i++)
			{
				dictionary[(PieceCategory)values.GetValue(i)] = names[i];
			}
			return dictionary;
		}

		public static PieceCategory GetCategory(string name)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			if (Enum.TryParse<PieceCategory>(name, ignoreCase: true, out PieceCategory result))
			{
				return result;
			}
			if (PieceCategories.TryGetValue(name, out result))
			{
				return result;
			}
			if (OtherPieceCategories.TryGetValue(name, out result))
			{
				return result;
			}
			Dictionary<PieceCategory, string> pieceCategoriesMap = GetPieceCategoriesMap();
			foreach (KeyValuePair<PieceCategory, string> item in pieceCategoriesMap)
			{
				if (item.Value == name)
				{
					result = item.Key;
					OtherPieceCategories[name] = result;
					return result;
				}
			}
			result = (PieceCategory)(pieceCategoriesMap.Count - 1);
			PieceCategories[name] = result;
			string categoryToken = GetCategoryToken(name);
			Localization.instance.AddWord(categoryToken, name);
			return result;
		}

		internal static void CreateCategoryTabs()
		{
			int num = MaxCategory();
			for (int i = Hud.instance.m_buildCategoryNames.Count; i < num; i++)
			{
				Hud.instance.m_buildCategoryNames.Add("");
			}
			for (int j = Hud.instance.m_pieceCategoryTabs.Length; j < num; j++)
			{
				GameObject val = CreateCategoryTab();
				Hud.instance.m_pieceCategoryTabs = CollectionExtensions.AddItem<GameObject>((IEnumerable<GameObject>)Hud.instance.m_pieceCategoryTabs, val).ToArray();
			}
			if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces))
			{
				RepositionCategories(Player.m_localPlayer.m_buildPieces);
				Player.m_localPlayer.UpdateAvailablePiecesList();
			}
		}

		private static GameObject CreateCategoryTab()
		{
			//IL_0073: 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)
			Transform transform = Hud.instance.m_pieceCategoryRoot.transform;
			GameObject val = Object.Instantiate<GameObject>(Hud.instance.m_pieceCategoryTabs[0], transform);
			val.SetActive(false);
			UIInputHandler orAddComponent = val.GetOrAddComponent<UIInputHandler>();
			orAddComponent.m_onLeftDown = (Action<UIInputHandler>)Delegate.Combine(orAddComponent.m_onLeftDown, new Action<UIInputHandler>(Hud.instance.OnLeftClickCategory));
			Text[] componentsInChildren = val.GetComponentsInChildren<Text>();
			foreach (Text obj in componentsInChildren)
			{
				((Graphic)obj).rectTransform.offsetMin = new Vector2(3f, 1f);
				((Graphic)obj).rectTransform.offsetMax = new Vector2(-3f, -1f);
				obj.resizeTextForBestFit = true;
				obj.resizeTextMinSize = 12;
				obj.resizeTextMaxSize = 20;
				obj.lineSpacing = 0.8f;
				obj.horizontalOverflow = (HorizontalWrapMode)0;
				obj.verticalOverflow = (VerticalWrapMode)0;
			}
			return val;
		}

		private static int MaxCategory()
		{
			return Enum.GetValues(typeof(PieceCategory)).Length - 1;
		}

		private static List<CodeInstruction> TranspileMaxCategory(IEnumerable<CodeInstruction> instructions, int maxOffset)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			int num = 4 + maxOffset;
			List<CodeInstruction> list = new List<CodeInstruction>();
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.LoadsConstant(instruction, (long)num))
				{
					list.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "MaxCategory", (Type[])null, (Type[])null)));
					if (maxOffset != 0)
					{
						list.Add(new CodeInstruction(OpCodes.Ldc_I4, (object)maxOffset));
						list.Add(new CodeInstruction(OpCodes.Add, (object)null));
					}
				}
				else
				{
					list.Add(instruction);
				}
			}
			return list;
		}

		private static IEnumerable<CodeInstruction> NextCategory_Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return TranspileMaxCategory(instructions, 0);
		}

		private static IEnumerable<CodeInstruction> PrevCategory_Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return TranspileMaxCategory(instructions, -1);
		}

		private static IEnumerable<CodeInstruction> SetCategory_Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return TranspileMaxCategory(instructions, -1);
		}

		private static IEnumerable<CodeInstruction> UpdateAvailable_Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return TranspileMaxCategory(instructions, 0);
		}

		private static HashSet<PieceCategory> CategoriesInPieceTable(PieceTable pieceTable)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			HashSet<PieceCategory> hashSet = new HashSet<PieceCategory>();
			foreach (GameObject piece in pieceTable.m_pieces)
			{
				hashSet.Add(piece.GetComponent<Piece>().m_category);
			}
			return hashSet;
		}

		private static void RepositionCategories(PieceTable pieceTable)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Invalid comparison between Unknown and I4
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: 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_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Expected O, but got Unknown
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Invalid comparison between Unknown and I4
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Expected I4, but got Unknown
			RectTransform val = (RectTransform)Hud.instance.m_pieceCategoryTabs[0].transform;
			RectTransform val2 = (RectTransform)Hud.instance.m_pieceCategoryRoot.transform;
			RectTransform val3 = (RectTransform)Hud.instance.m_pieceSelectionWindow.transform;
			Rect rect = val.rect;
			Vector2 size = ((Rect)(ref rect)).size;
			HashSet<PieceCategory> hashSet = CategoriesInPieceTable(pieceTable);
			Dictionary<PieceCategory, string> pieceCategoriesMap = GetPieceCategoriesMap();
			bool flag = hashSet.Count == 1 && (int)hashSet.First() == 0;
			pieceTable.m_useCategories = !flag;
			rect = val2.rect;
			int num = Mathf.Max((int)(((Rect)(ref rect)).width / size.x), 1);
			int num2 = VisibleTabCount(hashSet);
			float num3 = (0f - size.x) * (float)num / 2f + size.x / 2f;
			float num4 = (size.y + 1f) * Mathf.Floor((float)(num2 - 1) / (float)num) + 5f;
			Vector2 val4 = default(Vector2);
			((Vector2)(ref val4))..ctor(num3, num4);
			int num5 = 0;
			for (int i = 0; i < Hud.instance.m_pieceCategoryTabs.Length; i++)
			{
				GameObject val5 = Hud.instance.m_pieceCategoryTabs[i];
				string text = pieceCategoriesMap[(PieceCategory)i];
				bool flag2 = hashSet.Contains((PieceCategory)i);
				SetTabActive(val5, text, flag2);
				if (flag2)
				{
					RectTransform component = val5.GetComponent<RectTransform>();
					float num6 = size.x * (float)(num5 % num);
					float num7 = (0f - (size.y + 1f)) * Mathf.Floor((float)num5 / (float)num);
					component.anchoredPosition = val4 + new Vector2(num6, num7);
					component.anchorMin = new Vector2(0.5f, 0f);
					component.anchorMax = new Vector2(0.5f, 1f);
					num5++;
				}
				if (PieceCategories.ContainsKey(text))
				{
					Hud.instance.m_buildCategoryNames[i] = "$" + GetCategoryToken(text);
				}
			}
			Transform obj = ((Transform)val3).Find("Bkg2");
			RectTransform val6 = (RectTransform)((obj != null) ? ((Component)obj).transform : null);
			if (Object.op_Implicit((Object)(object)val6))
			{
				float num8 = (size.y + 1f) * (float)Mathf.Max(0, Mathf.FloorToInt((float)(num5 - 1) / (float)num));
				val6.offsetMax = new Vector2(val6.offsetMax.x, num8);
			}
			else
			{
				Debug.LogWarning((object)"RefreshCategories: Could not find background image");
			}
			if ((int)Player.m_localPlayer.m_buildPieces.m_selectedCategory >= Hud.instance.m_buildCategoryNames.Count)
			{
				Player.m_localPlayer.m_buildPieces.SetCategory((int)hashSet.First());
			}
			((Component)Hud.instance).GetComponentInParent<Localize>().RefreshLocalization();
		}

		private static int VisibleTabCount(HashSet<PieceCategory> visibleCategories)
		{
			int num = 0;
			for (int i = 0; i < Hud.instance.m_pieceCategoryTabs.Length; i++)
			{
				if (visibleCategories.Contains((PieceCategory)i))
				{
					num++;
				}
			}
			return num;
		}

		private static void SetTabActive(GameObject tab, string tabName, bool active)
		{
			tab.SetActive(active);
			if (active)
			{
				((Object)tab).name = tabName.Replace(hiddenCategoryMagic, "");
			}
			else
			{
				((Object)tab).name = tabName + hiddenCategoryMagic;
			}
		}

		private static string GetCategoryToken(string name)
		{
			char[] endChars = Localization.instance.m_endChars;
			string text = string.Concat(name.ToLower().Split(endChars));
			return "piecemanager_cat_" + text;
		}

		private static void Patch_SetPlaceMode(Player __instance)
		{
			if (Object.op_Implicit((Object)(object)__instance.m_buildPieces))
			{
				RepositionCategories(__instance.m_buildPieces);
			}
		}

		private static void Patch_PieceTable_NextCategory(PieceTable __instance)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_pieces.Count != 0 && __instance.m_useCategories && ((Object)Hud.instance.m_pieceCategoryTabs[__instance.m_selectedCategory]).name.Contains(hiddenCategoryMagic))
			{
				__instance.NextCategory();
			}
		}

		private static void Patch_PieceTable_PrevCategory(PieceTable __instance)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.m_pieces.Count != 0 && __instance.m_useCategories && ((Object)Hud.instance.m_pieceCategoryTabs[__instance.m_selectedCategory]).name.Contains(hiddenCategoryMagic))
			{
				__instance.PrevCategory();
			}
		}

		private static void UpdateAvailable_Prefix(PieceTable __instance)
		{
			if (__instance.m_availablePieces.Count > 0)
			{
				int num = MaxCategory() - __instance.m_availablePieces.Count;
				for (int i = 0; i < num; i++)
				{
					__instance.m_availablePieces.Add(new List<Piece>());
				}
			}
		}

		private static void UpdateAvailable_Postfix(PieceTable __instance)
		{
			Array.Resize(ref __instance.m_selectedPiece, __instance.m_availablePieces.Count);
			Array.Resize(ref __instance.m_lastSelectedPiece, __instance.m_availablePieces.Count);
		}

		[HarmonyPriority(200)]
		private static void Hud_AwakeCreateTabs()
		{
			CreateCategoryTabs();
		}

		[HarmonyPriority(700)]
		private static void Patch_ZNetSceneAwake(ZNetScene __instance)
		{
			foreach (GameObject piecePrefab in piecePrefabs)
			{
				if (!__instance.m_prefabs.Contains(piecePrefab))
				{
					__instance.m_prefabs.Add(piecePrefab);
				}
			}
		}

		[HarmonyPriority(700)]
		private static void RefFixPatch_ZNetSceneAwake(ZNetScene __instance)
		{
			//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)
			foreach (GameObject piecePrefab in piecePrefabs)
			{
				if (__instance.m_prefabs.Contains(piecePrefab) && Object.op_Implicit((Object)(object)piecePrefab.GetComponent<StationExtension>()))
				{
					piecePrefab.GetComponent<Piece>().m_isUpgrade = true;
					piecePrefab.GetComponent<StationExtension>().m_connectionPrefab = __instance.GetPrefab("piece_workbench_ext3").GetComponent<StationExtension>().m_connectionPrefab;
					piecePrefab.GetComponent<StationExtension>().m_connectionOffset = __instance.GetPrefab("piece_workbench_ext3").GetComponent<StationExtension>().m_connectionOffset;
				}
			}
		}

		[HarmonyPriority(300)]
		private static void Patch_ObjectDBInit(ObjectDB __instance)
		{
			foreach (BuildPiece registeredPiece in BuildPiece.registeredPieces)
			{
				string[] activeTools = registeredPiece.activeTools;
				foreach (string text in activeTools)
				{
					GameObject itemPrefab = __instance.GetItemPrefab(text);
					PieceTable val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces : null);
					if (val != null && !val.m_pieces.Contains(registeredPiece.Prefab))
					{
						val.m_pieces.Add(registeredPiece.Prefab);
					}
				}
			}
		}
	}
}
namespace CraftyCartsRemake
{
	[BepInPlugin("Azumatt.CraftyCarts", "CraftyCarts", "3.1.0")]
	[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(0)]
	[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
	public class CCR : BaseUnityPlugin
	{
		[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			public bool? Browsable = false;
		}

		[HarmonyPatch(typeof(CraftingStation), "Start")]
		[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)]
		private static class CraftingStation_Start_Patch
		{
			[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
			private static void Postfix(CraftingStation __instance, ref List<CraftingStation> ___m_allStations)
			{
				switch (((Object)__instance).name)
				{
				case "forge_cart_craftingstation":
				case "stone_cart_craftingstation":
				case "workbench_cart_craftingstation":
					if (!___m_allStations.Contains(__instance))
					{
						___m_allStations.Add(__instance);
					}
					break;
				}
			}
		}

		[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)]
		[HarmonyPatch(typeof(CraftingStation), "FixedUpdate")]
		private static class CCRCraftingStation_FixedUpdate_Patch
		{
			[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
			private static void Postfix(CraftingStation __instance, ref float ___m_useTimer, ref float ___m_updateExtensionTimer, GameObject ___m_inUseObject)
			{
				switch (((Object)__instance).name)
				{
				case "forge_cart_craftingstation":
				case "stone_cart_craftingstation":
				case "workbench_cart_craftingstation":
					___m_useTimer += Time.fixedDeltaTime;
					___m_updateExtensionTimer += Time.fixedDeltaTime;
					if (Object.op_Implicit((Object)(object)___m_inUseObject))
					{
						___m_inUseObject.SetActive(___m_useTimer < 1f);
					}
					break;
				}
			}
		}

		[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(0)]
		[HarmonyPatch(typeof(Container), "Awake")]
		private static class Container_Awake_Patch
		{
			[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
			private static void Postfix(Container __instance, ref Inventory ___m_inventory)
			{
				if (__instance.m_nview.GetZDO() != null)
				{
					string text = ((Object)((Component)__instance).transform.root).name.Replace("(Clone)", "").Trim();
					ref int width = ref ___m_inventory.m_width;
					ref int height = ref ___m_inventory.m_height;
					switch (text)
					{
					case "forge_cart":
						height = ForgeCartRow.Value;
						width = ForgeCartCol.Value;
						break;
					case "stone_cart":
						height = StonecutterCartRow.Value;
						width = StonecutterCartCol.Value;
						break;
					case "workbench_cart":
						height = WorkbenchCartRow.Value;
						width = WorkbenchCartCol.Value;
						break;
					}
				}
			}
		}

		public const string ModVersion = "3.1.0";

		public const string ModGUID = "Azumatt.CraftyCarts";

		public const string Author = "Azumatt";

		public const string ModName = "CraftyCarts";

		private readonly Harmony _harmony = new Harmony("Azumatt.CraftyCarts");

		internal static string ConnectionError = "";

		internal static BuildPiece ForgeCart = null;

		internal static BuildPiece StoneCart = null;

		internal static BuildPiece WorkbenchCart = null;

		internal const string ForgeCartFabName = "forge_cart";

		internal const string StoneCartFabName = "stone_cart";

		internal const string WorkbenchCartFabName = "workbench_cart";

		internal const string ForgeCartInstance = "forge_cart_craftingstation";

		internal const string StoneCartInstance = "stone_cart_craftingstation";

		internal const string WorkbenchCartInstance = "workbench_cart_craftingstation";

		private const string ConfigFileName = "Azumatt.CraftyCarts.cfg";

		private static readonly string ConfigFileFullPath;

		public static readonly ManualLogSource CCRLogger;

		private static readonly ConfigSync ConfigSync;

		public static ConfigEntry<int> ForgeCartRow;

		public static ConfigEntry<int> ForgeCartCol;

		public static ConfigEntry<int> StonecutterCartRow;

		public static ConfigEntry<int> StonecutterCartCol;

		public static ConfigEntry<int> WorkbenchCartRow;

		public static ConfigEntry<int> WorkbenchCartCol;

		public void Awake()
		{
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Expected O, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Expected O, but got Unknown
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Expected O, but got Unknown
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Expected O, but got Unknown
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Expected O, but got Unknown
			//IL_0285: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Expected O, but got Unknown
			ConfigSync.IsLocked = true;
			ForgeCart = new BuildPiece("craftycarts", "forge_cart");
			ForgeCart.Description.English("Mobile Forge");
			ForgeCart.RequiredItems.Add("Stone", 4, recover: true);
			ForgeCart.RequiredItems.Add("Coal", 4, recover: true);
			ForgeCart.RequiredItems.Add("Wood", 10, recover: true);
			ForgeCart.RequiredItems.Add("Copper", 6, recover: true);
			ForgeCart.Category.Set("Crafty Carts");
			StoneCart = new BuildPiece("craftycarts", "stone_cart");
			StoneCart.Description.English("Mobile Stone Cutter");
			StoneCart.RequiredItems.Add("Wood", 10, recover: true);
			StoneCart.RequiredItems.Add("Iron", 2, recover: true);
			StoneCart.RequiredItems.Add("Stone", 4, recover: true);
			StoneCart.Category.Set("Crafty Carts");
			WorkbenchCart = new BuildPiece("craftycarts", "workbench_cart");
			WorkbenchCart.Description.English("Mobile Workbench");
			WorkbenchCart.RequiredItems.Add("Wood", 10, recover: true);
			WorkbenchCart.Category.Set("Crafty Carts");
			ForgeCartRow = config("Forge Cart", "Inventory Rows", 5, new ConfigDescription("Rows for Forge", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 30), Array.Empty<object>()));
			ForgeCartCol = config("Forge Cart", "Inventory Columns", 8, new ConfigDescription("Columns for Forge", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 8), Array.Empty<object>()));
			WorkbenchCartRow = config("Workbench Cart", "Inventory Rows", 5, new ConfigDescription("Rows for Workbench", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 30), Array.Empty<object>()));
			WorkbenchCartCol = config("Workbench Cart", "Inventory Columns", 8, new ConfigDescription("Columns for Workbench", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 8), Array.Empty<object>()));
			StonecutterCartRow = config("Stonecutter Cart", "Inventory Rows", 5, new ConfigDescription("Rows for Stonecutter", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 30), Array.Empty<object>()));
			StonecutterCartCol = config("Stonecutter Cart", "Inventory Columns", 8, new ConfigDescription("Columns for Stonecutter", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 8), Array.Empty<object>()));
			_harmony.PatchAll();
			SetupWatcher();
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		private void SetupWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, "Azumatt.CraftyCarts.cfg");
			fileSystemWatcher.Changed += ReadConfigValues;
			fileSystemWatcher.Created += ReadConfigValues;
			fileSystemWatcher.Renamed += ReadConfigValues;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(ConfigFileFullPath))
			{
				return;
			}
			try
			{
				CCRLogger.LogDebug((object)"ReadConfigValues called");
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch
			{
				CCRLogger.LogError((object)"There was an issue loading your Azumatt.CraftyCarts.cfg");
				CCRLogger.LogError((object)"Please check your config entries for spelling and format!");
			}
		}

		private ConfigEntry<T> config<[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags);
			ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val);
			ConfigSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting;
			return val2;
		}

		private ConfigEntry<T> config<[<76454529-a769-42a6-a71c-ea642218f04f>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		static CCR()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + "Azumatt.CraftyCarts.cfg";
			CCRLogger = Logger.CreateLogSource("CraftyCarts");
			ConfigSync = new ConfigSync("Azumatt.CraftyCarts")
			{
				DisplayName = "CraftyCarts",
				CurrentVersion = "3.1.0",
				MinimumRequiredVersion = "3.1.0"
			};
			ForgeCartRow = null;
			ForgeCartCol = null;
			StonecutterCartRow = null;
			StonecutterCartCol = null;
			WorkbenchCartRow = null;
			WorkbenchCartCol = null;
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	public static class RegisterAndCheckVersion
	{
		[<8a37fe5c-47e1-4257-9589-07ee12084834>NullableContext(1)]
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			CCR.CCRLogger.LogDebug((object)"Registering version RPC handler");
			peer.m_rpc.Register<ZPackage>("CraftyCarts_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_Recycle_N_Reclaim_Version);
			CCR.CCRLogger.LogInfo((object)"Invoking version check");
			ZPackage val = new ZPackage();
			val.Write("3.1.0");
			val.Write(RpcHandlers.ComputeHashForMod().Replace("-", 

BepInEx/plugins/OdinPlus-OdinHorse/OdinHorse.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using CreatureManager;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using LocalizationManager;
using Microsoft.CodeAnalysis;
using PieceManager;
using ServerSync;
using UnityEngine;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: AssemblyFileVersion("1.2.5.0")]
[assembly: Guid("150DFDAF-FF35-4302-B2CC-BEDCE69118D5")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("OdinHorse")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/OdinPlus/OdinHorse")]
[assembly: AssemblyTitle("OdinHorse")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.5.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<49ee373d-af31-4560-b436-054c3e835efa>Embedded]
	internal sealed class <49ee373d-af31-4560-b436-054c3e835efa>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<49ee373d-af31-4560-b436-054c3e835efa>Embedded]
	[CompilerGenerated]
	internal sealed class <aef65ecd-bd45-4804-9aea-996149d4f0ea>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <aef65ecd-bd45-4804-9aea-996149d4f0ea>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <aef65ecd-bd45-4804-9aea-996149d4f0ea>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<49ee373d-af31-4560-b436-054c3e835efa>Embedded]
	[CompilerGenerated]
	internal sealed class <1900c84d-2197-45c6-9a21-f8e42635770d>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <1900c84d-2197-45c6-9a21-f8e42635770d>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace OdinHorse
{
	[<aef65ecd-bd45-4804-9aea-996149d4f0ea>Nullable(0)]
	[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(1)]
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	[BepInPlugin("Raelaziel.OdinHorse", "OdinHorse", "1.2.5")]
	public class OdinHorse : BaseUnityPlugin
	{
		[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(0)]
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(0)]
		public enum HorseBeasts
		{
			player,
			horse
		}

		[HarmonyPatch(typeof(Vagon), "LateUpdate")]
		[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(0)]
		private class LateUpdate_Vagon_Patch
		{
			[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(1)]
			private static void Prefix(ref Vagon __instance, ref ConfigurableJoint ___m_attachJoin, ref Rigidbody ___m_body)
			{
				if ((Object)(object)___m_attachJoin != (Object)null && (Object)(object)((Joint)___m_attachJoin).connectedBody == (Object)null)
				{
					__instance.Detach();
				}
			}
		}

		[HarmonyPatch(typeof(Vagon), "InUse")]
		[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(0)]
		private class InUse_Vagon_Patch
		{
			[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(1)]
			private static bool Prefix(ref bool __result, ref Vagon __instance)
			{
				if (Object.op_Implicit((Object)(object)__instance.m_container) && __instance.m_container.IsInUse())
				{
					__result = true;
				}
				else if (__instance.IsAttached())
				{
					__result = Object.op_Implicit((Object)(object)((Component)((Joint)__instance.m_attachJoin).connectedBody).gameObject.GetComponent<Player>());
				}
				else
				{
					__result = false;
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(Vagon), "FixedUpdate")]
		[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(0)]
		private class Vagon_FixedUpdate_Patch
		{
			[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(1)]
			private static bool Prefix(Vagon __instance)
			{
				//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
				if (!__instance.m_nview.IsValid())
				{
					return false;
				}
				__instance.UpdateAudio(Time.fixedDeltaTime);
				if (__instance.m_nview.IsOwner())
				{
					if (Object.op_Implicit((Object)(object)__instance.m_useRequester))
					{
						if (__instance.IsAttached())
						{
							__instance.Detach();
						}
						else
						{
							Character val = FindClosestAttachableAnimal(__instance);
							if ((Object)(object)val != (Object)null)
							{
								AttachCartTo(val, __instance);
							}
							else if (__instance.CanAttach(((Component)__instance.m_useRequester).gameObject))
							{
								AttachCartTo((Character)(object)__instance.m_useRequester, __instance);
							}
							else
							{
								((Character)__instance.m_useRequester).Message((MessageType)2, "Not in the right position", 0, (Sprite)null);
							}
						}
						__instance.m_useRequester = null;
					}
					if (__instance.IsAttached())
					{
						__instance.m_detachDistance = GetCartDetachDistance(AttachedCharacter(__instance));
						if (!__instance.CanAttach(((Component)((Joint)__instance.m_attachJoin).connectedBody).gameObject))
						{
							__instance.Detach();
						}
					}
				}
				else if (__instance.IsAttached())
				{
					__instance.Detach();
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(BaseAI), "Follow")]
		[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(0)]
		private class Tamed_Follow_patch
		{
			[<1900c84d-2197-45c6-9a21-f8e42635770d>NullableContext(1)]
			private static bool Prefix(GameObject go, float dt, ref BaseAI __instance)
			{
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0082: Unknown result type (might be due to invalid IL or missing references)
				if (!__instance.m_character.IsTamed())
				{
					return true;
				}
				BaseAI obj = __instance;
				if ((Object)(object)((MonsterAI)((obj is MonsterAI) ? obj : null)).GetFollowTarget().GetComponent<Player>() == (Object)null)
				{
					return true;
				}
				float num = Vector3.Distance(go.transform.position, ((Component)__instance).transform.position);
				if (ParseCharacterType(__instance.m_character) == HorseBeasts.horse)
				{
					float num2 = 3f;
					bool flag = num > num2 * 3f;
					if (num < num2)
					{
						__instance.StopMoving();
					}
					else
					{
						__instance.MoveTo(dt, go.transform.position, 0f, flag);
					}
					return false;
				}
				return true;
			}
		}

		[<aef65ecd-bd45-4804-9aea-996149d4f0ea>Nullable(0)]
		public static class CustomMapPins
		{
			[<aef65ecd-bd45-4804-9aea-996149d4f0ea>Nullable(0)]
			public class CustomPinhandlerHorse : MonoBehaviour
			{
				public Sprite icon;

				public string pinName;

				private PinData pin;

				private void Awake()
				{
					//IL_001a: Unknown result type (might be due to invalid IL or missing references)
					//IL_0024: Expected O, but got Unknown
					//IL_002b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005c: Unknown result type (might be due to invalid IL or missing references)
					//IL_009c: Unknown result type (might be due to invalid IL or missing references)
					//IL_00a2: Invalid comparison between Unknown and I4
					//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
					//IL_00d1: Expected O, but got Unknown
					if (!((Component)this).gameObject.GetComponent<Tameable>().HaveSaddle())
					{
						Object.DestroyImmediate((Object)(object)this);
						return;
					}
					pin = new PinData();
					pin.m_type = (PinType)0;
					pin.m_name = Localization.instance.Localize(pinName);
					pin.m_pos = ((Component)this).transform.position;
					pin.m_icon = icon;
					pin.m_save = false;
					pin.m_checked = false;
					pin.m_ownerID = 0L;
					RectTransform val = (((int)Minimap.instance.m_mode == 2) ? Minimap.instance.m_pinNameRootLarge : Minimap.instance.m_pinNameRootSmall);
					pin.m_NamePinData = new PinNameData(pin);
					Minimap.instance.CreateMapNamePin(pin, val);
					pin.m_NamePinData.PinNameText.richText = true;
					pin.m_NamePinData.PinNameText.overrideColorTags = false;
					Minimap.instance?.m_pins?.Add(pin);
				}

				private void LateUpdate()
				{
					//IL_0018: Unknown result type (might be due to invalid IL or missing references)
					//IL_001d: Unknown result type (might be due to invalid IL or missing references)
					pin.m_checked = false;
					pin.m_pos = ((Component)this).transform.position;
				}

				private void OnDestroy()
				{
					if (pin != null)
					{
						if (Object.op_Implicit((Object)(object)pin.m_uiElement))
						{
							Minimap.instance.DestroyPinMarker(pin);
						}
						Minimap.instance?.m_pins?.Remove(pin);
					}
				}
			}

			public static void RegisterCustomPin(GameObject go, string name, Sprite icon)
			{
				CustomPinhandlerHorse customPinhandlerHorse = go.AddComponent<CustomPinhandlerHorse>();
				customPinhandlerHorse.pinName = name;
				customPinhandlerHorse.icon = icon;
			}
		}

		[<aef65ecd-bd45-4804-9aea-996149d4f0ea>Nullable(0)]
		public static class CustomMapPins_Cart
		{
			[<aef65ecd-bd45-4804-9aea-996149d4f0ea>Nullable(0)]
			public class CustomPinhandler_Generic_Cart : MonoBehaviour
			{
				public Sprite icon;

				public string pinName;

				private PinData pin;

				private void Awake()
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					//IL_000b: Expected O, but got Unknown
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_003e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0043: Unknown result type (might be due to invalid IL or missing references)
					//IL_0083: Unknown result type (might be due to invalid IL or missing references)
					//IL_0089: Invalid comparison between Unknown and I4
					//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
					//IL_00b8: Expected O, but got Unknown
					pin = new PinData();
					pin.m_type = (PinType)0;
					pin.m_name = Localization.instance.Localize(pinName);
					pin.m_pos = ((Component)this).transform.position;
					pin.m_icon = icon;
					pin.m_save = false;
					pin.m_checked = false;
					pin.m_ownerID = 0L;
					RectTransform val = (((int)Minimap.instance.m_mode == 2) ? Minimap.instance.m_pinNameRootLarge : Minimap.instance.m_pinNameRootSmall);
					pin.m_NamePinData = new PinNameData(pin);
					Minimap.instance.CreateMapNamePin(pin, val);
					pin.m_NamePinData.PinNameText.richText = true;
					pin.m_NamePinData.PinNameText.overrideColorTags = false;
					Minimap.instance?.m_pins?.Add(pin);
				}

				private void LateUpdate()
				{
					//IL_0018: Unknown result type (might be due to invalid IL or missing references)
					//IL_001d: Unknown result type (might be due to invalid IL or missing references)
					pin.m_checked = false;
					pin.m_pos = ((Component)this).transform.position;
				}

				private void OnDestroy()
				{
					if (Object.op_Implicit((Object)(object)pin.m_uiElement))
					{
						Minimap.instance.DestroyPinMarker(pin);
					}
					Minimap.instance?.m_pins?.Remove(pin);
				}
			}

			public static void RegisterCustomPinGeneric(GameObject go, string name, Sprite icon)
			{
				CustomPinhandler_Generic_Cart customPinhandler_Generic_Cart = go.AddComponent<CustomPinhandler_Generic_Cart>();
				customPinhandler_Generic_Cart.pinName = name;
				customPinhandler_Generic_Cart.icon = icon;
			}
		}

		private const string ModName = "OdinHorse";

		private const string ModVersion = "1.2.5";

		private const string ModGUID = "Raelaziel.OdinHorse";

		private static readonly ConfigSync configSync = new ConfigSync("OdinHorse")
		{
			DisplayName = "OdinHorse",
			CurrentVersion = "1.2.5",
			MinimumRequiredVersion = "1.2.5"
		};

		private static ConfigEntry<Toggle> serverConfigLocked = null;

		internal static Creature raeHorse;

		internal static ConfigEntry<bool> ServerConfigLocked = null;

		internal static ConfigEntry<int> HorseRunningSpeed = null;

		internal static ConfigEntry<int> HorseHealth = null;

		internal static ConfigEntry<float> HorseStamina = null;

		internal static ConfigEntry<float> HorseStaminaRegen = null;

		internal static ConfigEntry<float> HorseStaminaRegenHungry = null;

		internal static ConfigEntry<int> HorseFeedingTime = null;

		internal static ConfigEntry<int> HorseTamingTime = null;

		internal static ConfigEntry<int> HorseOffspringHealth = null;

		internal static ConfigEntry<int> HorseOffspringGrowupTime = null;

		internal static ConfigEntry<float> HorseOffspringMeatDropChance = null;

		internal static ConfigEntry<int> HorseOffspringMeatDropMinimum = null;

		internal static ConfigEntry<int> HorseOffspringMeatDropMaximum = null;

		internal static ConfigEntry<float> HorseOffspringHideDropChance = null;

		internal static ConfigEntry<int> HorseOffspringHideDropMinimum = null;

		internal static ConfigEntry<int> HorseOffspringHideDropMaximum = null;

		private ConfigEntry<T> config<[<aef65ecd-bd45-4804-9aea-996149d4f0ea>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			configSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<aef65ecd-bd45-4804-9aea-996149d4f0ea>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Expected O, but got Unknown
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Expected O, but got Unknown
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Expected O, but got Unknown
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Expected O, but got Unknown
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Expected O, but got Unknown
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Expected O, but got Unknown
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Expected O, but got Unknown
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Expected O, but got Unknown
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Expected O, but got Unknown
			//IL_0713: Unknown result type (might be due to invalid IL or missing references)
			//IL_099b: Unknown result type (might be due to invalid IL or missing references)
			//IL_09a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_09ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_09bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_09cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_09dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_09e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_09ef: Expected O, but got Unknown
			//IL_09fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_09ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a0b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a1b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a2b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a3b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a42: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a4e: Expected O, but got Unknown
			//IL_0e32: Unknown result type (might be due to invalid IL or missing references)
			Localizer.Load();
			serverConfigLocked = config("General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			HorseRunningSpeed = config("Horse", "Running Speed", 10, new ConfigDescription("Declare running speed for Horse", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseHealth = config("Horse", "Health", 200, new ConfigDescription("Declare health points for Horse", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseStamina = config("Horse", "Stamina", 400f, new ConfigDescription("Declare stamina for Horse", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseStaminaRegen = config("Horse", "Stamina Regen", 2f, new ConfigDescription("Declare stamina regen for Horse", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseStaminaRegenHungry = config("Horse", "Stamina Regen Hungry", 1f, new ConfigDescription("Declare stamina regen when hungry for Horse", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseFeedingTime = config("Horse", "Fed duration", 600, new ConfigDescription("Declare fed duration for Horse", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseTamingTime = config("Horse", "Taming time", 1800, new ConfigDescription("Declare taming time needed to tame the Horse", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseOffspringHealth = config("Horse Offspring", "Health", 60, new ConfigDescription("Declare health points for Horse Offspring", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseOffspringGrowupTime = config("Horse Offspring", "Grow-up time", 2000, new ConfigDescription("Declare growup time needed to convert offspring into Horse. Time in seconds.", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseOffspringMeatDropChance = config("Horse Offspring", "Meat Drop Chance", 1f, new ConfigDescription("Declare drop chance for Horse Meat from offspring", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseOffspringMeatDropMinimum = config("Horse Offspring", "Meat Amount Min", 1, new ConfigDescription("Declare minimum amount of Horse Meat to drop from offspring", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseOffspringMeatDropMaximum = config("Horse Offspring", "Meat Amount Max", 2, new ConfigDescription("Declare maximum amount of Horse Meat to drop from offspring", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseOffspringHideDropChance = config("Horse Offspring", "Hide Drop Chance", 0.33f, new ConfigDescription("Declare drop chance for Horse Hide from offspring", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseOffspringHideDropMinimum = config("Horse Offspring", "Hide Amount Min", 1, new ConfigDescription("Declare minimum amount of Horse Hide to drop from offspring", (AcceptableValueBase)null, Array.Empty<object>()));
			HorseOffspringHideDropMaximum = config("Horse Offspring", "Hide Amount Max", 1, new ConfigDescription("Declare maximum amount of Horse Hide to drop from offspring", (AcceptableValueBase)null, Array.Empty<object>()));
			Item item = new Item("odinhorse", "rae_HorseMeat");
			Item item2 = new Item("odinhorse", "rae_HorseHide");
			Item item3 = new Item("odinhorse", "rae_OdinHorse_Trophy");
			Item item4 = new Item("odinhorse", "rae_SaddleHorse");
			item4.Crafting.Add(ItemManager.CraftingTable.Workbench, 1);
			item4.MaximumRequiredStationLevel = 5;
			item4.RequiredItems.Add("FineWood", 20);
			item4.RequiredItems.Add("Bronze", 10);
			item4.RequiredItems.Add("rae_HorseHide", 30);
			item4.CraftAmount = 1;
			Item item5 = new Item("odinhorse", "rae_HorseSticks");
			item5.Crafting.Add(ItemManager.CraftingTable.Cauldron, 1);
			item5.MaximumRequiredStationLevel = 10;
			item5.RequiredItems.Add("rae_HorseMeat", 3);
			item5.RequiredItems.Add("Coal", 1);
			item5.RequiredItems.Add("Dandelion", 2);
			item5.CraftAmount = 2;
			Item item6 = new Item("odinhorse", "rae_HorseSoup");
			item6.Crafting.Add(ItemManager.CraftingTable.Cauldron, 1);
			item6.MaximumRequiredStationLevel = 10;
			item6.RequiredItems.Add("rae_HorseMeat", 2);
			item6.RequiredItems.Add("Carrot", 2);
			item6.RequiredItems.Add("Dandelion", 3);
			item6.CraftAmount = 1;
			Item item7 = new Item("odinhorse", "rae_HorseMeatSkewer");
			item7.Crafting.Add(ItemManager.CraftingTable.Cauldron, 2);
			item7.MaximumRequiredStationLevel = 10;
			item7.RequiredItems.Add("rae_HorseMeat", 3);
			item7.RequiredItems.Add("Mushroom", 2);
			item7.RequiredItems.Add("NeckTail", 1);
			item7.CraftAmount = 2;
			Item item8 = new Item("odinhorse", "rae_Horseaker");
			item8.Crafting.Add(ItemManager.CraftingTable.Forge, 1);
			item8.MaximumRequiredStationLevel = 10;
			item8.RequiredItems.Add("Iron", 30);
			item8.RequiredItems.Add("rae_OdinHorse_Trophy", 1);
			item8.RequiredItems.Add("ElderBark", 35);
			item8.RequiredUpgradeItems.Add("Iron", 5);
			item8.RequiredUpgradeItems.Add("ElderBark", 10);
			item8.CraftAmount = 1;
			Item item9 = new Item("odinhorse", "rae_OdinHorse_Helmet");
			item9.Crafting.Add(ItemManager.CraftingTable.Workbench, 1);
			item9.MaximumRequiredStationLevel = 10;
			item9.RequiredItems.Add("Tin", 10);
			item9.RequiredItems.Add("rae_OdinHorse_Trophy", 1);
			item9.RequiredItems.Add("rae_HorseHide", 5);
			item9.RequiredUpgradeItems.Add("rae_HorseHide", 4);
			item9.RequiredUpgradeItems.Add("Tin", 2);
			item9.CraftAmount = 1;
			Item item10 = new Item("odinhorse", "rae_CapeHorseHide");
			item10.Crafting.Add(ItemManager.CraftingTable.Workbench, 1);
			item10.MaximumRequiredStationLevel = 10;
			item10.RequiredItems.Add("rae_HorseHide", 10);
			item10.RequiredItems.Add("rae_OdinHorse_Trophy", 1);
			item10.RequiredItems.Add("Tin", 2);
			item10.RequiredUpgradeItems.Add("rae_HorseHide", 10);
			item10.RequiredUpgradeItems.Add("Tin", 2);
			item10.CraftAmount = 1;
			BuildPiece buildPiece = new BuildPiece("odinhorse", "rae_OdinHorse_Rug");
			buildPiece.RequiredItems.Add("rae_HorseHide", 20, recover: true);
			buildPiece.Category.Add(BuildPieceCategory.Furniture);
			buildPiece.Crafting.Set(PieceManager.CraftingTable.Workbench);
			BuildPiece buildPiece2 = new BuildPiece("odinhorse", "rae_HorseChair");
			buildPiece2.RequiredItems.Add("rae_HorseHide", 2, recover: true);
			buildPiece2.RequiredItems.Add("FineWood", 3, recover: true);
			buildPiece2.Category.Add(BuildPieceCategory.Furniture);
			buildPiece2.Crafting.Set(PieceManager.CraftingTable.Workbench);
			BuildPiece buildPiece3 = new BuildPiece("horsecart", "rae_HorseCart");
			buildPiece3.RequiredItems.Add("BronzeNails", 60, recover: true);
			buildPiece3.RequiredItems.Add("FineWood", 40, recover: true);
			buildPiece3.Category.Add(BuildPieceCategory.Misc);
			buildPiece3.Crafting.Set(PieceManager.CraftingTable.Workbench);
			raeHorse = new Creature("odinhorse", "rae_OdinHorse")
			{
				ConfigurationEnabled = true,
				Biome = (Biome)1,
				CanSpawn = true,
				CanBeTamed = true,
				CanHaveStars = true,
				FoodItems = "Blueberries, Carrot, Cloudberry, Barley",
				SpawnChance = 15f,
				GroupSize = new CreatureManager.Range(1f, 2f),
				CheckSpawnInterval = 2000,
				SpecificSpawnTime = SpawnTime.Day,
				SpecificSpawnArea = SpawnArea.Center,
				RequiredWeather = Weather.ClearSkies,
				AttackImmediately = false,
				ForestSpawn = Forest.Both,
				Maximum = 1
			};
			ItemManager.PrefabManager.RegisterPrefab("odinhorse", "horse_bite_attack");
			GameObject obj = ItemManager.PrefabManager.RegisterPrefab("odinhorse", "rae_Offspring_Normal");
			ItemManager.PrefabManager.RegisterPrefab("odinhorse", "rae_Offspring_Normal_ragdoll");
			ItemManager.PrefabManager.RegisterPrefab("odinhorse", "rae_OdinHorse_ragdoll");
			raeHorse.Drops["rae_HorseMeat"].Amount = new CreatureManager.Range(1f, 2f);
			raeHorse.Drops["rae_HorseMeat"].DropChance = 100f;
			raeHorse.Drops["rae_HorseHide"].Amount = new CreatureManager.Range(1f, 2f);
			raeHorse.Drops["rae_HorseHide"].DropChance = 100f;
			raeHorse.Drops["rae_OdinHorse_Trophy"].Amount = new CreatureManager.Range(1f, 2f);
			raeHorse.Drops["rae_OdinHorse_Trophy"].DropChance = 10f;
			((Character)raeHorse.Prefab.GetComponent<Humanoid>()).m_runSpeed = HorseRunningSpeed.Value;
			((Character)raeHorse.Prefab.GetComponent<Humanoid>()).m_health = HorseHealth.Value;
			raeHorse.Prefab.GetComponent<Tameable>().m_fedDuration = HorseFeedingTime.Value;
			raeHorse.Prefab.GetComponent<Tameable>().m_tamingTime = HorseTamingTime.Value;
			raeHorse.Prefab.GetComponentInChildren<Sadle>(true).m_maxStamina = HorseStamina.Value;
			raeHorse.Prefab.GetComponentInChildren<Sadle>(true).m_staminaRegen = HorseStaminaRegen.Value;
			raeHorse.Prefab.GetComponentInChildren<Sadle>(true).m_staminaRegenHungry = HorseStaminaRegenHungry.Value;
			obj.GetComponent<CharacterDrop>().m_drops.Add(new Drop
			{
				m_prefab = item2.Prefab,
				m_amountMin = HorseOffspringHideDropMinimum.Value,
				m_amountMax = HorseOffspringHideDropMaximum.Value,
				m_chance = HorseOffspringHideDropChance.Value,
				m_levelMultiplier = true,
				m_onePerPlayer = false
			});
			obj.GetComponent<CharacterDrop>().m_drops.Add(new Drop
			{
				m_prefab = item.Prefab,
				m_amountMin = HorseOffspringMeatDropMinimum.Value,
				m_amountMax = HorseOffspringMeatDropMaximum.Value,
				m_chance = HorseOffspringMeatDropChance.Value,
				m_levelMultiplier = true,
				m_onePerPlayer = false
			});
			((Character)obj.GetComponent<Humanoid>()).m_health = HorseOffspringHealth.Value;
			obj.GetComponent<Growup>().m_growTime = HorseOffspringGrowupTime.Value;
			Item item11 = new Item("horsesets", "ArmorHorseClothHelmet_T1");
			item11.Crafting.Add(ItemManager.CraftingTable.Workbench, 1);
			item11.MaximumRequiredStationLevel = 10;
			item11.RequiredItems.Add("rae_HorseHide", 4);
			item11.RequiredItems.Add("LeatherScraps", 6);
			item11.RequiredItems.Add("rae_OdinHorse_Trophy", 1);
			item11.RequiredUpgradeItems.Add("rae_HorseHide", 2);
			item11.RequiredUpgradeItems.Add("LeatherScraps", 3);
			item11.CraftAmount = 1;
			Item item12 = new Item("horsesets", "ArmorHorseClothHelmet_T2");
			item12.Crafting.Add(ItemManager.CraftingTable.Forge, 1);
			item12.MaximumRequiredStationLevel = 10;
			item12.RequiredItems.Add("rae_HorseHide", 6);
			item12.RequiredItems.Add("Iron", 15);
			item12.RequiredItems.Add("LeatherScraps", 4);
			item12.RequiredItems.Add("rae_OdinHorse_Trophy", 1);
			item12.RequiredUpgradeItems.Add("rae_HorseHide", 3);
			item12.RequiredUpgradeItems.Add("Iron", 5);
			item12.RequiredUpgradeItems.Add("LeatherScraps", 2);
			item12.CraftAmount = 1;
			Item item13 = new Item("horsesets", "ArmorHorseClothChest_T1");
			item13.Crafting.Add(ItemManager.CraftingTable.Workbench, 1);
			item13.MaximumRequiredStationLevel = 10;
			item13.RequiredItems.Add("rae_HorseHide", 4);
			item13.RequiredItems.Add("LeatherScraps", 8);
			item13.RequiredUpgradeItems.Add("rae_HorseHide", 2);
			item13.RequiredUpgradeItems.Add("LeatherScraps", 4);
			item13.CraftAmount = 1;
			Item item14 = new Item("horsesets", "ArmorHorseClothChest_T2");
			item14.Crafting.Add(ItemManager.CraftingTable.Forge, 1);
			item14.MaximumRequiredStationLevel = 10;
			item14.RequiredItems.Add("rae_HorseHide", 6);
			item14.RequiredItems.Add("Iron", 20);
			item14.RequiredItems.Add("LeatherScraps", 8);
			item14.RequiredUpgradeItems.Add("rae_HorseHide", 2);
			item14.RequiredUpgradeItems.Add("Iron", 5);
			item14.RequiredUpgradeItems.Add("LeatherScraps", 4);
			item14.CraftAmount = 1;
			Item item15 = new Item("horsesets", "ArmorHorseClothLegs_T1");
			item15.Crafting.Add(ItemManager.CraftingTable.Workbench, 1);
			item15.MaximumRequiredStationLevel = 10;
			item15.RequiredItems.Add("rae_HorseHide", 4);
			item15.RequiredItems.Add("LeatherScraps", 8);
			item15.RequiredUpgradeItems.Add("rae_HorseHide", 2);
			item15.RequiredUpgradeItems.Add("LeatherScraps", 4);
			item15.CraftAmount = 1;
			Item item16 = new Item("horsesets", "ArmorHorseClothLegs_T2");
			item16.Crafting.Add(ItemManager.CraftingTable.Forge, 1);
			item16.MaximumRequiredStationLevel = 10;
			item16.RequiredItems.Add("rae_HorseHide", 6);
			item16.RequiredItems.Add("Iron", 20);
			item16.RequiredItems.Add("LeatherScraps", 8);
			item16.RequiredUpgradeItems.Add("rae_HorseHide", 2);
			item16.RequiredUpgradeItems.Add("Iron", 5);
			item16.RequiredUpgradeItems.Add("LeatherScraps", 4);
			item16.CraftAmount = 1;
			CustomMapPins.RegisterCustomPin(raeHorse.Prefab, "$horse_odin", item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_icons[0]);
			CustomMapPins_Cart.RegisterCustomPinGeneric(buildPiece3.Prefab, "$pin_cart", buildPiece3.Prefab.GetComponent<Piece>().m_icon);
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			new Harmony("Raelaziel.OdinHorse").PatchAll(executingAssembly);
		}

		public static HorseBeasts ParseCharacterType(Character c)
		{
			if (c.IsPlayer())
			{
				return HorseBeasts.player;
			}
			if (c.m_nview.IsValid())
			{
				_ = ((Object)ZNetScene.instance.GetPrefab(c.m_nview.GetZDO().GetPrefab())).name == "rae_OdinHorse";
				return HorseBeasts.horse;
			}
			return HorseBeasts.horse;
		}

		public static Vector3 GetCartOffsetVectorForCharacter(Character c)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)c))
			{
				return new Vector3(0f, 0.8f, 0f - c.GetRadius());
			}
			return new Vector3(0f, 0.8f, 0f);
		}

		public static bool IsAttachableCharacter(Character c)
		{
			return ParseCharacterType(c) switch
			{
				HorseBeasts.player => false, 
				HorseBeasts.horse => true, 
				_ => true, 
			};
		}

		public static float GetCartDetachDistance(Character c)
		{
			if (Object.op_Implicit((Object)(object)c))
			{
				if (c.IsPlayer())
				{
					return 2f;
				}
				return c.GetRadius() * 3f;
			}
			return 0f;
		}

		private static Character FindClosestAttachableAnimal(Vagon cart)
		{
			//IL_0064: 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_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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)cart))
			{
				return null;
			}
			Transform attachPoint = cart.m_attachPoint;
			Character result = null;
			float num = float.MaxValue;
			if (!Object.op_Implicit((Object)(object)cart.m_attachPoint))
			{
				return null;
			}
			foreach (Character allCharacter in Character.GetAllCharacters())
			{
				if (Object.op_Implicit((Object)(object)allCharacter) && !allCharacter.IsPlayer() && allCharacter.IsTamed() && IsAttachableCharacter(allCharacter))
				{
					Vector3 cartOffsetVectorForCharacter = GetCartOffsetVectorForCharacter(allCharacter);
					float num2 = Vector3.Distance(((Component)allCharacter).transform.position + cartOffsetVectorForCharacter, attachPoint.position);
					float cartDetachDistance = GetCartDetachDistance(allCharacter);
					if (num2 < cartDetachDistance && num2 < num)
					{
						result = allCharacter;
						num = num2;
					}
				}
			}
			return result;
		}

		private static Character AttachedCharacter(Vagon cart)
		{
			if (Object.op_Implicit((Object)(object)cart) && cart.IsAttached())
			{
				return ((Component)((Joint)cart.m_attachJoin).connectedBody).gameObject.GetComponent<Character>();
			}
			return null;
		}

		private static void LogCartContents(Vagon cart)
		{
			foreach (ItemData allItem in cart.m_container.GetInventory().GetAllItems())
			{
				_ = allItem;
			}
		}

		private static void AttachCartTo(Character attachTarget, Vagon cart)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			cart.m_attachOffset = GetCartOffsetVectorForCharacter(attachTarget);
			cart.m_attachJoin = ((Component)cart).gameObject.AddComponent<ConfigurableJoint>();
			((Joint)cart.m_attachJoin).autoConfigureConnectedAnchor = false;
			((Joint)cart.m_attachJoin).anchor = cart.m_attachPoint.localPosition;
			((Joint)cart.m_attachJoin).connectedAnchor = cart.m_attachOffset;
			((Joint)cart.m_attachJoin).breakForce = cart.m_breakForce;
			cart.m_attachJoin.xMotion = (ConfigurableJointMotion)1;
			cart.m_attachJoin.yMotion = (ConfigurableJointMotion)1;
			cart.m_attachJoin.zMotion = (ConfigurableJointMotion)1;
			SoftJointLimit linearLimit = default(SoftJointLimit);
			((SoftJointLimit)(ref linearLimit)).limit = 0.001f;
			cart.m_attachJoin.linearLimit = linearLimit;
			SoftJointLimitSpring linearLimitSpring = default(SoftJointLimitSpring);
			((SoftJointLimitSpring)(ref linearLimitSpring)).spring = cart.m_spring;
			((SoftJointLimitSpring)(ref linearLimitSpring)).damper = cart.m_springDamping;
			cart.m_attachJoin.linearLimitSpring = linearLimitSpring;
			cart.m_attachJoin.zMotion = (ConfigurableJointMotion)0;
			((Joint)cart.m_attachJoin).connectedBody = ((Component)attachTarget).gameObject.GetComponent<Rigidbody>();
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<043bb40e-dc91-4b99-975d-20a796b6e2ae>Embedded]
	internal sealed class <043bb40e-dc91-4b99-975d-20a796b6e2ae>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<043bb40e-dc91-4b99-975d-20a796b6e2ae>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <138ec25d-2d4d-44e5-9dd4-aed86543ce9f>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <138ec25d-2d4d-44e5-9dd4-aed86543ce9f>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <138ec25d-2d4d-44e5-9dd4-aed86543ce9f>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<043bb40e-dc91-4b99-975d-20a796b6e2ae>Embedded]
	[CompilerGenerated]
	internal sealed class <7eab116d-6482-4952-8c07-99c40e737793>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <7eab116d-6482-4952-8c07-99c40e737793>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[<043bb40e-dc91-4b99-975d-20a796b6e2ae>Embedded]
	[CompilerGenerated]
	internal sealed class <dd89c7fc-b5df-4808-ba6b-9d1c67364029>RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public <dd89c7fc-b5df-4808-ba6b-9d1c67364029>RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
	[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
	internal abstract class OwnConfigEntryBase
	{
		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		public object LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
	[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
	[PublicAPI]
	internal class SyncedConfigEntry<[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)] T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(2)]
	[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
	internal abstract class CustomSyncedValueBase
	{
		public object LocalBaseValue;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(1)]
		public readonly string Identifier;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(1)]
		public readonly Type Type;

		private object boxedValue;

		protected bool localIsOwner;

		public object BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action ValueChanged;

		[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
	[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
	internal sealed class CustomSyncedValue<[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)] T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
	[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)]
		private static class SnatchCurrentlyHandlingRPC
		{
			[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
			public static ZRpc currentRpc;

			[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)]
		private class ParsedConfigs
		{
			[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>();

			[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
		private class SendConfigsAfterLogin
		{
			[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix([<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
			public object value;
		}

		[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		public string DisplayName;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		public string CurrentVersion;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		public string MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		private OwnConfigEntryBase lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 1, 0, 1 })]
		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		[method: <7eab116d-6482-4952-8c07-99c40e737793>NullableContext(2)]
		[field: <138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		public event Action<bool> SourceOfTruthChanged;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		[method: <7eab116d-6482-4952-8c07-99c40e737793>NullableContext(2)]
		[field: <138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		private event Action lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)] T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += [<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)] T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += [<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (object _, EventArgs _) =>
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(([<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 0, 1 })] KeyValuePair<long, string> kv) =>
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out var value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		[return: <138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		private static OwnConfigEntryBase configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		[return: <138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 2, 1 })]
		public static SyncedConfigEntry<T> ConfigData<[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)] T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)] T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage([<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 2, 1 })] IEnumerable<ConfigEntryBase> configs = null, [<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 2, 1 })] IEnumerable<CustomSyncedValueBase> customValues = null, [<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 2, 1 })] IEnumerable<PackageEntry> packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, [<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)] object value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(1)]
	[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(0)]
	[PublicAPI]
	[HarmonyPatch]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		private string displayName;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		private string currentVersion;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		private string minimumRequiredVersion;

		public bool ModRequired = true;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		private string ReceivedCurrentVersion;

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		private string ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		[<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)]
		private ConfigSync ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new System.Version(ReceivedCurrentVersion) >= new System.Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error([<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(2)] ZRpc rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, [<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(new byte[] { 2, 1, 1 })] Action<ZRpc, ZPackage> original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (ZRpc rpc, [<138ec25d-2d4d-44e5-9dd4-aed86543ce9f>Nullable(1)] ZPackage pkg) =>
				{
					CheckVersion(rpc, pkg, action);
				}));
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy([<7eab116d-6482-4952-8c07-99c40e737793>NullableContext(0)] (KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[<d03a59c2-5655-4f2b-8172-069efc3fec10>Embedded]
	[CompilerGenerated]
	internal sealed class <d03a59c2-5655-4f2b-8172-069efc3fec10>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<d03a59c2-5655-4f2b-8172-069efc3fec10>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<d03a59c2-5655-4f2b-8172-069efc3fec10>Embedded]
	internal sealed class <30b8bc83-d42e-4053-af07-175c8989d878>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <30b8bc83-d42e-4053-af07-175c8989d878>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[<d03a59c2-5655-4f2b-8172-069efc3fec10>Embedded]
	[CompilerGenerated]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ItemManager
{
	[PublicAPI]
	internal enum CraftingTable
	{
		Disabled,
		Inventory,
		[InternalName("piece_workbench")]
		Workbench,
		[InternalName("piece_cauldron")]
		Cauldron,
		[InternalName("forge")]
		Forge,
		[InternalName("piece_artisanstation")]
		ArtisanTable,
		[InternalName("piece_stonecutter")]
		StoneCutter,
		[InternalName("piece_magetable")]
		MageTable,
		[InternalName("blackforge")]
		BlackForge,
		Custom
	}
	[PublicAPI]
	internal enum ConversionPiece
	{
		Disabled,
		[InternalName("smelter")]
		Smelter,
		[InternalName("charcoal_kiln")]
		CharcoalKiln,
		[InternalName("blastfurnace")]
		BlastFurnace,
		[InternalName("windmill")]
		Windmill,
		[InternalName("piece_spinningwheel")]
		SpinningWheel,
		[InternalName("eitrrefinery")]
		EitrRefinery,
		Custom
	}
	[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(1)]
	[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
	internal class InternalName : Attribute
	{
		public readonly string internalName;

		public InternalName(string internalName)
		{
			this.internalName = internalName;
		}
	}
	[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(1)]
	[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
	[PublicAPI]
	internal class RequiredResourceList
	{
		public readonly List<Requirement> Requirements = new List<Requirement>();

		public bool Free;

		public void Add(string itemName, int amount, int quality = 0)
		{
			Requirements.Add(new Requirement
			{
				itemName = itemName,
				amount = amount,
				quality = quality
			});
		}

		public void Add(string itemName, ConfigEntry<int> amountConfig, int quality = 0)
		{
			Requirements.Add(new Requirement
			{
				itemName = itemName,
				amountConfig = amountConfig,
				quality = quality
			});
		}
	}
	[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(1)]
	[PublicAPI]
	[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
	internal class CraftingStationList
	{
		public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>();

		public void Add(CraftingTable table, int level)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = table,
				level = level
			});
		}

		public void Add(string customTable, int level)
		{
			Stations.Add(new CraftingStationConfig
			{
				Table = CraftingTable.Custom,
				level = level,
				custom = customTable
			});
		}
	}
	[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(1)]
	[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
	[PublicAPI]
	internal class ItemRecipe
	{
		public readonly RequiredResourceList RequiredItems = new RequiredResourceList();

		public readonly RequiredResourceList RequiredUpgradeItems = new RequiredResourceList();

		public readonly CraftingStationList Crafting = new CraftingStationList();

		public int CraftAmount = 1;

		public bool RequireOnlyOneIngredient;

		public float QualityResultAmountMultiplier = 1f;

		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(2)]
		public ConfigEntryBase RecipeIsActive;
	}
	[PublicAPI]
	internal class Trade
	{
		public Trader Trader;

		public uint Price;

		public uint Stack = 1u;

		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(2)]
		public string RequiredGlobalKey;
	}
	[PublicAPI]
	[Flags]
	internal enum Trader
	{
		None = 0,
		Haldor = 1,
		Hildir = 2
	}
	internal struct Requirement
	{
		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(1)]
		public string itemName;

		public int amount;

		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(2)]
		public ConfigEntry<int> amountConfig;

		[Description("Set to a non-zero value to apply the requirement only for a specific quality")]
		public int quality;
	}
	internal struct CraftingStationConfig
	{
		public CraftingTable Table;

		public int level;

		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(2)]
		public string custom;
	}
	[Flags]
	internal enum Configurability
	{
		Disabled = 0,
		Recipe = 1,
		Stats = 2,
		Drop = 4,
		Trader = 8,
		Full = 0xF
	}
	[PublicAPI]
	[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
	[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(1)]
	internal class DropTargets
	{
		public readonly List<DropTarget> Drops = new List<DropTarget>();

		public void Add(string creatureName, float chance, int min = 1, int? max = null, bool levelMultiplier = true)
		{
			Drops.Add(new DropTarget
			{
				creature = creatureName,
				chance = chance,
				min = min,
				max = (max ?? min),
				levelMultiplier = levelMultiplier
			});
		}
	}
	internal struct DropTarget
	{
		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(1)]
		public string creature;

		public int min;

		public int max;

		public float chance;

		public bool levelMultiplier;
	}
	internal enum Toggle
	{
		On = 1,
		Off = 0
	}
	[PublicAPI]
	[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
	[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(1)]
	internal class Item
	{
		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
		private class ItemConfig
		{
			[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(new byte[] { 2, 1 })]
			public ConfigEntry<string> craft;

			[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(new byte[] { 2, 1 })]
			public ConfigEntry<string> upgrade;

			public ConfigEntry<CraftingTable> table;

			public ConfigEntry<int> tableLevel;

			public ConfigEntry<string> customTable;

			[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(2)]
			public ConfigEntry<int> maximumTableLevel;

			public ConfigEntry<Toggle> requireOneIngredient;

			public ConfigEntry<float> qualityResultAmountMultiplier;
		}

		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
		private class TraderConfig
		{
			public ConfigEntry<Trader> trader;

			public ConfigEntry<uint> price;

			public ConfigEntry<uint> stack;

			public ConfigEntry<string> requiredGlobalKey;
		}

		[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(0)]
		private class RequirementQuality
		{
			public int quality;
		}

		[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(2)]
		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			public string Category;

			[UsedImplicitly]
			[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(new byte[] { 2, 1 })]
			public Action<ConfigEntryBase> CustomDrawer;

			public Func<bool> browsability;
		}

		[PublicAPI]
		[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(0)]
		public enum DamageModifier
		{
			Normal,
			Resistant,
			Weak,
			Immune,
			Ignore,
			VeryResistant,
			VeryWeak,
			None
		}

		[<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(0)]
		private delegate void setDmgFunc(ref DamageTypes dmg, float value);

		[<5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(0)]
		private class SerializedRequirements
		{
			public readonly List<Requirement> Reqs;

			public SerializedRequirements(List<Requirement> reqs)
			{
				Reqs = reqs;
			}

			public SerializedRequirements(string reqs)
				: this(reqs.Split(new char[1] { ',' }).Select([<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(0)] (string r) =>
				{
					string[] array = r.Split(new char[1] { ':' });
					Requirement result = default(Requirement);
					result.itemName = array[0];
					result.amount = ((array.Length <= 1 || !int.TryParse(array[1], out var result2)) ? 1 : result2);
					result.quality = ((array.Length > 2 && int.TryParse(array[2], out var result3)) ? result3 : 0);
					return result;
				}).ToList())
			{
			}

			public override string ToString()
			{
				return string.Join(",", Reqs.Select([<30b8bc83-d42e-4053-af07-175c8989d878>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}" + ((r.quality > 0) ? $":{r.quality}" : "")));
			}

			[return: <5c5e4f9c-2ff6-4c67-bbc3-5ca70ccea940>Nullable(2)]
			public static ItemDrop fetchByName(ObjectDB objectDB, string name)
			{
				GameObject itemPrefab = objectDB.GetItemPrefab(name);
				ItemDrop obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)obj == (Object)null)
				{
					Debug.LogWarning((object)("The required item '" + name + "' does not exist."));
				}
				return obj;
			}

			public static Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade)
			{
				//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0178: Unknown result type (might be due to invalid IL or missing references)
				//IL_017d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0185: Unknown result type (might be due to invalid IL or m

BepInEx/plugins/pruts-DungeonReset/DungeonReset.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("DungeonReset")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DungeonReset")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("03f34726-acb1-48ac-bfdf-fead74ab6569")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 DungeonReset
{
	public static class Dungeons
	{
		private static float interval => Configs.Interval.Value;

		private static float playerProtectionInterval => Configs.PlayerProtectionInterval.Value;

		public static void OnDungeonLoad(DungeonGenerator dungeon)
		{
			Main.Log.LogInfo((object)("Dungeon '" + dungeon.GetCleanName() + "' was captured!\n"));
			UnscheduleAllNotLoaded();
			Schedule(dungeon);
		}

		public static void Schedule(DungeonGenerator dungeon, float delay = 0f)
		{
			float num = Random.Range(1f, 5f);
			float num2 = dungeon.Remaining();
			float num3 = delay + num2 + num;
			new Timer(dungeon, num3, interval);
			Main.Log.LogInfo((object)$"Dungeon '{dungeon.GetCleanName()}' was scheduled for reset in {num3:F0} seconds!\n");
		}

		public static void UnscheduleAllNotLoaded()
		{
			List<Timer> list = new List<Timer>(Timer.Each);
			foreach (Timer item in list)
			{
				if ((Object)(object)item.dungeon == (Object)null)
				{
					item.Destroy();
				}
			}
		}

		public static void UnscheduleAll()
		{
			List<Timer> list = new List<Timer>(Timer.Each);
			foreach (Timer item in list)
			{
				item.Destroy();
			}
		}

		public static bool Validate(Timer timer)
		{
			if (ValidateOutOfRange(timer) && ValidateTooEarly(timer) && ValidateOverdue(timer))
			{
				return ValidatePlayerProtection(timer);
			}
			return false;
		}

		public static void Reset(DungeonGenerator dungeon, Bounds? bounds = null)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			Bounds val = (Bounds)(((??)bounds) ?? new Bounds(((Component)dungeon).transform.position, dungeon.m_zoneSize * 2f));
			Scene activeScene = SceneManager.GetActiveScene();
			GameObject[] rootGameObjects = ((Scene)(ref activeScene)).GetRootGameObjects();
			foreach (GameObject val2 in rootGameObjects)
			{
				if (val2.transform.position.y < 4000f || !((Bounds)(ref val)).Contains(val2.transform.position) || Object.op_Implicit((Object)(object)val2.GetComponent<Player>()) || Object.op_Implicit((Object)(object)val2.GetComponent<TombStone>()) || (Object)(object)val2 == (Object)(object)((Component)dungeon).gameObject)
				{
					continue;
				}
				Piece component = val2.GetComponent<Piece>();
				if ((((Object)(object)component != (Object)null) ? component.GetCreator() : 0) != 0L)
				{
					continue;
				}
				ZNetView component2 = val2.GetComponent<ZNetView>();
				if ((Object)(object)component2 != (Object)null)
				{
					ZDO zDO = component2.GetZDO();
					if (zDO != null)
					{
						zDO.SetOwner(ZDOMan.instance.GetMyID());
					}
					component2.Destroy();
				}
				else
				{
					ZNetScene.instance.Destroy(val2);
				}
			}
			dungeon.Generate((SpawnMode)0);
			dungeon.SetLastReset(DateTimeOffset.Now);
			Main.Log.LogInfo((object)("Dungeon '" + dungeon.GetCleanName() + "' was regenerated successfully!\n"));
		}

		private static bool ValidateOutOfRange(Timer timer)
		{
			if ((Object)(object)timer.dungeon != (Object)null)
			{
				return true;
			}
			Main.Log.LogWarning((object)"Dungeon 'null' couldn't regenerate because it was out of bounds!\n");
			timer.Destroy();
			return false;
		}

		private static bool ValidateTooEarly(Timer timer)
		{
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				return true;
			}
			Main.Log.LogWarning((object)("Dungeon '" + timer.dungeon.GetCleanName() + "' wanted to reset too early!\n"));
			Schedule(timer.dungeon, 10f);
			return false;
		}

		private static bool ValidateOverdue(Timer timer)
		{
			if (timer.dungeon.IsOverdue())
			{
				return true;
			}
			Main.Log.LogWarning((object)("Dungeon '" + timer.dungeon.GetCleanName() + "' has already been reset!\n"));
			Schedule(timer.dungeon);
			return false;
		}

		private static bool ValidatePlayerProtection(Timer timer)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			if (!Configs.PlayerProtection.Value)
			{
				return true;
			}
			Bounds val = default(Bounds);
			((Bounds)(ref val))..ctor(((Component)timer.dungeon).transform.position, timer.dungeon.m_zoneSize * 2f);
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (((Bounds)(ref val)).Contains(((Component)allPlayer).transform.position))
				{
					Main.Log.LogWarning((object)("Dungeon '" + timer.dungeon.GetCleanName() + "' couldn't regenerate because a player was found inside!\n"));
					Schedule(timer.dungeon, playerProtectionInterval);
					return false;
				}
			}
			return true;
		}
	}
	[BepInPlugin("Tekla_DungeonReset", "DungeonReset", "5.4.1606")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class Main : BaseUnityPlugin
	{
		public const string NAME = "DungeonReset";

		public const string AUTHOR = "Tekla";

		public const string GUID = "Tekla_DungeonReset";

		public const string VERSION = "5.4.1606";

		internal static Main Instance;

		internal static ManualLogSource Log { get; private set; }

		internal static Harmony Harmony { get; private set; }

		internal static Assembly Assembly { get; private set; }

		internal static string Folder { get; private set; }

		public Main()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			Log = new ManualLogSource("DungeonReset");
			Harmony = new Harmony("Tekla_DungeonReset");
			Assembly = Assembly.GetExecutingAssembly();
			Folder = Path.GetDirectoryName(Assembly.Location);
			Instance = this;
		}

		public void Awake()
		{
			Configs.Awake((BaseUnityPlugin)(object)this);
			if (Configs.CommandsEnable.Value)
			{
				Commands.Awake();
			}
			if (Configs.LoggerEnable.Value)
			{
				Logger.Sources.Add((ILogSource)(object)Log);
			}
			if (Configs.Enable.Value)
			{
				Harmony.PatchAll(Assembly);
			}
		}
	}
	[HarmonyPatch]
	public static class Patches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(DungeonGenerator), "Load")]
		public static void DungeonGenerator_Load_Post(DungeonGenerator __instance)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Main.Log.LogInfo((object)$"Loaded dungeon '{__instance.GetCleanName()}' with theme {__instance.m_themes}\n");
			if (Configs.AllowedThemes.Value.Contains(((object)(Theme)(ref __instance.m_themes)).ToString()))
			{
				Dungeons.OnDungeonLoad(__instance);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ZNet), "OnDestroy")]
		public static void ZNet_OnDestroy_Post()
		{
			Dungeons.UnscheduleAll();
		}
	}
	public class Timer
	{
		public static readonly List<Timer> Each = new List<Timer>();

		public DungeonGenerator dungeon;

		public float delay;

		public float interval;

		private Coroutine task;

		public Timer(DungeonGenerator dungeon, float delay, float interval)
		{
			this.dungeon = dungeon;
			this.delay = delay;
			this.interval = interval;
			Each.Find((Timer ctx) => (Object)(object)ctx.dungeon == (Object)(object)this.dungeon)?.Destroy();
			Main instance = Main.Instance;
			task = ((instance != null) ? ((MonoBehaviour)instance).StartCoroutine(Cycle()) : null);
			Each.Add(this);
		}

		public void Destroy()
		{
			Main instance = Main.Instance;
			if (instance != null)
			{
				((MonoBehaviour)instance).StopCoroutine(task);
			}
			task = null;
			Each.Remove(this);
		}

		private IEnumerator Cycle()
		{
			yield return null;
			yield return (object)new WaitForSeconds(delay);
			while (true)
			{
				if (Dungeons.Validate(this))
				{
					Dungeons.Reset(dungeon);
				}
				yield return null;
				yield return (object)new WaitForSeconds(interval);
			}
		}
	}
	public static class Configs
	{
		public static ConfigEntry<bool> Enable;

		public static ConfigEntry<float> Interval;

		public static ConfigEntry<string> AllowedThemes;

		public static ConfigEntry<bool> PlayerProtection;

		public static ConfigEntry<float> PlayerProtectionInterval;

		public static ConfigEntry<bool> CommandsEnable;

		public static ConfigEntry<bool> LoggerEnable;

		public static Color Lit = new Color(0.96f, 0.33f, 0.23f, 1f);

		public static void Awake(BaseUnityPlugin Plugin)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Expected O, but got Unknown
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Expected O, but got Unknown
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Expected O, but got Unknown
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Expected O, but got Unknown
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Expected O, but got Unknown
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Expected O, but got Unknown
			Enable = Plugin.Config.Bind<bool>("1. General", "Enable", true, new ConfigDescription("Enables or disables dungeon regeneration.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = 0,
				IsAdminOnly = true,
				EntryColor = Lit
			} }));
			Interval = Plugin.Config.Bind<float>("1. General", "Interval", 82800f, new ConfigDescription("Set the amount of seconds it takes each dungeon to try to regenerate.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = 1,
				IsAdminOnly = true
			} }));
			AllowedThemes = Plugin.Config.Bind<string>("1. General", "Themes", "Crypt, SunkenCrypt, Cave, ForestCrypt, DvergerTown", new ConfigDescription("Set allowed dungeon themes to reset. Possible themes are: Crypt, SunkenCrypt, Cave, ForestCrypt, GoblinCamp, MeadowsVillage, MeadowsFarm, DvergerTown, DvergerBoss", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = 2,
				IsAdminOnly = true
			} }));
			PlayerProtection = Plugin.Config.Bind<bool>("1. General", "Player Protection", true, new ConfigDescription("If enabled, dungeons won't reset while players are inside.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = 3,
				IsAdminOnly = true
			} }));
			PlayerProtectionInterval = Plugin.Config.Bind<float>("1. General", "Player Protection Interval", 600f, new ConfigDescription("Time it takes to retry a reset on a dungeon that wasn't reset due to Player Protection.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = 4,
				IsAdminOnly = true
			} }));
			CommandsEnable = Plugin.Config.Bind<bool>("2. Commands", "Enable", true, new ConfigDescription("Enables or disables commands.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = 5,
				IsAdminOnly = true,
				EntryColor = Lit
			} }));
			LoggerEnable = Plugin.Config.Bind<bool>("3. Logger", "Enable", true, new ConfigDescription("Enables or disables debugging logs.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				Order = 6,
				IsAdminOnly = false,
				EntryColor = Lit
			} }));
			Plugin.Config.SaveOnConfigSet = true;
		}
	}
	public static class DungeonExtensions
	{
		public static string GetCleanName(this DungeonGenerator dg)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			string text = ((Object)dg).name.Replace("(Clone)", "").Replace("(DungeonGenerator)", "").Trim();
			Vector3 position = ((Component)dg).transform.position;
			return text + " " + ((Vector3)(ref position)).ToString("F0");
		}

		public static void SetLastReset(this DungeonGenerator dg, DateTimeOffset dt)
		{
			if (dg == null)
			{
				return;
			}
			ZNetView nview = dg.m_nview;
			if (nview != null)
			{
				ZDO zDO = nview.GetZDO();
				if (zDO != null)
				{
					zDO.Set("Areas LastReset", dt.ToUnixTimeSeconds());
				}
			}
		}

		public static DateTimeOffset GetLastReset(this DungeonGenerator dg)
		{
			long? obj;
			if (dg == null)
			{
				obj = null;
			}
			else
			{
				ZNetView nview = dg.m_nview;
				if (nview == null)
				{
					obj = null;
				}
				else
				{
					ZDO zDO = nview.GetZDO();
					obj = ((zDO != null) ? new long?(zDO.GetLong("Areas LastReset", 0L)) : null);
				}
			}
			long? num = obj;
			return DateTimeOffset.FromUnixTimeSeconds(num.GetValueOrDefault());
		}

		public static float Remaining(this DungeonGenerator dungeon)
		{
			float num = (float)(DateTimeOffset.Now - dungeon.GetLastReset()).TotalSeconds;
			float value = Configs.Interval.Value;
			if (!(num > value))
			{
				return value - num;
			}
			return 0f;
		}

		public static bool IsOverdue(this DungeonGenerator dungeon)
		{
			return dungeon.Remaining() == 0f;
		}
	}
	public static class DicExtensions
	{
		public static bool RemoveAll<T, T2>(this Dictionary<T, T2> dictionary, T key)
		{
			int num = 0;
			while (dictionary.ContainsKey(key))
			{
				if (dictionary.Remove(key))
				{
					num++;
				}
			}
			return num > 0;
		}
	}
	public static class Commands
	{
		public static void Awake()
		{
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ResetClosest());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ResetLoaded());
		}
	}
	public class ResetClosest : ConsoleCommand
	{
		public override string Name => "dungeonresetclosest";

		public override string Help => "Force reset closest dungeon in (X,Z) distance.";

		public override void Run(string[] args)
		{
			if (!SynchronizationManager.Instance.PlayerIsAdmin)
			{
				Console.instance.Print("You are not an admin!");
				return;
			}
			DungeonGenerator closest = GetClosest();
			if ((Object)(object)closest == (Object)null)
			{
				Console.instance.Print("No dungeon found!");
				return;
			}
			Console.instance.Print("Forcing regeneration of Dungeon '" + closest.GetCleanName() + "', resetting now!");
			Dungeons.Reset(closest);
		}

		private static DungeonGenerator GetClosest()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			DungeonGenerator val = null;
			float num = float.MaxValue;
			foreach (Timer item in Timer.Each)
			{
				if (!((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)item.dungeon == (Object)null))
				{
					float num2 = Utils.DistanceXZ(((Component)Player.m_localPlayer).transform.position, ((Component)item.dungeon).transform.position);
					if ((Object)(object)val == (Object)null || num2 < num)
					{
						val = item.dungeon;
						num = num2;
					}
				}
			}
			return val;
		}
	}
	public class ResetLoaded : ConsoleCommand
	{
		public override string Name => "dungeonresetloaded";

		public override string Help => "Force reset all loaded dungeons.";

		public override void Run(string[] args)
		{
			if (!SynchronizationManager.Instance.PlayerIsAdmin)
			{
				Console.instance.Print("You are not an admin!");
				return;
			}
			int num = 0;
			foreach (Timer item in Timer.Each)
			{
				if (!((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)item.dungeon == (Object)null))
				{
					num++;
					Console.instance.Print("Forcing regeneration of Dungeon '" + item.dungeon.GetCleanName() + "', resetting now!");
					Dungeons.Reset(item.dungeon);
				}
			}
			if (num < 1)
			{
				Console.instance.Print("Could't find loaded dungeons!");
			}
			else
			{
				Console.instance.Print($"Forced a total of {num} dungeons to reset!");
			}
		}
	}
}

BepInEx/plugins/RandyKnapp-EpicLoot/EpicLoot.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
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 System.Xml;
using System.Xml.Linq;
using Auga;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Common;
using EpicLoot.Abilities;
using EpicLoot.Adventure;
using EpicLoot.Adventure.Feature;
using EpicLoot.Crafting;
using EpicLoot.CraftingV2;
using EpicLoot.Data;
using EpicLoot.GatedItemType;
using EpicLoot.Healing;
using EpicLoot.LegendarySystem;
using EpicLoot.LootBeams;
using EpicLoot.MagicItemEffects;
using EpicLoot.Patching;
using EpicLoot_UnityLib;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using ServerSync;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: Guid("963cf4f8-ba02-49fc-8884-97e781e6bc18")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright © Randy Knapp 2023")]
[assembly: AssemblyProduct("EpicLoot")]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyFileVersion("0.9.20")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Randy Knapp Mods")]
[assembly: AssemblyTitle("EpicLoot")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyDescription("")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.1", FrameworkDisplayName = ".NET Framework 4.6.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.9.20.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[<1230952a-f8e9-40f7-92bc-ee734705a1fd>Embedded]
	[CompilerGenerated]
	internal sealed class <1230952a-f8e9-40f7-92bc-ee734705a1fd>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<1230952a-f8e9-40f7-92bc-ee734705a1fd>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <524eb557-3b41-49bd-aaba-1299d919d441>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <524eb557-3b41-49bd-aaba-1299d919d441>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <524eb557-3b41-49bd-aaba-1299d919d441>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[<1230952a-f8e9-40f7-92bc-ee734705a1fd>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <6b053683-9e3e-4918-a43e-62d6d9d08a9e>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <6b053683-9e3e-4918-a43e-62d6d9d08a9e>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[<1230952a-f8e9-40f7-92bc-ee734705a1fd>Embedded]
	[CompilerGenerated]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public static class PlayerExtensions
{
	public static ZDO GetZDO(this Player player)
	{
		return ((Character)player).m_nview.GetZDO();
	}
}
namespace Common
{
	public class ConfigPositionedElement : MonoBehaviour
	{
		public ConfigEntry<TextAnchor> AnchorConfig;

		public ConfigEntry<Vector2> PositionConfig;

		protected RectTransform _rt;

		protected TextAnchor _currentAnchor;

		public virtual void Awake()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			_rt = (RectTransform)((Component)this).transform;
			EnsureCorrectPosition();
		}

		public virtual void Update()
		{
			EnsureCorrectPosition();
		}

		public virtual void EnsureCorrectPosition()
		{
			//IL_0012: 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_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected I4, but got Unknown
			//IL_002a: 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_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e4: Unknown result type (might be due to invalid IL or missing references)
			if (AnchorConfig != null && PositionConfig != null && (_currentAnchor != AnchorConfig.Value || !(_rt.anchoredPosition == PositionConfig.Value)))
			{
				_currentAnchor = AnchorConfig.Value;
				TextAnchor currentAnchor = _currentAnchor;
				TextAnchor val = currentAnchor;
				Vector2 val2 = default(Vector2);
				switch ((int)val)
				{
				case 0:
				{
					RectTransform rt25 = _rt;
					RectTransform rt26 = _rt;
					RectTransform rt27 = _rt;
					((Vector2)(ref val2))..ctor(0f, 1f);
					rt27.anchorMax = val2;
					Vector2 pivot = (rt26.anchorMin = val2);
					rt25.pivot = pivot;
					break;
				}
				case 1:
				{
					RectTransform rt22 = _rt;
					RectTransform rt23 = _rt;
					RectTransform rt24 = _rt;
					((Vector2)(ref val2))..ctor(0.5f, 1f);
					rt24.anchorMax = val2;
					Vector2 pivot = (rt23.anchorMin = val2);
					rt22.pivot = pivot;
					break;
				}
				case 2:
				{
					RectTransform rt19 = _rt;
					RectTransform rt20 = _rt;
					RectTransform rt21 = _rt;
					((Vector2)(ref val2))..ctor(1f, 1f);
					rt21.anchorMax = val2;
					Vector2 pivot = (rt20.anchorMin = val2);
					rt19.pivot = pivot;
					break;
				}
				case 3:
				{
					RectTransform rt16 = _rt;
					RectTransform rt17 = _rt;
					RectTransform rt18 = _rt;
					((Vector2)(ref val2))..ctor(0f, 0.5f);
					rt18.anchorMax = val2;
					Vector2 pivot = (rt17.anchorMin = val2);
					rt16.pivot = pivot;
					break;
				}
				case 4:
				{
					RectTransform rt13 = _rt;
					RectTransform rt14 = _rt;
					RectTransform rt15 = _rt;
					((Vector2)(ref val2))..ctor(0.5f, 0.5f);
					rt15.anchorMax = val2;
					Vector2 pivot = (rt14.anchorMin = val2);
					rt13.pivot = pivot;
					break;
				}
				case 5:
				{
					RectTransform rt10 = _rt;
					RectTransform rt11 = _rt;
					RectTransform rt12 = _rt;
					((Vector2)(ref val2))..ctor(1f, 0.5f);
					rt12.anchorMax = val2;
					Vector2 pivot = (rt11.anchorMin = val2);
					rt10.pivot = pivot;
					break;
				}
				case 6:
				{
					RectTransform rt7 = _rt;
					RectTransform rt8 = _rt;
					RectTransform rt9 = _rt;
					((Vector2)(ref val2))..ctor(0f, 0f);
					rt9.anchorMax = val2;
					Vector2 pivot = (rt8.anchorMin = val2);
					rt7.pivot = pivot;
					break;
				}
				case 7:
				{
					RectTransform rt4 = _rt;
					RectTransform rt5 = _rt;
					RectTransform rt6 = _rt;
					((Vector2)(ref val2))..ctor(0.5f, 0f);
					rt6.anchorMax = val2;
					Vector2 pivot = (rt5.anchorMin = val2);
					rt4.pivot = pivot;
					break;
				}
				case 8:
				{
					RectTransform rt = _rt;
					RectTransform rt2 = _rt;
					RectTransform rt3 = _rt;
					((Vector2)(ref val2))..ctor(1f, 0f);
					rt3.anchorMax = val2;
					Vector2 pivot = (rt2.anchorMin = val2);
					rt.pivot = pivot;
					break;
				}
				}
				_rt.anchoredPosition = PositionConfig.Value;
			}
		}
	}
	[Serializable]
	public class RecipeRequirementConfig
	{
		public string item = "";

		public int amount = 1;
	}
	[Serializable]
	public class RecipeConfig
	{
		public string name = "";

		public string item = "";

		public int amount = 1;

		public string craftingStation = "";

		public int minStationLevel = 1;

		public bool enabled = true;

		public string repairStation = "";

		public List<RecipeRequirementConfig> resources = new List<RecipeRequirementConfig>();
	}
	[Serializable]
	public class RecipesConfig
	{
		public List<RecipeConfig> recipes = new List<RecipeConfig>();
	}
	public static class GameObjectExtensions
	{
		public static RectTransform RectTransform(this GameObject go)
		{
			Transform transform = go.transform;
			return (RectTransform)(object)((transform is RectTransform) ? transform : null);
		}

		public static T RequireComponent<T>(this GameObject go) where T : Component
		{
			T component = go.GetComponent<T>();
			return ((Object)(object)component == (Object)null) ? go.AddComponent<T>() : component;
		}
	}
	public class GotDestroyed : MonoBehaviour
	{
		public void OnDisable()
		{
			Debug.LogError((object)("I got destroyed! (" + ((Object)((Component)this).gameObject).name + ")"));
			Debug.Log((object)Environment.StackTrace);
		}
	}
	public class MultiValueDictionary<TKey, TValue> : Dictionary<TKey, List<TValue>>
	{
		public void Add(TKey key, TValue value)
		{
			if (!TryGetValue(key, out var value2))
			{
				value2 = new List<TValue>();
				Add(key, value2);
			}
			value2.Add(value);
		}

		public bool ContainsValue(TKey key, TValue value)
		{
			if (TryGetValue(key, out var value2))
			{
				return value2.Contains(value);
			}
			return false;
		}

		public void Remove(TKey key, TValue value)
		{
			if (TryGetValue(key, out var value2))
			{
				value2.Remove(value);
				if (value2.Count <= 0)
				{
					Remove(key);
				}
			}
		}

		public void Merge(MultiValueDictionary<TKey, TValue> toMergeWith)
		{
			if (toMergeWith == null)
			{
				return;
			}
			foreach (KeyValuePair<TKey, List<TValue>> item in toMergeWith)
			{
				foreach (TValue item2 in item.Value)
				{
					Add(item.Key, item2);
				}
			}
		}

		public List<TValue> GetValues(TKey key, bool returnEmptySet = false)
		{
			if (!TryGetValue(key, out var value) && returnEmptySet)
			{
				return new List<TValue>();
			}
			return value;
		}
	}
	public static class PrefabCreator
	{
		public static ManualLogSource Logger;

		public static Dictionary<string, CraftingStation> CraftingStations;

		public static T RequireComponent<T>(GameObject go) where T : Component
		{
			T val = go.GetComponent<T>();
			if ((Object)(object)val == (Object)null)
			{
				val = go.AddComponent<T>();
			}
			return val;
		}

		public static void Reset()
		{
			CraftingStations = null;
		}

		private static void InitCraftingStations()
		{
			if (CraftingStations != null)
			{
				return;
			}
			CraftingStations = new Dictionary<string, CraftingStation>();
			foreach (Recipe recipe in ObjectDB.instance.m_recipes)
			{
				if ((Object)(object)recipe.m_craftingStation != (Object)null && !CraftingStations.ContainsKey(((Object)recipe.m_craftingStation).name))
				{
					CraftingStations.Add(((Object)recipe.m_craftingStation).name, recipe.m_craftingStation);
				}
			}
		}

		public static Recipe CreateRecipe(string name, string itemId, RecipeConfig recipeConfig)
		{
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Expected O, but got Unknown
			InitCraftingStations();
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(itemId);
			if ((Object)(object)itemPrefab == (Object)null)
			{
				ManualLogSource logger = Logger;
				if (logger != null)
				{
					logger.LogWarning((object)("[PrefabCreator] Could not find item prefab (" + itemId + ")"));
				}
				return null;
			}
			Recipe val = ScriptableObject.CreateInstance<Recipe>();
			((Object)val).name = name;
			val.m_amount = recipeConfig.amount;
			val.m_minStationLevel = recipeConfig.minStationLevel;
			val.m_item = itemPrefab.GetComponent<ItemDrop>();
			val.m_enabled = recipeConfig.enabled;
			if (!string.IsNullOrEmpty(recipeConfig.craftingStation))
			{
				if (!CraftingStations.ContainsKey(recipeConfig.craftingStation))
				{
					ManualLogSource logger2 = Logger;
					if (logger2 != null)
					{
						logger2.LogWarning((object)("[PrefabCreator] Could not find crafting station (" + itemId + "): " + recipeConfig.craftingStation));
					}
					string text = string.Join(", ", CraftingStations.Keys);
					ManualLogSource logger3 = Logger;
					if (logger3 != null)
					{
						logger3.LogInfo((object)("[PrefabCreator] Available Stations: " + text));
					}
				}
				else
				{
					val.m_craftingStation = CraftingStations[recipeConfig.craftingStation];
				}
			}
			if (!string.IsNullOrEmpty(recipeConfig.repairStation))
			{
				if (!CraftingStations.ContainsKey(recipeConfig.repairStation))
				{
					ManualLogSource logger4 = Logger;
					if (logger4 != null)
					{
						logger4.LogWarning((object)("[PrefabCreator] Could not find repair station (" + itemId + "): " + recipeConfig.repairStation));
					}
					string text2 = string.Join(", ", CraftingStations.Keys);
					ManualLogSource logger5 = Logger;
					if (logger5 != null)
					{
						logger5.LogInfo((object)("[PrefabCreator] Available Stations: " + text2));
					}
				}
				else
				{
					val.m_repairStation = CraftingStations[recipeConfig.repairStation];
				}
			}
			List<Requirement> list = new List<Requirement>();
			foreach (RecipeRequirementConfig resource in recipeConfig.resources)
			{
				GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab(resource.item);
				if ((Object)(object)itemPrefab2 == (Object)null)
				{
					ManualLogSource logger6 = Logger;
					if (logger6 != null)
					{
						logger6.LogError((object)("[PrefabCreator] Could not find requirement item (" + itemId + "): " + resource.item));
					}
				}
				else
				{
					list.Add(new Requirement
					{
						m_amount = resource.amount,
						m_resItem = itemPrefab2.GetComponent<ItemDrop>()
					});
				}
			}
			val.m_resources = list.ToArray();
			return val;
		}

		public static Recipe AddNewRecipe(string name, string itemId, RecipeConfig recipeConfig)
		{
			Recipe val = CreateRecipe(name, itemId, recipeConfig);
			if ((Object)(object)val == (Object)null)
			{
				ManualLogSource logger = Logger;
				if (logger != null)
				{
					logger.LogError((object)("[PrefabCreator] Failed to create recipe (" + name + ")"));
				}
				return null;
			}
			return AddNewRecipe(val);
		}

		public static Recipe AddNewRecipe(Recipe recipe)
		{
			int num = ObjectDB.instance.m_recipes.RemoveAll((Recipe x) => ((Object)x).name == ((Object)recipe).name);
			if (num > 0)
			{
				ManualLogSource logger = Logger;
				if (logger != null)
				{
					logger.LogInfo((object)$"[PrefabCreator] Removed recipe ({((Object)recipe).name}): {num}");
				}
			}
			ObjectDB.instance.m_recipes.Add(recipe);
			ManualLogSource logger2 = Logger;
			if (logger2 != null)
			{
				logger2.LogInfo((object)("[PrefabCreator] Added recipe: " + ((Object)recipe).name));
			}
			return recipe;
		}
	}
	[Serializable]
	public struct SerializableVector3
	{
		public float x;

		public float y;

		public float z;

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

		public void ToPackage(ZPackage pkg)
		{
			pkg.Write(x);
			pkg.Write(y);
			pkg.Write(z);
		}

		public static SerializableVector3 FromPackage(ZPackage pkg)
		{
			SerializableVector3 result = default(SerializableVector3);
			result.x = pkg.ReadSingle();
			result.y = pkg.ReadSingle();
			result.z = pkg.ReadSingle();
			return result;
		}

		public override string ToString()
		{
			return $"[{x}, {y}, {z}]";
		}

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

		public static implicit operator SerializableVector3(Vector3 v)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return new SerializableVector3(v.x, v.y, v.z);
		}

		public static SerializableVector3 operator +(SerializableVector3 a, SerializableVector3 b)
		{
			return new SerializableVector3(a.x + b.x, a.y + b.y, a.z + b.z);
		}

		public static SerializableVector3 operator -(SerializableVector3 a, SerializableVector3 b)
		{
			return new SerializableVector3(a.x - b.x, a.y - b.y, a.z - b.z);
		}

		public static SerializableVector3 operator -(SerializableVector3 a)
		{
			return new SerializableVector3(0f - a.x, 0f - a.y, 0f - a.z);
		}

		public static SerializableVector3 operator *(SerializableVector3 a, float m)
		{
			return new SerializableVector3(a.x * m, a.y * m, a.z * m);
		}

		public static SerializableVector3 operator *(float m, SerializableVector3 a)
		{
			return new SerializableVector3(a.x * m, a.y * m, a.z * m);
		}

		public static SerializableVector3 operator /(SerializableVector3 a, float d)
		{
			return new SerializableVector3(a.x / d, a.y / d, a.z / d);
		}
	}
	public static class Utils
	{
		public static void PrintObject(object o)
		{
			if (o == null)
			{
				Debug.Log((object)"null");
			}
			else
			{
				Debug.Log((object)(o?.ToString() + ":\n" + GetObjectString(o, "  ")));
			}
		}

		public static string GetObjectString(object obj, string indent)
		{
			string text = "";
			Type type = obj.GetType();
			IEnumerable<FieldInfo> enumerable = from f in type.GetFields()
				where f.IsPublic
				select f;
			foreach (FieldInfo item in enumerable)
			{
				object value = item.GetValue(obj);
				string text2 = ((value == null) ? "null" : value.ToString());
				text = text + "\n" + indent + item.Name + ": " + text2;
			}
			return text;
		}

		public static Sprite LoadSpriteFromFile(string spritePath)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			spritePath = Path.Combine(Paths.PluginPath, spritePath);
			if (File.Exists(spritePath))
			{
				byte[] array = File.ReadAllBytes(spritePath);
				Texture2D val = new Texture2D(20, 20);
				if (ImageConversion.LoadImage(val, array))
				{
					return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), default(Vector2), 100f);
				}
			}
			return null;
		}

		public static Sprite LoadSpriteFromFile(string modFolder, string iconName)
		{
			string spritePath = Path.Combine(modFolder, iconName);
			return LoadSpriteFromFile(spritePath);
		}

		public static string RemoveBetween(string s, string from, string to)
		{
			int num = 0;
			while (num >= 0)
			{
				num = s.IndexOf(from, StringComparison.InvariantCulture);
				if (num < 0)
				{
					break;
				}
				int num2 = s.IndexOf(to, num, StringComparison.InvariantCulture);
				if (num2 < 0)
				{
					break;
				}
				s = s.Remove(num, num2 - num + to.Length);
			}
			return s;
		}

		public static void CopyFields(object originalObject, object cloneObject, Type typeToReflect, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public)
		{
			FieldInfo[] fields = typeToReflect.GetFields(bindingFlags);
			foreach (FieldInfo fieldInfo in fields)
			{
				object value = fieldInfo.GetValue(originalObject);
				fieldInfo.SetValue(cloneObject, value);
			}
		}

		public static bool IsServer()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Invalid comparison between Unknown and I4
			return ZNet.instance.IsServer() || ZNet.instance.IsDedicated() || (int)SystemInfo.graphicsDeviceType == 4;
		}
	}
	public static class ArrayUtils
	{
		public static bool IsNullOrEmpty<T>(T[] a)
		{
			return a == null || a.Length == 0;
		}

		public static T[] Copy<T>(T[] other)
		{
			return other?.ToArray();
		}
	}
	public static class ListExtensions
	{
		public static bool TryFind<T>(this List<T> list, Predicate<T> predicate, out T result)
		{
			int num = list.FindIndex(predicate);
			if (num != -1)
			{
				result = list[num];
				return true;
			}
			result = default(T);
			return false;
		}
	}
	public class WeightedRandomCollection<T>
	{
		private readonly Random _random;

		private List<T> _list;

		private Func<T, float> _weightSelector;

		private bool _removeOnSelect;

		public float TotalWeight { get; private set; }

		public WeightedRandomCollection(Random random)
		{
			_random = random;
		}

		public WeightedRandomCollection(Random random, IEnumerable<T> collection, Func<T, float> weightSelector, bool removeOnSelect = false)
		{
			_random = random ?? new Random();
			Setup(collection, weightSelector, removeOnSelect);
		}

		public void Setup(IEnumerable<T> collection, Func<T, float> weightSelector, bool removeOnSelect = false)
		{
			_list = collection.ToList();
			_weightSelector = weightSelector;
			_removeOnSelect = removeOnSelect;
			TotalWeight = _list.Sum(_weightSelector);
		}

		public T Roll()
		{
			if (_list == null)
			{
				return default(T);
			}
			float num = (float)_random.NextDouble() * TotalWeight;
			float num2 = 0f;
			T val = default(T);
			foreach (var item in _list.Select((T weightedItem) => new
			{
				Value = weightedItem,
				Weight = _weightSelector(weightedItem)
			}))
			{
				num2 += item.Weight;
				if (num2 >= num)
				{
					val = item.Value;
					break;
				}
			}
			if (_removeOnSelect)
			{
				_list.Remove(val);
				TotalWeight = _list.Sum(_weightSelector);
			}
			return val;
		}

		public List<T> Roll(int numberOfRolls)
		{
			if (_list == null)
			{
				return null;
			}
			List<T> list = new List<T>();
			for (int i = 0; i < numberOfRolls; i++)
			{
				T x = Roll();
				if (!EqualityComparer<T>.Default.Equals(x, default(T)))
				{
					list.Add(Roll());
				}
			}
			return list;
		}

		public void Reset()
		{
			_list = null;
			_weightSelector = null;
			_removeOnSelect = false;
			TotalWeight = 0f;
		}
	}
}
namespace EpicLoot
{
	[HarmonyPatch]
	public static class Attack_Patch
	{
		public static Attack ActiveAttack;

		[HarmonyPatch(typeof(Attack), "DoMeleeAttack")]
		[HarmonyPriority(0)]
		[HarmonyPrefix]
		public static void Attack_DoMeleeAttack_Prefix(Attack __instance)
		{
			ActiveAttack = __instance;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Attack), "DoMeleeAttack")]
		public static void Attack_DoMeleeAttack_Postfix()
		{
			ActiveAttack = null;
		}
	}
	[HarmonyPatch(typeof(Hud), "Awake")]
	public static class Hud_Awake_Patch
	{
		public static void Postfix(Hud __instance)
		{
			GameObject val = Object.Instantiate<GameObject>(EpicLoot.Assets.DebugTextPrefab, __instance.m_rootObject.transform, false);
			val.AddComponent<DebugText>();
		}
	}
	public class DebugText : MonoBehaviour
	{
		public Text Label;

		private static DebugText _instance;

		public void Awake()
		{
			_instance = this;
			Label = ((Component)this).GetComponentInChildren<Text>();
			((Component)this).gameObject.SetActive(false);
		}

		public void OnDestroy()
		{
			_instance = null;
		}

		public static void SetText(string s)
		{
			_instance.Label.text = s;
		}
	}
	public static class EpicLootAuga
	{
		public static Button ReplaceButton(Button button, bool icon = false, bool keepListeners = false)
		{
			Button newButton = API.MediumButton_Create(((Component)button).transform.parent, ((Object)button).name, string.Empty);
			return ReplaceButtonInternal(newButton, button, icon, keepListeners);
		}

		public static Button ReplaceButtonFancy(Button button, bool icon = false, bool keepListeners = false)
		{
			Button newButton = API.FancyButton_Create(((Component)button).transform.parent, ((Object)button).name, string.Empty);
			return ReplaceButtonInternal(newButton, button, icon, keepListeners);
		}

		private static Button ReplaceButtonInternal(Button newButton, Button button, bool icon, bool keepListeners)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			if (icon)
			{
				Object.Destroy((Object)(object)((Component)((Component)newButton).GetComponentInChildren<Text>()).gameObject);
				Transform val = Object.Instantiate<Transform>(((Component)button).transform.Find("Icon"), ((Component)newButton).transform);
				((Object)val).name = "Icon";
			}
			else
			{
				string text = ((Component)button).GetComponentInChildren<Text>().text;
				((Component)newButton).GetComponentInChildren<Text>().text = text;
			}
			RectTransform val2 = (RectTransform)((Component)button).transform;
			RectTransform val3 = (RectTransform)((Component)newButton).transform;
			val3.anchorMin = val2.anchorMin;
			val3.anchorMax = val2.anchorMax;
			val3.pivot = val2.pivot;
			val3.anchoredPosition = val2.anchoredPosition;
			Rect rect = val2.rect;
			val3.SetSizeWithCurrentAnchors((Axis)0, ((Rect)(ref rect)).width);
			if (keepListeners)
			{
				newButton.onClick = button.onClick;
				button.onClick = new ButtonClickedEvent();
			}
			UIGamePad component = ((Component)button).GetComponent<UIGamePad>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.m_hint != (Object)null)
			{
				component.m_hint.transform.SetParent(((Component)newButton).transform);
				UIGamePad val4 = ((Component)newButton).gameObject.AddComponent<UIGamePad>();
				val4.m_keyCode = component.m_keyCode;
				val4.m_zinputKey = component.m_zinputKey;
				val4.m_hint = component.m_hint;
				val4.m_blockingElements = component.m_blockingElements.ToList();
			}
			Object.DestroyImmediate((Object)(object)((Component)button).gameObject);
			return newButton;
		}

		public static void MakeSimpleTooltip(GameObject obj)
		{
			API.Tooltip_MakeSimpleTooltip(obj);
		}

		public static void ReplaceBackground(GameObject obj, bool withCornerDecoration)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: 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)
			Image component = obj.GetComponent<Image>();
			Object.Destroy((Object)(object)component);
			GameObject val = API.Panel_Create(obj.transform, Vector2.one, "AugaBackground", withCornerDecoration);
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetSiblingIndex(0);
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.one;
			val2.pivot = new Vector2(0.5f, 0.5f);
			val2.sizeDelta = new Vector2(40f, 40f);
		}

		public static void FixItemBG(GameObject obj)
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			Transform val = obj.transform.Find("MagicBG");
			if ((Object)(object)val != (Object)null)
			{
				Image component = ((Component)val).GetComponent<Image>();
				if ((Object)(object)component != (Object)null)
				{
					component.sprite = EpicLoot.GetMagicItemBgSprite();
				}
			}
			bool flag = false;
			Transform val2 = obj.transform.Find("ItemBG");
			Image val3 = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponent<Image>() : null);
			if ((Object)(object)val3 == (Object)null)
			{
				val3 = obj.GetComponent<Image>();
			}
			if ((Object)(object)val3 != (Object)null)
			{
				val3.sprite = API.GetItemBackgroundSprite();
				((Graphic)val3).color = new Color(0f, 0f, 0f, 0.5f);
				flag = true;
			}
			if (!flag)
			{
				Transform val4 = obj.transform.Find("Icon");
				if ((Object)(object)val4 != (Object)null)
				{
					Transform val5 = Object.Instantiate<Transform>(val4, val4.parent);
					val5.SetSiblingIndex(2);
					Image component2 = ((Component)val5).GetComponent<Image>();
					component2.sprite = API.GetItemBackgroundSprite();
					((Graphic)component2).color = new Color(0f, 0f, 0f, 0.5f);
				}
			}
		}

		public static void FixListElementColors(GameObject obj)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			Transform val = obj.transform.Find("Selected");
			if ((Object)(object)val != (Object)null)
			{
				Image component = ((Component)val).GetComponent<Image>();
				if ((Object)(object)component != (Object)null)
				{
					Color color = default(Color);
					ColorUtility.TryParseHtmlString(API.Blue, ref color);
					((Graphic)component).color = color;
				}
			}
			Transform val2 = obj.transform.Find("Background");
			if ((Object)(object)val2 != (Object)null)
			{
				Image component2 = ((Component)val2).GetComponent<Image>();
				if ((Object)(object)component2 != (Object)null)
				{
					((Graphic)component2).color = new Color(0f, 0f, 0f, 0.5f);
				}
			}
			Button component3 = obj.GetComponent<Button>();
			if ((Object)(object)component3 != (Object)null)
			{
				((Selectable)component3).colors = ColorBlock.defaultColorBlock;
			}
		}

		public static void FixFonts(GameObject obj)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			Text[] componentsInChildren = obj.GetComponentsInChildren<Text>(true);
			Text[] array = componentsInChildren;
			Color color = default(Color);
			Color color2 = default(Color);
			foreach (Text val in array)
			{
				if (((Object)val.font).name == "Norsebold")
				{
					val.font = API.GetBoldFont();
					ColorUtility.TryParseHtmlString(API.Brown1, ref color);
					((Graphic)val).color = color;
					val.text = Localization.instance.Localize(val.text).ToUpperInvariant();
				}
				else
				{
					val.font = API.GetSemiBoldFont();
				}
				if (((Object)val).name == "Count" || ((Object)val).name == "RewardLabel" || ((Object)val).name.EndsWith("Count"))
				{
					ColorUtility.TryParseHtmlString(API.BrightGold, ref color2);
					((Graphic)val).color = color2;
				}
				val.text = val.text.Replace("<color=yellow>", "<color=" + API.BrightGold + ">");
			}
		}

		public static Button ReplaceVerticalLargeTab(Button button)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_005a: 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_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = EpicLoot.LoadAsset<GameObject>("EnchantingTabAuga");
			GameObject val2 = Object.Instantiate<GameObject>(val, ((Component)button).transform.parent);
			((Object)val2).name = ((Object)button).name;
			FixFonts(val2);
			int siblingIndex = ((Component)button).transform.GetSiblingIndex();
			RectTransform val3 = (RectTransform)((Component)button).transform;
			RectTransform val4 = (RectTransform)val2.transform;
			val4.anchorMin = val3.anchorMin;
			val4.anchorMax = val3.anchorMax;
			val4.pivot = val3.pivot;
			val4.anchoredPosition = val3.anchoredPosition;
			Rect rect = val3.rect;
			val4.SetSizeWithCurrentAnchors((Axis)0, ((Rect)(ref rect)).width);
			((Component)val2.transform.Find("Text")).GetComponent<Text>().text = ((Component)((Component)button).transform.Find("Text")).GetComponent<Text>().text;
			((Component)val2.transform.Find("Image")).GetComponent<Image>().sprite = ((Component)((Component)button).transform.Find("Image")).GetComponent<Image>().sprite;
			FeatureStatus component = val2.GetComponent<FeatureStatus>();
			FeatureStatus component2 = ((Component)button).GetComponent<FeatureStatus>();
			if ((Object)(object)component2 == (Object)null && (Object)(object)component != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)component);
			}
			if ((Object)(object)component != (Object)null && (Object)(object)component2 != (Object)null)
			{
				component.Feature = component2.Feature;
				component.Refresh();
			}
			Object.DestroyImmediate((Object)(object)((Component)button).gameObject);
			val2.transform.SetSiblingIndex(siblingIndex);
			return val2.GetComponent<Button>();
		}

		public static void FixupScrollbar(Scrollbar scrollbar)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			Object.Destroy((Object)(object)((Component)scrollbar).GetComponent<Image>());
			((Selectable)scrollbar).colors = ColorBlock.defaultColorBlock;
			Image component = ((Component)scrollbar.handleRect).GetComponent<Image>();
			Color val = default(Color);
			if (ColorUtility.TryParseHtmlString("#8B7C6A", ref val))
			{
				((Graphic)component).color = new Color(val.r, val.g, val.b, 1f);
			}
		}
	}
	[HarmonyPatch(typeof(GameCamera), "UpdateCamera")]
	public static class GameCamera_UpdateCamera_Patch
	{
		public static bool Prefix(GameCamera __instance)
		{
			if (__instance.m_freeFly)
			{
				__instance.UpdateFreeFly(1f / 30f);
				__instance.UpdateCameraShake(1f / 30f);
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Humanoid))]
	public class Humanoid_Patch
	{
		[HarmonyPatch("SetupVisEquipment")]
		[HarmonyPrefix]
		public static bool SetupVisEquipment_Prefix(Humanoid __instance, VisEquipment visEq, bool isRagdoll)
		{
			if (!isRagdoll)
			{
				object obj;
				if (__instance.m_leftItem == null)
				{
					obj = "";
				}
				else
				{
					ItemData leftItem = __instance.m_leftItem;
					if (leftItem == null)
					{
						obj = null;
					}
					else
					{
						GameObject dropPrefab = leftItem.m_dropPrefab;
						obj = ((dropPrefab != null) ? ((Object)dropPrefab).name : null);
					}
				}
				visEq.SetLeftItem((string)obj, __instance.m_leftItem?.m_variant ?? 0);
				object rightItem;
				if (__instance.m_rightItem == null)
				{
					rightItem = "";
				}
				else
				{
					ItemData rightItem2 = __instance.m_rightItem;
					if (rightItem2 == null)
					{
						rightItem = null;
					}
					else
					{
						GameObject dropPrefab2 = rightItem2.m_dropPrefab;
						rightItem = ((dropPrefab2 != null) ? ((Object)dropPrefab2).name : null);
					}
				}
				visEq.SetRightItem((string)rightItem);
				if (((Character)__instance).IsPlayer())
				{
					object obj2;
					if (__instance.m_hiddenLeftItem == null)
					{
						obj2 = "";
					}
					else
					{
						GameObject dropPrefab3 = __instance.m_hiddenLeftItem.m_dropPrefab;
						obj2 = ((dropPrefab3 != null) ? ((Object)dropPrefab3).name : null);
					}
					visEq.SetLeftBackItem((string)obj2, __instance.m_hiddenLeftItem?.m_variant ?? 0);
					object rightBackItem;
					if (__instance.m_hiddenRightItem == null)
					{
						rightBackItem = "";
					}
					else
					{
						GameObject dropPrefab4 = __instance.m_hiddenRightItem.m_dropPrefab;
						rightBackItem = ((dropPrefab4 != null) ? ((Object)dropPrefab4).name : null);
					}
					visEq.SetRightBackItem((string)rightBackItem);
				}
			}
			object chestItem;
			if (__instance.m_chestItem == null)
			{
				chestItem = "";
			}
			else
			{
				ItemData chestItem2 = __instance.m_chestItem;
				if (chestItem2 == null)
				{
					chestItem = null;
				}
				else
				{
					GameObject dropPrefab5 = chestItem2.m_dropPrefab;
					chestItem = ((dropPrefab5 != null) ? ((Object)dropPrefab5).name : null);
				}
			}
			visEq.SetChestItem((string)chestItem);
			object legItem;
			if (__instance.m_legItem == null)
			{
				legItem = "";
			}
			else
			{
				ItemData legItem2 = __instance.m_legItem;
				if (legItem2 == null)
				{
					legItem = null;
				}
				else
				{
					GameObject dropPrefab6 = legItem2.m_dropPrefab;
					legItem = ((dropPrefab6 != null) ? ((Object)dropPrefab6).name : null);
				}
			}
			visEq.SetLegItem((string)legItem);
			object helmetItem;
			if (__instance.m_helmetItem == null)
			{
				helmetItem = "";
			}
			else
			{
				ItemData helmetItem2 = __instance.m_helmetItem;
				if (helmetItem2 == null)
				{
					helmetItem = null;
				}
				else
				{
					GameObject dropPrefab7 = helmetItem2.m_dropPrefab;
					helmetItem = ((dropPrefab7 != null) ? ((Object)dropPrefab7).name : null);
				}
			}
			visEq.SetHelmetItem((string)helmetItem);
			object obj3;
			if (__instance.m_shoulderItem == null)
			{
				obj3 = "";
			}
			else
			{
				ItemData shoulderItem = __instance.m_shoulderItem;
				if (shoulderItem == null)
				{
					obj3 = null;
				}
				else
				{
					GameObject dropPrefab8 = shoulderItem.m_dropPrefab;
					obj3 = ((dropPrefab8 != null) ? ((Object)dropPrefab8).name : null);
				}
			}
			visEq.SetShoulderItem((string)obj3, __instance.m_shoulderItem?.m_variant ?? 0);
			object utilityItem;
			if (__instance.m_utilityItem == null)
			{
				utilityItem = "";
			}
			else
			{
				ItemData utilityItem2 = __instance.m_utilityItem;
				if (utilityItem2 == null)
				{
					utilityItem = null;
				}
				else
				{
					GameObject dropPrefab9 = utilityItem2.m_dropPrefab;
					utilityItem = ((dropPrefab9 != null) ? ((Object)dropPrefab9).name : null);
				}
			}
			visEq.SetUtilityItem((string)utilityItem);
			if (!((Character)__instance).IsPlayer())
			{
				return false;
			}
			visEq.SetBeardItem(__instance.m_beardItem);
			visEq.SetHairItem(__instance.m_hairItem);
			return false;
		}
	}
	public static class EpicLootDropsHelper
	{
		public static bool InstantDropsEnabled { get; set; }
	}
	[HarmonyPatch(typeof(CharacterDrop), "OnDeath")]
	public static class CharacterDrop_OnDeath_Patch
	{
		public static void Postfix(CharacterDrop __instance)
		{
			if (EpicLootDropsHelper.InstantDropsEnabled)
			{
				EpicLoot.OnCharacterDeath(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Ragdoll), "Setup")]
	public static class Ragdoll_Setup_Patch
	{
		public static void Postfix(Ragdoll __instance, CharacterDrop characterDrop)
		{
			if (!((Object)(object)characterDrop == (Object)null) && !((Object)(object)characterDrop.m_character == (Object)null) && !characterDrop.m_character.IsPlayer() && EpicLoot.CanCharacterDropLoot(characterDrop.m_character))
			{
				EpicLootDropsHelper.InstantDropsEnabled = false;
				string characterCleanName = EpicLoot.GetCharacterCleanName(characterDrop.m_character);
				int level = characterDrop.m_character.GetLevel();
				__instance.m_nview.m_zdo.Set("characterName", characterCleanName);
				__instance.m_nview.m_zdo.Set("level", level);
			}
		}
	}
	[HarmonyPatch(typeof(Ragdoll), "SpawnLoot")]
	public static class Ragdoll_SpawnLoot_Patch
	{
		public static void Postfix(Ragdoll __instance, Vector3 center)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			string @string = __instance.m_nview.m_zdo.GetString("characterName", "");
			int @int = __instance.m_nview.m_zdo.GetInt("level", 0);
			if (!string.IsNullOrEmpty(@string))
			{
				EpicLoot.OnCharacterDeath(@string, @int, center + Vector3.up * 0.75f);
			}
		}
	}
	[HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")]
	public static class CharacterDrop_GenerateDropList_DropsEnabled
	{
		[HarmonyBefore(new string[] { "org.bepinex.plugins.creaturelevelcontrol" })]
		[HarmonyPriority(800)]
		public static void Postfix(CharacterDrop __instance)
		{
			EpicLootDropsHelper.InstantDropsEnabled = __instance.m_dropsEnabled;
		}
	}
	[HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")]
	public static class CharacterDrop_GenerateDropList_Patch
	{
		public static void Postfix(CharacterDrop __instance, ref List<KeyValuePair<GameObject, int>> __result)
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Invalid comparison between Unknown and I4
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)__instance.m_character != (Object)null) || !__instance.m_character.IsBoss() || EpicLoot.GetBossTrophyDropMode() == BossDropMode.Default)
			{
				return;
			}
			for (int i = 0; i < __result.Count; i++)
			{
				GameObject key = __result[i].Key;
				ItemDrop component = key.GetComponent<ItemDrop>();
				if (!((Object)(object)component == (Object)null) && component.m_itemData != null && (int)component.m_itemData.m_shared.m_itemType == 13)
				{
					List<PlayerInfo> playerList = ZNet.instance.GetPlayerList();
					int num = EpicLoot.GetBossTrophyDropMode() switch
					{
						BossDropMode.OnePerPlayerOnServer => playerList.Count, 
						BossDropMode.OnePerPlayerNearBoss => Math.Max(Player.GetPlayersInRangeXZ(((Component)__instance.m_character).transform.position, EpicLoot.GetBossTrophyDropPlayerRange()), playerList.Count((PlayerInfo x) => Vector3.Distance(x.m_position, ((Component)__instance.m_character).transform.position) <= EpicLoot.GetBossTrophyDropPlayerRange())), 
						_ => 1, 
					};
					EpicLoot.Log($"Dropping trophies: {num} (mode={EpicLoot.GetBossTrophyDropMode()})");
					__result[i] = new KeyValuePair<GameObject, int>(key, num);
				}
			}
		}
	}
	public class Multiplayer_Player_Patch
	{
		[HarmonyPatch]
		public static class Humanoid_Patch
		{
			[HarmonyPatch(typeof(Humanoid), "EquipItem")]
			public class AttachExtendedDataToZDO_Humanoid_EquipItem_Patch
			{
				[UsedImplicitly]
				private static void Postfix(ItemData item, bool __result, Humanoid __instance)
				{
					//IL_001d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0029: Expected O, but got Unknown
					if (__result && (Object)(object)__instance == (Object)(object)Player.m_localPlayer && item != null)
					{
						UpdatePlayerZDOForEquipment((Player)__instance, item, equip: true);
					}
				}
			}

			[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
			public class AttachExtendedDataToZDO_Humanoid_UnequipItem_Patch
			{
				[UsedImplicitly]
				private static void Prefix(Humanoid __instance, ItemData item)
				{
					//IL_0024: Unknown result type (might be due to invalid IL or missing references)
					//IL_0030: Expected O, but got Unknown
					if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && item != null && ((Humanoid)Player.m_localPlayer).IsItemEquiped(item))
					{
						UpdatePlayerZDOForEquipment((Player)__instance, item, equip: false);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "Update")]
		public static class WatchLegendaryEquipment_Player_Update_Patch
		{
			private static float _updateEventTime;

			[UsedImplicitly]
			public static void Postfix(Player __instance)
			{
				_updateEventTime -= Time.deltaTime;
				if ((double)_updateEventTime > 0.0)
				{
					return;
				}
				_updateEventTime = 10f;
				if ((Object)(object)__instance != (Object)null && (Object)(object)__instance != (Object)(object)Player.m_localPlayer && (Object)(object)((Character)__instance).m_nview != (Object)null)
				{
					ZDO zDO = ((Character)__instance).m_nview.GetZDO();
					if (zDO != null && (DoCheck(__instance, zDO, "LeftItem", "lf-ell", ref ((Humanoid)__instance).m_leftItem) || DoCheck(__instance, zDO, "RightItem", "ri-ell", ref ((Humanoid)__instance).m_rightItem) || DoCheck(__instance, zDO, "ChestItem", "ch-ell", ref ((Humanoid)__instance).m_chestItem) || DoCheck(__instance, zDO, "LegItem", "lg-ell", ref ((Humanoid)__instance).m_legItem) || DoCheck(__instance, zDO, "HelmetItem", "hl-ell", ref ((Humanoid)__instance).m_helmetItem) || DoCheck(__instance, zDO, "ShoulderItem", "sh-ell", ref ((Humanoid)__instance).m_shoulderItem) || DoCheck(__instance, zDO, "UtilityItem", "ut-ell", ref ((Humanoid)__instance).m_utilityItem)))
					{
						((Humanoid)__instance).SetupVisEquipment(((Humanoid)__instance).m_visEquipment, false);
					}
				}
			}

			private static bool DoCheck(Player player, ZDO zdo, string equipKey, string legendaryDataKey, ref ItemData itemData)
			{
				string @string = zdo.GetString(legendaryDataKey, "");
				if (string.IsNullOrEmpty(@string))
				{
					bool flag = itemData != null;
					if (flag)
					{
						ForceResetVisEquipment((Humanoid)(object)player, itemData);
					}
					itemData = null;
					return flag;
				}
				string text = itemData?.GetMagicItem()?.LegendaryID;
				if (text == @string)
				{
					return false;
				}
				int @int = zdo.GetInt(equipKey, 0);
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(@int);
				ItemData val = ((itemPrefab == null) ? null : itemPrefab.GetComponent<ItemDrop>()?.m_itemData);
				if (val != null)
				{
					itemData = val.Clone();
					itemData.m_durability = float.PositiveInfinity;
					MagicItemComponent orCreate = itemData.Data().GetOrCreate<MagicItemComponent>();
					MagicItem magicItem = new MagicItem
					{
						Rarity = ItemRarity.Legendary,
						LegendaryID = @string
					};
					orCreate.SetMagicItem(magicItem);
					ForceResetVisEquipment((Humanoid)(object)player, itemData);
				}
				return false;
			}

			public static void ForceResetVisEquipment(Humanoid humanoid, ItemData item)
			{
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Expected I4, but got Unknown
				//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Invalid comparison between Unknown and I4
				if ((Object)(object)humanoid == (Object)null || (Object)(object)humanoid.m_visEquipment == (Object)null || item == null)
				{
					return;
				}
				ItemType itemType = item.m_shared.m_itemType;
				ItemType val = itemType;
				switch (val - 3)
				{
				case 0:
					if (humanoid.m_rightItem != null && (int)humanoid.m_rightItem.m_shared.m_itemType == 15 && humanoid.m_leftItem == null)
					{
						humanoid.m_visEquipment.m_currentLeftItemHash = -1;
					}
					humanoid.m_visEquipment.m_currentRightItemHash = -1;
					break;
				case 1:
				case 2:
					humanoid.m_visEquipment.m_currentLeftItemHash = -1;
					break;
				case 11:
				case 19:
					humanoid.m_visEquipment.m_currentRightItemHash = -1;
					humanoid.m_visEquipment.m_currentLeftItemHash = -1;
					break;
				case 4:
					humanoid.m_visEquipment.m_currentChestItemHash = -1;
					break;
				case 8:
					humanoid.m_visEquipment.m_currentLegItemHash = -1;
					break;
				case 3:
					humanoid.m_visEquipment.m_currentHelmetItemHash = -1;
					break;
				case 14:
					humanoid.m_visEquipment.m_currentShoulderItemHash = -1;
					break;
				case 15:
					humanoid.m_visEquipment.m_currentUtilityItemHash = -1;
					break;
				case 16:
					humanoid.m_visEquipment.m_currentRightItemHash = -1;
					break;
				case 5:
				case 6:
				case 7:
				case 9:
				case 10:
				case 12:
				case 13:
				case 17:
				case 18:
					break;
				}
			}
		}

		[HarmonyPatch]
		public static class WatchMultiplayerMagicEffects_Player_Patch
		{
			[HarmonyPostfix]
			[HarmonyPatch(typeof(Humanoid), "EquipItem")]
			public static void EquipItem_Postfix(Humanoid __instance)
			{
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val != null)
				{
					UpdateRichesAndLuck(val);
				}
			}

			[HarmonyPostfix]
			[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
			public static void UnequipItem_Postfix(Humanoid __instance)
			{
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val != null)
				{
					UpdateRichesAndLuck(val);
				}
			}

			public static void UpdateRichesAndLuck(Player player)
			{
				if (!((Object)(object)player == (Object)(object)Player.m_localPlayer))
				{
					return;
				}
				ZNetView nview = ((Character)player).m_nview;
				ZDO val = ((nview != null) ? nview.GetZDO() : null);
				if (val != null)
				{
					int @int = val.GetInt("el-luk", 0);
					int int2 = val.GetInt("el-rch", 0);
					int num = (int)player.GetTotalActiveMagicEffectValue(MagicEffectType.Luck);
					int num2 = (int)player.GetTotalActiveMagicEffectValue(MagicEffectType.Riches);
					if (num != @int)
					{
						val.Set("el-luk", num);
					}
					if (num2 != int2)
					{
						val.Set("el-rch", num2);
					}
				}
			}
		}

		public static void UpdatePlayerZDOForEquipment(Player player, ItemData item, bool equip)
		{
			//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_0062: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected I4, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Invalid comparison between Unknown and I4
			object obj;
			if (player == null)
			{
				obj = null;
			}
			else
			{
				ZNetView nview = ((Character)player).m_nview;
				obj = ((nview != null) ? nview.GetZDO() : null);
			}
			ZDO val = (ZDO)obj;
			if (val == null)
			{
				return;
			}
			MagicItem magicItem = item.GetMagicItem();
			string text = ((!equip) ? "" : ((magicItem != null && magicItem.IsUniqueLegendary()) ? magicItem.LegendaryID : ""));
			ItemType itemType = item.m_shared.m_itemType;
			ItemType val2 = itemType;
			ItemType val3 = val2;
			switch (val3 - 3)
			{
			default:
				if ((int)val3 != 22)
				{
					break;
				}
				goto case 0;
			case 0:
			case 1:
			case 2:
			case 11:
			{
				ItemData leftItem = ((Humanoid)player).m_leftItem;
				if (((leftItem != null) ? ((Object)leftItem.m_dropPrefab).name : null) == ((Object)item.m_dropPrefab).name)
				{
					val.Set("lf-ell", text);
				}
				ItemData rightItem = ((Humanoid)player).m_rightItem;
				if (((rightItem != null) ? ((Object)rightItem.m_dropPrefab).name : null) == ((Object)item.m_dropPrefab).name)
				{
					val.Set("ri-ell", text);
				}
				break;
			}
			case 4:
				val.Set("ch-ell", text);
				break;
			case 8:
				val.Set("lg-ell", text);
				break;
			case 3:
				val.Set("hl-ell", text);
				break;
			case 14:
				val.Set("sh-ell", text);
				break;
			case 15:
				val.Set("ut-ell", text);
				break;
			case 5:
			case 6:
			case 7:
			case 9:
			case 10:
			case 12:
			case 13:
				break;
			}
		}
	}
	[HarmonyPatch(typeof(Terminal), "InitTerminal")]
	public static class Terminal_Patch
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__1_0;

			public static ConsoleEvent <>9__1_1;

			public static ConsoleEvent <>9__1_2;

			public static ConsoleEvent <>9__1_3;

			public static ConsoleEvent <>9__1_4;

			public static ConsoleEvent <>9__1_5;

			public static ConsoleEvent <>9__1_6;

			public static ConsoleEvent <>9__1_7;

			public static ConsoleEvent <>9__1_8;

			public static ConsoleEvent <>9__1_9;

			public static ConsoleEvent <>9__1_10;

			public static ConsoleEvent <>9__1_11;

			public static ConsoleEvent <>9__1_12;

			public static ConsoleEvent <>9__1_13;

			public static ConsoleEvent <>9__1_14;

			public static ConsoleEvent <>9__1_15;

			public static ConsoleEvent <>9__1_16;

			public static ConsoleEvent <>9__1_17;

			public static ConsoleEvent <>9__1_18;

			public static ConsoleEvent <>9__1_19;

			public static ConsoleEvent <>9__1_20;

			public static ConsoleEvent <>9__1_21;

			public static ConsoleEvent <>9__1_22;

			public static ConsoleEvent <>9__1_23;

			public static ConsoleEvent <>9__1_24;

			public static ConsoleEvent <>9__1_25;

			public static ConsoleEvent <>9__1_26;

			public static ConsoleEvent <>9__1_27;

			public static ConsoleEvent <>9__1_28;

			public static ConsoleEvent <>9__1_29;

			public static ConsoleEvent <>9__1_30;

			public static Func<TreasureMapChestInfo, int> <>9__3_0;

			public static Func<GameObject, bool> <>9__7_0;

			public static Func<GameObject, bool> <>9__7_1;

			public static Func<GameObject, string> <>9__7_2;

			public static Func<string, float> <>9__7_3;

			internal void <Postfix>b__1_0(ConsoleEventArgs args)
			{
				MagicItem(args.Context, args.Args);
			}

			internal void <Postfix>b__1_1(ConsoleEventArgs args)
			{
				MagicItem(args.Context, args.Args);
			}

			internal void <Postfix>b__1_2(ConsoleEventArgs args)
			{
				SpawnMagicItemWithEffect(args.Context, args.Args);
			}

			internal void <Postfix>b__1_3(ConsoleEventArgs args)
			{
				SpawnMagicItemWithEffect(args.Context, args.Args);
			}

			internal void <Postfix>b__1_4(ConsoleEventArgs args)
			{
				SpawnLegendaryMagicItem(args.Context, args.Args);
			}

			internal void <Postfix>b__1_5(ConsoleEventArgs args)
			{
				SpawnLegendaryMagicItem(args.Context, args.Args);
			}

			internal void <Postfix>b__1_6(ConsoleEventArgs args)
			{
				SpawnMagicItemSet(args.Context, args.Args);
			}

			internal void <Postfix>b__1_7(ConsoleEventArgs args)
			{
				SpawnMagicItemSet(args.Context, args.Args);
			}

			internal void <Postfix>b__1_8(ConsoleEventArgs args)
			{
				CheckStackQuality(args.Context);
			}

			internal void <Postfix>b__1_9(ConsoleEventArgs args)
			{
				SpawnMagicCraftingMaterials();
			}

			internal void <Postfix>b__1_10(ConsoleEventArgs args)
			{
				ToggleAlwaysDrop(args.Context);
			}

			internal void <Postfix>b__1_11(ConsoleEventArgs args)
			{
				LootRoller.CheatDisableGating = !LootRoller.CheatDisableGating;
				args.Context.AddString($"> Disable gating for magic item drops: {LootRoller.CheatDisableGating}");
			}

			internal void <Postfix>b__1_12(ConsoleEventArgs args)
			{
				TestTreasureMap(args.Args);
			}

			internal void <Postfix>b__1_13(ConsoleEventArgs args)
			{
				TestTreasureMap(args.Args);
			}

			internal void <Postfix>b__1_14(ConsoleEventArgs args)
			{
				Player localPlayer = Player.m_localPlayer;
				AdventureSaveData adventureSaveData = localPlayer.GetAdventureSaveData();
				adventureSaveData.TreasureMaps.Clear();
				adventureSaveData.NumberOfTreasureMapsOrBountiesStarted = 0;
				localPlayer.SaveAdventureSaveData();
			}

			internal void <Postfix>b__1_15(ConsoleEventArgs args)
			{
				Player localPlayer = Player.m_localPlayer;
				AdventureSaveData adventureSaveData = localPlayer.GetAdventureSaveData();
				adventureSaveData.TreasureMaps.Clear();
				adventureSaveData.NumberOfTreasureMapsOrBountiesStarted = 0;
				localPlayer.SaveAdventureSaveData();
			}

			internal void <Postfix>b__1_16(ConsoleEventArgs args)
			{
				MinimapController.DebugMode = !MinimapController.DebugMode;
				args.Context.AddString($"> Treasure Map Debug Mode: {MinimapController.DebugMode}");
			}

			internal void <Postfix>b__1_17(ConsoleEventArgs args)
			{
				MinimapController.DebugMode = !MinimapController.DebugMode;
				args.Context.AddString($"> Treasure Map Debug Mode: {MinimapController.DebugMode}");
			}

			internal void <Postfix>b__1_18(ConsoleEventArgs args)
			{
				Player localPlayer = Player.m_localPlayer;
				AdventureSaveData adventureSaveData = localPlayer.GetAdventureSaveData();
				adventureSaveData.Bounties.Clear();
				localPlayer.SaveAdventureSaveData();
			}

			internal void <Postfix>b__1_19(ConsoleEventArgs args)
			{
				Random random = new Random();
				int num = ((args.Length >= 2) ? int.Parse(args[1]) : 10);
				for (int i = 0; i < num; i++)
				{
					string text = BountiesAdventureFeature.GenerateTargetName(random);
					args.Context.AddString(text);
				}
			}

			internal void <Postfix>b__1_20(ConsoleEventArgs args)
			{
				Player localPlayer = Player.m_localPlayer;
				AdventureComponent component = ((Component)localPlayer).GetComponent<AdventureComponent>();
				component.SaveData = new AdventureSaveDataList();
				localPlayer.SaveAdventureSaveData();
			}

			internal void <Postfix>b__1_21(ConsoleEventArgs args)
			{
				int num = ((args.Length >= 2) ? int.Parse(args[1]) : AdventureDataManager.Bounties.GetCurrentInterval());
				List<BountyInfo> availableBounties = AdventureDataManager.Bounties.GetAvailableBounties(num, removeAcceptedBounties: false);
				BountiesAdventureFeature.PrintBounties($"Bounties for Interval {num}:", availableBounties);
			}

			internal void <Postfix>b__1_22(ConsoleEventArgs args)
			{
				Player localPlayer = Player.m_localPlayer;
				List<BountyInfo> bounties = localPlayer.GetAdventureSaveData().Bounties;
				BountiesAdventureFeature.PrintBounties("Player Bounties:", bounties);
			}

			internal void <Postfix>b__1_23(ConsoleEventArgs args)
			{
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				Player localPlayer = Player.m_localPlayer;
				LocationInstance val = default(LocationInstance);
				if (ZoneSystem.instance.FindClosestLocation("Vendor_BlackForest", ((Component)localPlayer).transform.position, ref val))
				{
					((Terminal)Console.instance).AddString(((object)(Vector3)(ref val.m_position)).ToString());
				}
			}

			internal void <Postfix>b__1_24(ConsoleEventArgs args)
			{
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				Player localPlayer = Player.m_localPlayer;
				LocationInstance val = default(LocationInstance);
				if (ZoneSystem.instance.FindClosestLocation("Vendor_BlackForest", ((Component)localPlayer).transform.position, ref val))
				{
					((Terminal)Console.instance).AddString(((object)(Vector3)(ref val.m_position)).ToString());
				}
			}

			internal void <Postfix>b__1_25(ConsoleEventArgs args)
			{
				if (!((Object)(object)ZoneSystem.instance != (Object)null))
				{
					return;
				}
				args.Context.AddString("> Print Global Keys:");
				foreach (string globalKey in ZoneSystem.instance.GetGlobalKeys())
				{
					args.Context.AddString("> " + globalKey);
				}
			}

			internal void <Postfix>b__1_26(ConsoleEventArgs args)
			{
				Player localPlayer = Player.m_localPlayer;
				FixResistances(localPlayer);
			}

			internal void <Postfix>b__1_27(ConsoleEventArgs args)
			{
				string lootTableName = ((args.Length > 1) ? args[1] : "Greydwarf");
				float luckFactor = ((args.Length > 2) ? float.Parse(args[2]) : 0f);
				LootRoller.PrintLuckTest(lootTableName, luckFactor);
			}

			internal void <Postfix>b__1_28(ConsoleEventArgs args)
			{
				string lootTableName = ((args.Length > 1) ? args[1] : "Greydwarf");
				int level = ((args.Length <= 2) ? 1 : int.Parse(args[2]));
				int itemIndex = ((args.Length > 3) ? int.Parse(args[3]) : 0);
				LootRoller.PrintLootResolutionTest(lootTableName, level, itemIndex);
			}

			internal void <Postfix>b__1_29(ConsoleEventArgs args)
			{
				Player localPlayer = Player.m_localPlayer;
				if (!((Object)(object)localPlayer != (Object)null))
				{
					return;
				}
				AbilityController component = ((Component)localPlayer).GetComponent<AbilityController>();
				if (!((Object)(object)component != (Object)null))
				{
					return;
				}
				foreach (Ability currentAbility in component.CurrentAbilities)
				{
					currentAbility.ResetCooldown();
				}
			}

			internal void <Postfix>b__1_30(ConsoleEventArgs args)
			{
				LootRoller.DebugLuckFactor();
			}

			internal int <TestTreasureMapCoroutine>b__3_0(TreasureMapChestInfo x)
			{
				return x.Interval;
			}

			internal bool <MagicItem>b__7_0(GameObject x)
			{
				return EpicLoot.CanBeMagicItem(x.GetComponent<ItemDrop>().m_itemData);
			}

			internal bool <MagicItem>b__7_1(GameObject x)
			{
				return ((Object)x).name != "HelmetDverger" && ((Object)x).name != "BeltStrength" && ((Object)x).name != "Wishbone";
			}

			internal string <MagicItem>b__7_2(GameObject x)
			{
				return ((Object)x).name;
			}

			internal float <MagicItem>b__7_3(string x)
			{
				return 1f;
			}
		}

		private static readonly Random _random = new Random();

		public static void Postfix()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Expected O, but got Unknown
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Expected O, but got Unknown
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Expected O, but got Unknown
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Expected O, but got Unknown
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Expected O, but got Unknown
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Expected O, but got Unknown
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Expected O, but got Unknown
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Expected O, but got Unknown
			//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Expected O, but got Unknown
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_0313: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_031e: Expected O, but got Unknown
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0349: Unknown result type (might be due to invalid IL or missing references)
			//IL_034e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Expected O, but got Unknown
			//IL_0391: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Expected O, but got Unknown
			//IL_03c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Expected O, but got Unknown
			//IL_03fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f6: Expected O, but got Unknown
			//IL_0433: Unknown result type (might be due to invalid IL or missing references)
			//IL_0421: Unknown result type (might be due to invalid IL or missing references)
			//IL_0426: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Expected O, but got Unknown
			//IL_0469: Unknown result type (might be due to invalid IL or missing references)
			//IL_0457: Unknown result type (might be due to invalid IL or missing references)
			//IL_045c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0462: Expected O, but got Unknown
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			//IL_048d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0492: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Expected O, but got Unknown
			//IL_04d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ce: Expected O, but got Unknown
			//IL_050b: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Expected O, but got Unknown
			//IL_0541: Unknown result type (might be due to invalid IL or missing references)
			//IL_052f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0534: Unknown result type (might be due to invalid IL or missing references)
			//IL_053a: Expected O, but got Unknown
			//IL_0577: Unknown result type (might be due to invalid IL or missing references)
			//IL_0565: Unknown result type (might be due to invalid IL or missing references)
			//IL_056a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0570: Expected O, but got Unknown
			//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_059b: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a6: Expected O, but got Unknown
			//IL_05e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_05dc: Expected O, but got Unknown
			//IL_0619: Unknown result type (might be due to invalid IL or missing references)
			//IL_0607: Unknown result type (might be due to invalid IL or missing references)
			//IL_060c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0612: Expected O, but got Unknown
			//IL_064f: Unknown result type (might be due to invalid IL or missing references)
			//IL_063d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0642: Unknown result type (might be due to invalid IL or missing references)
			//IL_0648: Expected O, but got Unknown
			//IL_0685: Unknown result type (might be due to invalid IL or missing references)
			//IL_0673: Unknown result type (might be due to invalid IL or missing references)
			//IL_0678: Unknown result type (might be due to invalid IL or missing references)
			//IL_067e: Expected O, but got Unknown
			object obj = <>c.<>9__1_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					MagicItem(args.Context, args.Args);
				};
				<>c.<>9__1_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("magicitem", "", (ConsoleEvent)obj, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj2 = <>c.<>9__1_1;
			if (obj2 == null)
			{
				ConsoleEvent val2 = delegate(ConsoleEventArgs args)
				{
					MagicItem(args.Context, args.Args);
				};
				<>c.<>9__1_1 = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("mi", "", (ConsoleEvent)obj2, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj3 = <>c.<>9__1_2;
			if (obj3 == null)
			{
				ConsoleEvent val3 = delegate(ConsoleEventArgs args)
				{
					SpawnMagicItemWithEffect(args.Context, args.Args);
				};
				<>c.<>9__1_2 = val3;
				obj3 = (object)val3;
			}
			new ConsoleCommand("magicitemwitheffect", "", (ConsoleEvent)obj3, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj4 = <>c.<>9__1_3;
			if (obj4 == null)
			{
				ConsoleEvent val4 = delegate(ConsoleEventArgs args)
				{
					SpawnMagicItemWithEffect(args.Context, args.Args);
				};
				<>c.<>9__1_3 = val4;
				obj4 = (object)val4;
			}
			new ConsoleCommand("mieffect", "", (ConsoleEvent)obj4, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj5 = <>c.<>9__1_4;
			if (obj5 == null)
			{
				ConsoleEvent val5 = delegate(ConsoleEventArgs args)
				{
					SpawnLegendaryMagicItem(args.Context, args.Args);
				};
				<>c.<>9__1_4 = val5;
				obj5 = (object)val5;
			}
			new ConsoleCommand("magicitemlegendary", "", (ConsoleEvent)obj5, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj6 = <>c.<>9__1_5;
			if (obj6 == null)
			{
				ConsoleEvent val6 = delegate(ConsoleEventArgs args)
				{
					SpawnLegendaryMagicItem(args.Context, args.Args);
				};
				<>c.<>9__1_5 = val6;
				obj6 = (object)val6;
			}
			new ConsoleCommand("milegend", "", (ConsoleEvent)obj6, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj7 = <>c.<>9__1_6;
			if (obj7 == null)
			{
				ConsoleEvent val7 = delegate(ConsoleEventArgs args)
				{
					SpawnMagicItemSet(args.Context, args.Args);
				};
				<>c.<>9__1_6 = val7;
				obj7 = (object)val7;
			}
			new ConsoleCommand("magicitemset", "", (ConsoleEvent)obj7, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj8 = <>c.<>9__1_7;
			if (obj8 == null)
			{
				ConsoleEvent val8 = delegate(ConsoleEventArgs args)
				{
					SpawnMagicItemSet(args.Context, args.Args);
				};
				<>c.<>9__1_7 = val8;
				obj8 = (object)val8;
			}
			new ConsoleCommand("miset", "", (ConsoleEvent)obj8, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj9 = <>c.<>9__1_8;
			if (obj9 == null)
			{
				ConsoleEvent val9 = delegate(ConsoleEventArgs args)
				{
					CheckStackQuality(args.Context);
				};
				<>c.<>9__1_8 = val9;
				obj9 = (object)val9;
			}
			new ConsoleCommand("checkstackquality", "", (ConsoleEvent)obj9, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj10 = <>c.<>9__1_9;
			if (obj10 == null)
			{
				ConsoleEvent val10 = delegate
				{
					SpawnMagicCraftingMaterials();
				};
				<>c.<>9__1_9 = val10;
				obj10 = (object)val10;
			}
			new ConsoleCommand("magicmats", "", (ConsoleEvent)obj10, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj11 = <>c.<>9__1_10;
			if (obj11 == null)
			{
				ConsoleEvent val11 = delegate(ConsoleEventArgs args)
				{
					ToggleAlwaysDrop(args.Context);
				};
				<>c.<>9__1_10 = val11;
				obj11 = (object)val11;
			}
			new ConsoleCommand("alwaysdrop", "", (ConsoleEvent)obj11, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj12 = <>c.<>9__1_11;
			if (obj12 == null)
			{
				ConsoleEvent val12 = delegate(ConsoleEventArgs args)
				{
					LootRoller.CheatDisableGating = !LootRoller.CheatDisableGating;
					args.Context.AddString($"> Disable gating for magic item drops: {LootRoller.CheatDisableGating}");
				};
				<>c.<>9__1_11 = val12;
				obj12 = (object)val12;
			}
			new ConsoleCommand("cheatgating", "", (ConsoleEvent)obj12, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj13 = <>c.<>9__1_12;
			if (obj13 == null)
			{
				ConsoleEvent val13 = delegate(ConsoleEventArgs args)
				{
					TestTreasureMap(args.Args);
				};
				<>c.<>9__1_12 = val13;
				obj13 = (object)val13;
			}
			new ConsoleCommand("testtreasuremap", "", (ConsoleEvent)obj13, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj14 = <>c.<>9__1_13;
			if (obj14 == null)
			{
				ConsoleEvent val14 = delegate(ConsoleEventArgs args)
				{
					TestTreasureMap(args.Args);
				};
				<>c.<>9__1_13 = val14;
				obj14 = (object)val14;
			}
			new ConsoleCommand("testtm", "", (ConsoleEvent)obj14, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj15 = <>c.<>9__1_14;
			if (obj15 == null)
			{
				ConsoleEvent val15 = delegate
				{
					Player localPlayer9 = Player.m_localPlayer;
					AdventureSaveData adventureSaveData3 = localPlayer9.GetAdventureSaveData();
					adventureSaveData3.TreasureMaps.Clear();
					adventureSaveData3.NumberOfTreasureMapsOrBountiesStarted = 0;
					localPlayer9.SaveAdventureSaveData();
				};
				<>c.<>9__1_14 = val15;
				obj15 = (object)val15;
			}
			new ConsoleCommand("resettreasuremap", "", (ConsoleEvent)obj15, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj16 = <>c.<>9__1_15;
			if (obj16 == null)
			{
				ConsoleEvent val16 = delegate
				{
					Player localPlayer8 = Player.m_localPlayer;
					AdventureSaveData adventureSaveData2 = localPlayer8.GetAdventureSaveData();
					adventureSaveData2.TreasureMaps.Clear();
					adventureSaveData2.NumberOfTreasureMapsOrBountiesStarted = 0;
					localPlayer8.SaveAdventureSaveData();
				};
				<>c.<>9__1_15 = val16;
				obj16 = (object)val16;
			}
			new ConsoleCommand("resettm", "", (ConsoleEvent)obj16, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj17 = <>c.<>9__1_16;
			if (obj17 == null)
			{
				ConsoleEvent val17 = delegate(ConsoleEventArgs args)
				{
					MinimapController.DebugMode = !MinimapController.DebugMode;
					args.Context.AddString($"> Treasure Map Debug Mode: {MinimapController.DebugMode}");
				};
				<>c.<>9__1_16 = val17;
				obj17 = (object)val17;
			}
			new ConsoleCommand("debugtreasuremap", "", (ConsoleEvent)obj17, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj18 = <>c.<>9__1_17;
			if (obj18 == null)
			{
				ConsoleEvent val18 = delegate(ConsoleEventArgs args)
				{
					MinimapController.DebugMode = !MinimapController.DebugMode;
					args.Context.AddString($"> Treasure Map Debug Mode: {MinimapController.DebugMode}");
				};
				<>c.<>9__1_17 = val18;
				obj18 = (object)val18;
			}
			new ConsoleCommand("debugtm", "", (ConsoleEvent)obj18, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj19 = <>c.<>9__1_18;
			if (obj19 == null)
			{
				ConsoleEvent val19 = delegate
				{
					Player localPlayer7 = Player.m_localPlayer;
					AdventureSaveData adventureSaveData = localPlayer7.GetAdventureSaveData();
					adventureSaveData.Bounties.Clear();
					localPlayer7.SaveAdventureSaveData();
				};
				<>c.<>9__1_18 = val19;
				obj19 = (object)val19;
			}
			new ConsoleCommand("resetbounties", "", (ConsoleEvent)obj19, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj20 = <>c.<>9__1_19;
			if (obj20 == null)
			{
				ConsoleEvent val20 = delegate(ConsoleEventArgs args)
				{
					Random random = new Random();
					int num2 = ((args.Length >= 2) ? int.Parse(args[1]) : 10);
					for (int i = 0; i < num2; i++)
					{
						string text = BountiesAdventureFeature.GenerateTargetName(random);
						args.Context.AddString(text);
					}
				};
				<>c.<>9__1_19 = val20;
				obj20 = (object)val20;
			}
			new ConsoleCommand("testbountynames", "", (ConsoleEvent)obj20, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj21 = <>c.<>9__1_20;
			if (obj21 == null)
			{
				ConsoleEvent val21 = delegate
				{
					Player localPlayer6 = Player.m_localPlayer;
					AdventureComponent component2 = ((Component)localPlayer6).GetComponent<AdventureComponent>();
					component2.SaveData = new AdventureSaveDataList();
					localPlayer6.SaveAdventureSaveData();
				};
				<>c.<>9__1_20 = val21;
				obj21 = (object)val21;
			}
			new ConsoleCommand("resetadventure", "", (ConsoleEvent)obj21, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj22 = <>c.<>9__1_21;
			if (obj22 == null)
			{
				ConsoleEvent val22 = delegate(ConsoleEventArgs args)
				{
					int num = ((args.Length >= 2) ? int.Parse(args[1]) : AdventureDataManager.Bounties.GetCurrentInterval());
					List<BountyInfo> availableBounties = AdventureDataManager.Bounties.GetAvailableBounties(num, removeAcceptedBounties: false);
					BountiesAdventureFeature.PrintBounties($"Bounties for Interval {num}:", availableBounties);
				};
				<>c.<>9__1_21 = val22;
				obj22 = (object)val22;
			}
			new ConsoleCommand("bounties", "", (ConsoleEvent)obj22, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj23 = <>c.<>9__1_22;
			if (obj23 == null)
			{
				ConsoleEvent val23 = delegate
				{
					Player localPlayer5 = Player.m_localPlayer;
					List<BountyInfo> bounties = localPlayer5.GetAdventureSaveData().Bounties;
					BountiesAdventureFeature.PrintBounties("Player Bounties:", bounties);
				};
				<>c.<>9__1_22 = val23;
				obj23 = (object)val23;
			}
			new ConsoleCommand("playerbounties", "", (ConsoleEvent)obj23, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj24 = <>c.<>9__1_23;
			if (obj24 == null)
			{
				ConsoleEvent val24 = delegate
				{
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					Player localPlayer4 = Player.m_localPlayer;
					LocationInstance val33 = default(LocationInstance);
					if (ZoneSystem.instance.FindClosestLocation("Vendor_BlackForest", ((Component)localPlayer4).transform.position, ref val33))
					{
						((Terminal)Console.instance).AddString(((object)(Vector3)(ref val33.m_position)).ToString());
					}
				};
				<>c.<>9__1_23 = val24;
				obj24 = (object)val24;
			}
			new ConsoleCommand("gotomerchant", "", (ConsoleEvent)obj24, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj25 = <>c.<>9__1_24;
			if (obj25 == null)
			{
				ConsoleEvent val25 = delegate
				{
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					Player localPlayer3 = Player.m_localPlayer;
					LocationInstance val32 = default(LocationInstance);
					if (ZoneSystem.instance.FindClosestLocation("Vendor_BlackForest", ((Component)localPlayer3).transform.position, ref val32))
					{
						((Terminal)Console.instance).AddString(((object)(Vector3)(ref val32.m_position)).ToString());
					}
				};
				<>c.<>9__1_24 = val25;
				obj25 = (object)val25;
			}
			new ConsoleCommand("gotom", "", (ConsoleEvent)obj25, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj26 = <>c.<>9__1_25;
			if (obj26 == null)
			{
				ConsoleEvent val26 = delegate(ConsoleEventArgs args)
				{
					if ((Object)(object)ZoneSystem.instance != (Object)null)
					{
						args.Context.AddString("> Print Global Keys:");
						foreach (string globalKey in ZoneSystem.instance.GetGlobalKeys())
						{
							args.Context.AddString("> " + globalKey);
						}
					}
				};
				<>c.<>9__1_25 = val26;
				obj26 = (object)val26;
			}
			new ConsoleCommand("globalkeys", "", (ConsoleEvent)obj26, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj27 = <>c.<>9__1_26;
			if (obj27 == null)
			{
				ConsoleEvent val27 = delegate
				{
					Player localPlayer2 = Player.m_localPlayer;
					FixResistances(localPlayer2);
				};
				<>c.<>9__1_26 = val27;
				obj27 = (object)val27;
			}
			new ConsoleCommand("fixresistances", "", (ConsoleEvent)obj27, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj28 = <>c.<>9__1_27;
			if (obj28 == null)
			{
				ConsoleEvent val28 = delegate(ConsoleEventArgs args)
				{
					string lootTableName2 = ((args.Length > 1) ? args[1] : "Greydwarf");
					float luckFactor = ((args.Length > 2) ? float.Parse(args[2]) : 0f);
					LootRoller.PrintLuckTest(lootTableName2, luckFactor);
				};
				<>c.<>9__1_27 = val28;
				obj28 = (object)val28;
			}
			new ConsoleCommand("lucktest", "", (ConsoleEvent)obj28, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj29 = <>c.<>9__1_28;
			if (obj29 == null)
			{
				ConsoleEvent val29 = delegate(ConsoleEventArgs args)
				{
					string lootTableName = ((args.Length > 1) ? args[1] : "Greydwarf");
					int level = ((args.Length <= 2) ? 1 : int.Parse(args[2]));
					int itemIndex = ((args.Length > 3) ? int.Parse(args[3]) : 0);
					LootRoller.PrintLootResolutionTest(lootTableName, level, itemIndex);
				};
				<>c.<>9__1_28 = val29;
				obj29 = (object)val29;
			}
			new ConsoleCommand("lootres", "", (ConsoleEvent)obj29, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj30 = <>c.<>9__1_29;
			if (obj30 == null)
			{
				ConsoleEvent val30 = delegate
				{
					Player localPlayer = Player.m_localPlayer;
					if ((Object)(object)localPlayer != (Object)null)
					{
						AbilityController component = ((Component)localPlayer).GetComponent<AbilityController>();
						if ((Object)(object)component != (Object)null)
						{
							foreach (Ability currentAbility in component.CurrentAbilities)
							{
								currentAbility.ResetCooldown();
							}
						}
					}
				};
				<>c.<>9__1_29 = val30;
				obj30 = (object)val30;
			}
			new ConsoleCommand("resetcooldowns", "", (ConsoleEvent)obj30, true, false, false, false, false, (ConsoleOptionsFetcher)null, false);
			object obj31 = <>c.<>9__1_30;
			if (obj31 == null)
			{
				ConsoleEvent val31 = delegate
				{
					LootRoller.DebugLuckFactor();
				};
				<>c.<>9__1_30 = val31;
				obj31 = (object)val31;
			}
			new ConsoleCommand("debugluck", "", (ConsoleEvent)obj31, false, false, false, false, false, (ConsoleOptionsFetcher)null, false);
		}

		private static void TestTreasureMap(string[] args)
		{
			//IL_0026: 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)
			Player localPlayer = Player.m_localPlayer;
			int result = 1;
			if (args.Length >= 2)
			{
				int.TryParse(args[1], out result);
			}
			Biome result2 = (Biome)0;
			if (args.Length >= 3)
			{
				Enum.TryParse<Biome>(args[2], out result2);
			}
			int result3 = -1;
			if (args.Length >= 4)
			{
				int.TryParse(args[3], out result3);
			}
			AdventureDataManager.CheatNumberOfBounties = result3;
			AdventureSaveData adventureSaveData = localPlayer.GetAdventureSaveData();
			((MonoBehaviour)localPlayer).StartCoroutine(TestTreasureMapCoroutine(adventureSaveData, result2, localPlayer, result));
		}

		private static IEnumerator TestTreasureMapCoroutine(AdventureSaveData saveData, Biome biome, Player player, int count)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Biome[] array = new Biome[5];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			Biome[] biomes = (Biome[])(object)array;
			saveData.DebugMode = true;
			int startInterval = ((saveData.TreasureMaps.Count == 0) ? (-1) : (saveData.TreasureMaps.Min((TreasureMapChestInfo x) => x.Interval) - 1));
			int i = 0;
			while (i < count)
			{
				saveData.IntervalOverride = startInterval - (i + 1);
				Biome selectedBiome = (Biome)(((int)biome == 0) ? ((int)biomes[Random.Range(0, biomes.Length)]) : ((int)biome));
				yield return AdventureDataManager.TreasureMaps.SpawnTreasureChest(selectedBiome, player, OnTreasureChestSpawnComplete);
				int num = i + 1;
				i = num;
			}
			saveData.DebugMode = false;
			AdventureDataManager.CheatNumberOfBounties = -1;
		}

		private static void OnTreasureChestSpawnComplete(bool success, Vector3 spawnPoint)
		{
			//IL_0012: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			string text = "> Failed to spawn treasure map chest";
			if (success)
			{
				text = $"> Spawning Treasure Map Chest at <{spawnPoint.x:0.#}, {spawnPoint.z:0.#}> (height:{spawnPoint.y:0.#})";
			}
			((Terminal)Console.instance).AddString(text);
			EpicLoot.LogWarning(text);
		}

		private static void ToggleAlwaysDrop(Terminal context)
		{
			EpicLoot.AlwaysDropCheat = !EpicLoot.AlwaysDropCheat;
			context.AddString($"> Always Drop: {EpicLoot.AlwaysDropCheat}");
		}

		private static void SpawnMagicCraftingMaterials()
		{
			//IL_0026: 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_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			foreach (GameObject registeredItemPrefab in EpicLoot.RegisteredItemPrefabs)
			{
				ItemDrop component = Object.Instantiate<GameObject>(registeredItemPrefab, ((Component)Player.m_localPlayer).transform.position + ((Component)Player.m_localPlayer).transform.forward * 2f + Vector3.up, Quaternion.identity).GetComponent<ItemDrop>();
				if (component.m_itemData.IsMagicCraftingMaterial() || (component.m_itemData.IsRunestone() && component.m_itemData.GetCraftingMaterialRarity() != ItemRarity.Mythic))
				{
					component.m_itemData.m_stack = component.m_itemData.m_shared.m_maxStackSize / 2;
				}
				else
				{
					ZNetScene.instance.Destroy(((Component)component).gameObject);
				}
			}
		}

		public static void MagicItem(Terminal context, string[] args)
		{
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			string text = ((args.Length >= 2) ? args[1] : "random");
			string text2 = ((args.Length >= 3) ? args[2] : "random");
			int num = ((args.Length < 4) ? 1 : int.Parse(args[3]));
			int cheatEffectCount = ((args.Length >= 5) ? int.Parse(args[4]) : (-1));
			context.AddString($"magicitem - rarity:{text}, item:{text2}, count:{num}");
			List<string> collection = (from x in ObjectDB.instance.m_items
				where EpicLoot.CanBeMagicItem(x.GetComponent<ItemDrop>().m_itemData)
				where ((Object)x).name != "HelmetDverger" && ((Object)x).name != "BeltStrength" && ((Object)x).name != "Wishbone"
				select ((Object)x).name).ToList();
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				return;
			}
			LootRoller.CheatEffectCount = cheatEffectCount;
			for (int i = 0; i < num; i++)
			{
				float[] rarityTable = GetRarityTable(text);
				string text3 = text2;
				if (text3 == "random")
				{
					WeightedRandomCollection<string> weightedRandomCollection = new WeightedRandomCollection<string>(_random, collection, (string x) => 1f);
					text3 = weightedRandomCollection.Roll();
				}
				if ((Object)(object)ObjectDB.instance.GetItemPrefab(text3) == (Object)null)
				{
					context.AddString("> Could not find item: " + text3);
					break;
				}
				context.AddString(string.Format(">  {0} - rarity: [{1}], item: {2}", i + 1, string.Join(", ", rarityTable), text3));
				LootTable lootTable = new LootTable();
				lootTable.Object = "Console";
				lootTable.Drops = new float[1][] { new float[2] { 1f, 1f } };
				lootTable.Loot = new LootDrop[1]
				{
					new LootDrop
					{
						Item = text3,
						Rarity = rarityTable,
						Weight = 1f
					}
				};
				LootTable lootTable2 = lootTable;
				Vector3 insideUnitSphere = Random.insideUnitSphere;
				Vector3 dropPoint = ((Component)Player.m_localPlayer).transform.position + ((Component)Player.m_localPlayer).transform.forward * 3f + Vector3.up * 1.5f + insideUnitSphere;
				LootRoller.CheatRollingItem = true;
				LootRoller.RollLootTableAndSpawnObjects(lootTable2, 1, lootTable2.Object, dropPoint);
				LootRoller.CheatRollingItem = false;
			}
			LootRoller.CheatEffectCount = -1;
		}

		public static void SpawnMagicItemWithEffect(Terminal context, string[] args)
		{
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			if (args.Length < 3)
			{
				EpicLoot.LogError("Specify effect and item name");
			}
			else
			{
				if ((Object)(object)Player.m_localPlayer == (Object)null)
				{
					return;
				}
				string text = args[1];
				string text2 = args[2];
				context.AddString("magicitem - " + text2 + " with effect: " + text);
				MagicItemEffectDefinition magicItemEffectDefinition = MagicItemEffectDefinitions.Get(text);
				if (magicItemEffectDefinition == null)
				{
					context.AddString("> Could not find effect: " + text);
					return;
				}
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text2);
				if ((Object)(object)itemPrefab == (Object)null)
				{
					context.AddString("> Could not find item: " + text2);
					return;
				}
				ItemData itemData = itemPrefab.GetComponent<ItemDrop>().m_itemData;
				if (!EpicLoot.CanBeMagicItem(itemData))
				{
					context.AddString("> Can't be magic item: " + text2);
					return;
				}
				MagicItemEffectRequirements requirements = magicItemEffectDefinition.Requirements;
				float[] rarityTable = GetRarityTable(((requirements.AllowedRarities.Count != 0) ? requirements.AllowedRarities.First() : ItemRarity.Magic).ToString());
				LootTable lootTable = new LootTable();
				lootTable.Object = "Console";
				lootTable.Drops = new float[1][] { new float[2] { 1f, 1f 

BepInEx/plugins/rin_jugatla-Add_All_Fuel_And_Ore_For_Smelter_Charcoalkiln_etc/AddAllFuel.dll

Decompiled 8 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AddAllFuel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AddAllFuel")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("52be6d2b-daf1-446a-88a5-1c2e02280b51")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace AddAllFuel;

[BepInPlugin("rin_jugatla.AddAllFuel", "AddAllFuel", "1.6.1")]
public class BepInExPlugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Container), "Awake")]
	public static class ModifyContainerAwake
	{
		private static void Postfix(Container __instance)
		{
			if ((((Object)__instance).name.StartsWith("piece_chest") || ((Object)__instance).name.StartsWith("Container")) && __instance.GetInventory() != null)
			{
				Containers.Add(__instance);
			}
		}
	}

	[HarmonyPatch(typeof(Container), "OnDestroyed")]
	public static class ModifyContainerOnDestroyed
	{
		private static void Prefix(Container __instance)
		{
			Containers.Remove(__instance);
		}
	}

	[HarmonyPatch(typeof(Smelter), "OnAddOre")]
	[HarmonyPriority(600)]
	private static class ModifySmelterOnAddOre
	{
		private static bool Prefix(Smelter __instance, ref Humanoid user, ZNetView ___m_nview, ref bool __result)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			__result = false;
			int value = Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>();
			if (value >= __instance.m_maxOre)
			{
				((Character)user).Message((MessageType)2, "$msg_itsfull", 0, (Sprite)null);
				return false;
			}
			bool flag = (Input.GetKey(ModifierKey.Value) && IsReverseModifierMode.Value) || (!Input.GetKey(ModifierKey.Value) && !IsReverseModifierMode.Value);
			ItemData val = FindCookableItem(__instance, user.GetInventory(), flag);
			Container val2 = null;
			if (val == null)
			{
				if (IsUseFromContainer.Value)
				{
					foreach (Container item in Utility.GetNearByContainer(((Component)user).transform.position) ?? new List<Container>())
					{
						val2 = item;
						val = FindCookableItem(__instance, item.GetInventory(), flag);
						if (val != null)
						{
							break;
						}
					}
				}
				if (val == null)
				{
					if (flag)
					{
						return true;
					}
					((Character)user).Message((MessageType)2, "$msg_noprocessableitems", 0, (Sprite)null);
					return false;
				}
			}
			if (!Traverse.Create((object)__instance).Method("IsItemAllowed", new object[1] { ((Object)val.m_dropPrefab).name }).GetValue<bool>())
			{
				((Character)user).Message((MessageType)2, "$msg_wontwork", 0, (Sprite)null);
				return false;
			}
			((Character)user).Message((MessageType)2, "$msg_added " + val.m_shared.m_name, 0, (Sprite)null);
			int val3 = __instance.m_maxOre - value;
			int num = 1;
			if (!flag)
			{
				num = Math.Min(val.m_stack, val3);
			}
			if (IsDebug)
			{
				Debug.Log((object)$"{val.m_shared.m_name}({val.m_stack})");
				Debug.Log((object)$"{value} / {__instance.m_maxOre}");
				Debug.Log((object)$"{num}");
			}
			if ((Object)(object)val2 == (Object)null)
			{
				user.GetInventory().RemoveItem(val, num);
			}
			else
			{
				val2.GetInventory().RemoveItem(val, num);
				typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(val2, new object[0]);
			}
			for (int i = 0; i < num; i++)
			{
				___m_nview.InvokeRPC("AddOre", new object[1] { ((Object)val.m_dropPrefab).name });
			}
			__result = true;
			return false;
		}

		private static ItemData FindCookableItem(Smelter __instance, Inventory inventory, bool isAddOne)
		{
			IEnumerable<string> enumerable = null;
			enumerable = ((!(IsAllowAddOneExcludeItem.Value && isAddOne)) ? (from n in __instance.m_conversion
				where !ExcludeNames.Contains(n.m_from.m_itemData.m_shared.m_name)
				select n.m_from.m_itemData.m_shared.m_name) : __instance.m_conversion.Select((ItemConversion n) => n.m_from.m_itemData.m_shared.m_name));
			if (enumerable == null)
			{
				return null;
			}
			foreach (string item in enumerable)
			{
				ItemData val = ((inventory != null) ? inventory.GetItem(item) : null);
				if (val != null)
				{
					return val;
				}
			}
			return null;
		}

		private static void RPC_AddOre(Smelter instance, ZNetView m_nview, string name, int count)
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			if (m_nview.IsOwner() && Traverse.Create((object)instance).Method("IsItemAllowed", new object[1] { name }).GetValue<bool>())
			{
				int value = Traverse.Create((object)instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>();
				for (int i = 0; i < count; i++)
				{
					m_nview.GetZDO().Set($"item{value + i}", name);
				}
				m_nview.GetZDO().Set("queued", value + count);
				instance.m_oreAddedEffects.Create(((Component)instance).transform.position, ((Component)instance).transform.rotation, (Transform)null, 1f);
				ZLog.Log((object)$"Added ore {name} * {count}");
			}
		}
	}

	[HarmonyPatch(typeof(Smelter), "OnAddFuel")]
	[HarmonyPriority(600)]
	private static class ModifySmelterOnAddFuel
	{
		private static bool Prefix(Smelter __instance, Humanoid user, ItemData item, ZNetView ___m_nview, ref bool __result)
		{
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			__result = false;
			string fuelName = __instance.m_fuelItem.m_itemData.m_shared.m_name;
			if (item != null && item.m_shared.m_name != fuelName)
			{
				((Character)user).Message((MessageType)2, "$msg_wrongitem", 0, (Sprite)null);
				return false;
			}
			float value = Traverse.Create((object)__instance).Method("GetFuel", Array.Empty<object>()).GetValue<float>();
			if (value > (float)(__instance.m_maxFuel - 1))
			{
				((Character)user).Message((MessageType)2, "$msg_itsfull", 0, (Sprite)null);
				return false;
			}
			bool flag = (Input.GetKey(ModifierKey.Value) && IsReverseModifierMode.Value) || (!Input.GetKey(ModifierKey.Value) && !IsReverseModifierMode.Value);
			item = user.GetInventory().GetItem(fuelName);
			Container val = null;
			if (item == null)
			{
				if (IsUseFromContainer.Value)
				{
					val = Utility.GetNearByContainer(((Component)user).transform.position)?.Where(delegate(Container n)
					{
						Inventory inventory = n.GetInventory();
						return ((inventory != null) ? inventory.GetItem(fuelName) : null) != null;
					}).FirstOrDefault();
					item = ((val != null) ? val.GetInventory().GetItem(fuelName) : null);
				}
				if (item == null)
				{
					if (flag)
					{
						return true;
					}
					((Character)user).Message((MessageType)2, "$msg_donthaveany " + fuelName, 0, (Sprite)null);
					return false;
				}
			}
			((Character)user).Message((MessageType)2, "$msg_added " + fuelName, 0, (Sprite)null);
			int val2 = (int)((float)__instance.m_maxFuel - value);
			int num = 1;
			if (!flag)
			{
				num = Math.Min(item.m_stack, val2);
			}
			if (IsDebug)
			{
				Debug.Log((object)$"{item.m_shared.m_name}({item.m_stack})");
				Debug.Log((object)$"{value} / {__instance.m_maxFuel}");
				Debug.Log((object)$"{num}");
			}
			if ((Object)(object)val == (Object)null)
			{
				user.GetInventory().RemoveItem(item, num);
			}
			else
			{
				val.GetInventory().RemoveItem(item, num);
				typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(val, new object[0]);
			}
			for (int i = 0; i < num; i++)
			{
				___m_nview.InvokeRPC("AddFuel", Array.Empty<object>());
			}
			__result = true;
			return false;
		}

		private static void RPC_AddFuel(Smelter instance, ZNetView m_nview, float count)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			if (m_nview.IsOwner())
			{
				float value = Traverse.Create((object)instance).Method("GetFuel", Array.Empty<object>()).GetValue<float>();
				m_nview.GetZDO().Set("fuel", value + count);
				instance.m_fuelAddedEffects.Create(((Component)instance).transform.position, ((Component)instance).transform.rotation, ((Component)instance).transform, 1f);
				ZLog.Log((object)$"Added fuel * {count}");
			}
		}
	}

	[HarmonyPatch(typeof(Fireplace), "Interact")]
	[HarmonyPriority(600)]
	private static class ModifyFireplaceInteract
	{
		private static bool Prefix(Fireplace __instance, Humanoid user, bool hold, ZNetView ___m_nview, ref bool __result)
		{
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			__result = false;
			if (hold)
			{
				return false;
			}
			if (!___m_nview.HasOwner())
			{
				___m_nview.ClaimOwnership();
			}
			string fuelName = __instance.m_fuelItem.m_itemData.m_shared.m_name;
			float num = Mathf.CeilToInt(___m_nview.GetZDO().GetFloat("fuel", 0f));
			if (num > __instance.m_maxFuel - 1f)
			{
				((Character)user).Message((MessageType)2, Localization.instance.Localize("$msg_cantaddmore", new string[1] { fuelName }), 0, (Sprite)null);
				return false;
			}
			bool flag = (Input.GetKey(ModifierKey.Value) && IsReverseModifierMode.Value) || (!Input.GetKey(ModifierKey.Value) && !IsReverseModifierMode.Value);
			Inventory inventory = user.GetInventory();
			ItemData val = ((inventory != null) ? inventory.GetItem(fuelName) : null);
			Container val2 = null;
			if (val == null)
			{
				if (IsUseFromContainer.Value)
				{
					val2 = Utility.GetNearByContainer(((Component)user).transform.position)?.Where(delegate(Container n)
					{
						Inventory inventory2 = n.GetInventory();
						return ((inventory2 != null) ? inventory2.GetItem(fuelName) : null) != null;
					})?.FirstOrDefault();
					val = ((val2 != null) ? val2.GetInventory().GetItem(fuelName) : null);
				}
				if (val == null)
				{
					if (flag)
					{
						return true;
					}
					((Character)user).Message((MessageType)2, "$msg_outof " + fuelName, 0, (Sprite)null);
					return false;
				}
			}
			((Character)user).Message((MessageType)2, Localization.instance.Localize("$msg_fireadding", new string[1] { fuelName }), 0, (Sprite)null);
			int val3 = (int)(__instance.m_maxFuel - num);
			int num2 = 1;
			if (!flag)
			{
				num2 = Math.Min(val.m_stack, val3);
			}
			if ((Object)(object)val2 == (Object)null)
			{
				user.GetInventory().RemoveItem(val, num2);
			}
			else
			{
				val2.GetInventory().RemoveItem(val, num2);
				typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(val2, new object[0]);
			}
			for (int i = 0; i < num2; i++)
			{
				___m_nview.InvokeRPC("AddFuel", Array.Empty<object>());
			}
			__result = true;
			return false;
		}

		private static void RPC_AddFuel(Fireplace instance, ZNetView m_nview, float count)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if (m_nview.IsOwner())
			{
				float num = Mathf.Clamp(m_nview.GetZDO().GetFloat("fuel", 0f) + count, 0f, instance.m_maxFuel);
				m_nview.GetZDO().Set("fuel", num);
				instance.m_fuelAddedEffects.Create(((Component)instance).transform.position, ((Component)instance).transform.rotation, (Transform)null, 1f);
				ZLog.Log((object)$"Added fuel * {count}");
				Traverse.Create((object)instance).Method("UpdateState", Array.Empty<object>()).GetValue();
			}
		}
	}

	private static class Utility
	{
		public static List<Container> GetNearByContainer(Vector3 center)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			float sqrRange = UseFromContainerRange.Value * UseFromContainerRange.Value;
			List<Container> list = Containers.Where(delegate(Container n)
			{
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)n != (Object)null && (Object)(object)((Component)n).transform != (Object)null && n.GetInventory() != null)
				{
					Vector3 val = ((Component)n).transform.position - center;
					if (((Vector3)(ref val)).sqrMagnitude < sqrRange)
					{
						return Traverse.Create((object)n).Method("CheckAccess", new object[1] { Player.m_localPlayer.GetPlayerID() }).GetValue<bool>();
					}
				}
				return false;
			})?.ToList();
			if (list == null || list.Count() == 0)
			{
				return null;
			}
			return list;
		}
	}

	private const string PluginGuid = "rin_jugatla.AddAllFuel";

	private const string PluginName = "AddAllFuel";

	private const string PluginVersion = "1.6.1";

	private static readonly bool IsDebug = false;

	private static ConfigEntry<bool> IsEnabled;

	private static ConfigEntry<int> NexusID;

	private static ConfigEntry<string> ModifierKey;

	private static ConfigEntry<bool> IsReverseModifierMode;

	private static IReadOnlyList<string> ExcludeNames;

	private static ConfigEntry<bool> IsAllowAddOneExcludeItem;

	private static ConfigEntry<bool> IsUseFromContainer;

	private static ConfigEntry<float> UseFromContainerRange;

	private static List<Container> Containers = new List<Container>();

	private void Awake()
	{
		IsEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable this mod");
		NexusID = ((BaseUnityPlugin)this).Config.Bind<int>("General", "NexusID", 107, "Nexus mod ID for updates");
		ModifierKey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ModifierKey", "left shift", "Modifier keys for using mods");
		IsReverseModifierMode = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "IsReverseModifierMode", false, "false: Batch submit with ModifierKey + UseKey. true: Batch submit with UseKey.");
		ExcludeNames = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ExcludeNames", "", "Name of item not to be used as fuel/ore. Setting example: $item_finewood,$item_roundlog").Value.Replace(" ", "").Split(new char[1] { ',' }).ToList();
		IsAllowAddOneExcludeItem = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AllowAddOneExcludeItem", true, "Allow the addition of excluded items if you don't want to do batch processing?");
		IsUseFromContainer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "UseFromContainer", false, "If you don't have enough items on hand, you can replenish them from containers.");
		UseFromContainerRange = ((BaseUnityPlugin)this).Config.Bind<float>("General", "UseFromContainerRange", 5f, "Search range when replenishing items from containers.");
		if (IsEnabled.Value)
		{
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		}
	}
}

BepInEx/plugins/RockerKitten-BoneAppetit/BoneAppetit.dll

Decompiled 8 months ago
#define DEBUG
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using Boneappetit;
using HarmonyLib;
using JetBrains.Annotations;
using Jotunn;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("BoneAppetit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BoneAppetit")]
[assembly: AssemblyCopyright("Copyright RockerKitten and sbtoon©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")]
[assembly: AssemblyFileVersion("3.3.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.3.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
[RequireComponent(typeof(ParticleSystem))]
public class CFX_AutoDestructShuriken : MonoBehaviour
{
	public bool OnlyDeactivate;

	private void OnEnable()
	{
		((MonoBehaviour)this).StartCoroutine("CheckIfAlive");
	}

	private IEnumerator CheckIfAlive()
	{
		ParticleSystem ps = ((Component)this).GetComponent<ParticleSystem>();
		while ((Object)(object)ps != (Object)null)
		{
			yield return (object)new WaitForSeconds(0.5f);
			if (!ps.IsAlive(true))
			{
				if (OnlyDeactivate)
				{
					((Component)this).gameObject.SetActive(false);
				}
				else
				{
					Object.Destroy((Object)(object)((Component)this).gameObject);
				}
				break;
			}
		}
	}
}
public class CFX_AutoRotate : MonoBehaviour
{
	public Vector3 rotation;

	public Space space = (Space)1;

	private void Update()
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		((Component)this).transform.Rotate(rotation * Time.deltaTime, space);
	}
}
[RequireComponent(typeof(ParticleSystem))]
public class CFX_ElectricityBall : MonoBehaviour
{
	public bool OnlyDeactivate;

	private void OnEnable()
	{
		((MonoBehaviour)this).StartCoroutine("CheckIfAlive");
	}

	private IEnumerator CheckIfAlive()
	{
		ParticleSystem ps = ((Component)this).GetComponent<ParticleSystem>();
		while ((Object)(object)ps != (Object)null)
		{
			yield return (object)new WaitForSeconds(0.5f);
			if (!ps.IsAlive(true))
			{
				if (OnlyDeactivate)
				{
					((Component)this).gameObject.SetActive(false);
				}
				else
				{
					Object.Destroy((Object)(object)((Component)this).gameObject);
				}
				break;
			}
		}
	}
}
[RequireComponent(typeof(Light))]
public class CFX_LightFlicker : MonoBehaviour
{
	public bool loop;

	public float smoothFactor = 1f;

	public float addIntensity = 1f;

	private float minIntensity;

	private float maxIntensity;

	private float baseIntensity;

	private void Awake()
	{
		baseIntensity = ((Component)this).GetComponent<Light>().intensity;
	}

	private void OnEnable()
	{
		minIntensity = baseIntensity;
		maxIntensity = minIntensity + addIntensity;
	}

	private void Update()
	{
		((Component)this).GetComponent<Light>().intensity = Mathf.Lerp(minIntensity, maxIntensity, Mathf.PerlinNoise(Time.time * smoothFactor, 0f));
	}
}
[RequireComponent(typeof(Light))]
public class CFX_LightIntensityFade : MonoBehaviour
{
	public float duration = 1f;

	public float delay = 0f;

	public float finalIntensity = 0f;

	private float baseIntensity;

	public bool autodestruct;

	private float p_lifetime = 0f;

	private float p_delay;

	private void Start()
	{
		baseIntensity = ((Component)this).GetComponent<Light>().intensity;
	}

	private void OnEnable()
	{
		p_lifetime = 0f;
		p_delay = delay;
		if (delay > 0f)
		{
			((Behaviour)((Component)this).GetComponent<Light>()).enabled = false;
		}
	}

	private void Update()
	{
		if (p_delay > 0f)
		{
			p_delay -= Time.deltaTime;
			if (p_delay <= 0f)
			{
				((Behaviour)((Component)this).GetComponent<Light>()).enabled = true;
			}
		}
		else if (p_lifetime / duration < 1f)
		{
			((Component)this).GetComponent<Light>().intensity = Mathf.Lerp(baseIntensity, finalIntensity, p_lifetime / duration);
			p_lifetime += Time.deltaTime;
		}
		else if (autodestruct)
		{
			Object.Destroy((Object)(object)((Component)this).gameObject);
		}
	}
}
[Serializable]
internal enum ShaderType
{
	Alpha,
	Blob,
	Bonemass,
	Clouds,
	Creature,
	Decal,
	Distortion,
	Flow,
	FlowOpaque,
	Grass,
	GuiScroll,
	HeightMap,
	Icon,
	InteriorSide,
	LitGui,
	LitParticles,
	MapShader,
	ParticleDetail,
	Piece,
	Player,
	Rug,
	ShadowBlob,
	SkyboxProcedural,
	SkyObject,
	StaticRock,
	Tar,
	TrilinearMap,
	BGBlur,
	Water,
	WaterBottom,
	WaterMask,
	Yggdrasil,
	YggdrasilRoot,
	ToonDeferredShading2017
}
public class ShaderReplacerNew : MonoBehaviour
{
	[Tooltip("Use this Field For Normal Renderers")]
	[SerializeField]
	internal Renderer[] _renderers = null;

	[SerializeField]
	internal ShaderType _shaderType = ShaderType.Creature;

	[SerializeField]
	internal bool DebugOutput = false;

	private void Awake()
	{
		if (IsHeadlessMode() || _renderers.Length == 0 || !((Component)this).gameObject.activeInHierarchy)
		{
			return;
		}
		Renderer[] renderers = _renderers;
		foreach (Renderer val in renderers)
		{
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			Material[] sharedMaterials = val.sharedMaterials;
			foreach (Material val2 in sharedMaterials)
			{
				if ((Object)(object)val2 == (Object)null)
				{
					((Component)val).gameObject.SetActive(false);
				}
				else
				{
					val2.shader = Shader.Find(ReturnEnumString(_shaderType));
				}
			}
		}
	}

	internal string ReturnEnumString(ShaderType shaderchoice)
	{
		string result = "";
		switch (shaderchoice)
		{
		case ShaderType.Alpha:
			result = "Custom/AlphaParticle";
			break;
		case ShaderType.Blob:
			result = "Custom/Blob";
			break;
		case ShaderType.Bonemass:
			result = "Custom/Bonemass";
			break;
		case ShaderType.Clouds:
			result = "Custom/Clouds";
			break;
		case ShaderType.Creature:
			result = "Custom/Creature";
			break;
		case ShaderType.Decal:
			result = "Custom/Decal";
			break;
		case ShaderType.Distortion:
			result = "Custom/Distortion";
			break;
		case ShaderType.Flow:
			result = "Custom/Flow";
			break;
		case ShaderType.FlowOpaque:
			result = "Custom/FlowOpaque";
			break;
		case ShaderType.Grass:
			result = "Custom/Grass";
			break;
		case ShaderType.GuiScroll:
			result = "Custom/GuiScroll";
			break;
		case ShaderType.HeightMap:
			result = "Custom/HeightMap";
			break;
		case ShaderType.Icon:
			result = "Custom/Icon";
			break;
		case ShaderType.InteriorSide:
			result = "Custom/InteriorSide";
			break;
		case ShaderType.LitGui:
			result = "Custom/LitGui";
			break;
		case ShaderType.LitParticles:
			result = "Lux Lit Particles/ Bumped";
			break;
		case ShaderType.MapShader:
			result = "Custom/mapshader";
			break;
		case ShaderType.ParticleDetail:
			result = "Custom/ParticleDecal";
			break;
		case ShaderType.Piece:
			result = "Custom/Piece";
			break;
		default:
			throw new ArgumentOutOfRangeException("shaderchoice", shaderchoice, null);
		case ShaderType.Player:
		case ShaderType.Rug:
		case ShaderType.ShadowBlob:
		case ShaderType.SkyboxProcedural:
		case ShaderType.SkyObject:
		case ShaderType.StaticRock:
		case ShaderType.Tar:
		case ShaderType.TrilinearMap:
		case ShaderType.BGBlur:
		case ShaderType.Water:
		case ShaderType.WaterBottom:
		case ShaderType.WaterMask:
		case ShaderType.Yggdrasil:
		case ShaderType.YggdrasilRoot:
		case ShaderType.ToonDeferredShading2017:
			break;
		}
		return result;
	}

	public static bool IsHeadlessMode()
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Invalid comparison between Unknown and I4
		return (int)SystemInfo.graphicsDeviceType == 4;
	}
}
namespace BoneAppetit
{
	public static class Patch
	{
		[HarmonyPatch(typeof(CookingStation))]
		public static class PatchCookingStation
		{
			[HarmonyPostfix]
			[HarmonyPatch("CookItem")]
			[HarmonyPriority(400)]
			[UsedImplicitly]
			public static void Postfix(ref bool __result)
			{
				try
				{
					Boneappetit.BoneAppetit.Instance.OnCookingStationCookItem(ref __result);
				}
				catch (Exception ex)
				{
					Logger.LogError((object)ex);
				}
			}
		}

		[HarmonyPatch(typeof(Inventory), "AddItem", new Type[]
		{
			typeof(string),
			typeof(int),
			typeof(int),
			typeof(int),
			typeof(long),
			typeof(string),
			typeof(bool)
		})]
		public static class PatchInventory
		{
			[HarmonyPostfix]
			[HarmonyPriority(400)]
			[UsedImplicitly]
			public static void Postfix(string name, int stack, int quality, int variant, long crafterID, string crafterName, bool pickedUp)
			{
				try
				{
					Logger.LogDebug((object)"PatchInventoryPostfix");
					if ((Object)(object)Player.m_localPlayer == (Object)null)
					{
						Logger.LogDebug((object)"Player is null");
					}
					else
					{
						Boneappetit.BoneAppetit.Instance.OnInventoryAddItemPostFix(name, stack, quality, variant, crafterID, crafterName);
					}
				}
				catch (Exception ex)
				{
					Logger.LogError((object)ex);
				}
			}
		}
	}
}
namespace Boneappetit
{
	[BepInPlugin("com.rockerkitten.boneappetit", "BoneAppetit", "3.3.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class BoneAppetit : BaseUnityPlugin
	{
		public const string PluginGUID = "com.rockerkitten.boneappetit";

		public const string PluginName = "BoneAppetit";

		public const string PluginVersion = "3.3.0";

		public AssetBundle GrillAssetBundle;

		public AssetBundle FoodAssetBundle;

		public static BoneAppetit Instance;

		private Harmony _harmony;

		public Sprite CookingSprite;

		public SkillType rkCookingSkill;

		public static ConfigEntry<int> NexusId;

		public ConfigEntry<bool> PorkRindEnable;

		public ConfigEntry<bool> KabobEnable;

		public ConfigEntry<bool> FriedLoxEnable;

		public ConfigEntry<bool> GlazedCarrotEnable;

		public ConfigEntry<bool> BaconEnable;

		public ConfigEntry<bool> SmokedFishEnable;

		public ConfigEntry<bool> PancakesEnable;

		public ConfigEntry<bool> PizzaEnable;

		public ConfigEntry<bool> CoffeeEnable;

		public ConfigEntry<bool> LatteEnable;

		public ConfigEntry<bool> SmokelessEnable;

		public ConfigEntry<bool> HaggisEnable;

		public ConfigEntry<bool> CandiedTurnipEnable;

		public ConfigEntry<bool> MoochiEnable;

		public ConfigEntry<bool> Nut_EllaEnable;

		public ConfigEntry<bool> BrothEnable;

		public ConfigEntry<bool> FishStewEnable;

		public ConfigEntry<bool> ButterEnable;

		public ConfigEntry<bool> BloodSausageEnable;

		public ConfigEntry<bool> OmletteEnable;

		public ConfigEntry<bool> BurgerEnable;

		public ConfigEntry<bool> PorridgeEnable;

		public ConfigEntry<bool> PBJEnable;

		public ConfigEntry<bool> BoiledEggEnable;

		public ConfigEntry<bool> CakeEnable;

		public ConfigEntry<bool> GrillOriginal;

		public ConfigEntry<bool> CarrotSticksEnable;

		public ConfigEntry<bool> CheffHatEnable;

		public ConfigEntry<bool> MeadEnable;

		public ConfigEntry<bool> CookingSkillEnable;

		public ConfigEntry<bool> BonusWhenCookingEnabled;

		public ConfigEntry<bool> HatSEMessage;

		public ConfigEntry<float> HatXpGain;

		public EffectList buildStone;

		public EffectList cookingSound;

		public EffectList breakStone;

		public EffectList hitStone;

		public EffectList buildKitten;

		public EffectList hearthAddFuel;

		public EffectList fireAddFuel;

		public Dictionary<string, GameObject> Prefabs = new Dictionary<string, GameObject>();

		public GameObject icecream_prefab;

		public CustomItem icecream;

		public GameObject porkrind_prefab;

		public CustomItem porkrind;

		public GameObject kabob_prefab;

		public CustomItem kabob;

		public GameObject friedlox_prefab;

		public CustomItem friedlox;

		public GameObject glazedcarrot_prefab;

		public CustomItem glazedcarrot;

		public GameObject bacon_prefab;

		public CustomItem bacon;

		public GameObject smokedfish_prefab;

		public CustomItem smokedfish;

		public GameObject pancake_prefab;

		public CustomItem pancake;

		public GameObject pizza_prefab;

		public CustomItem pizza;

		public GameObject coffee_prefab;

		public CustomItem coffee;

		public GameObject latte_prefab;

		public CustomItem latte;

		public GameObject firecream_prefab;

		public CustomItem firecream;

		public CustomItem electriccream;

		public GameObject electriccream_prefab;

		public CustomItem acidcream;

		public GameObject acidcream_prefab;

		public GameObject porridge_prefab;

		public CustomItem porridge;

		public GameObject pbj_prefab;

		public CustomItem pbj;

		public GameObject cake_prefab;

		public CustomItem cake;

		public AudioSource fireVol;

		public GameObject haggisFab;

		public CustomItem haggis;

		public GameObject candiedTurnipFab;

		public CustomItem candiedTurnip;

		public GameObject moochiFab;

		public CustomItem moochi;

		public GameObject omletteFab;

		public CustomItem omlette;

		public GameObject fishStewFab;

		public CustomItem fishStew;

		public GameObject brothFab;

		public CustomItem broth;

		public GameObject butterFab;

		public CustomItem butter;

		public GameObject bloodsausageFab;

		public CustomItem bloodsausage;

		public GameObject burgerFab;

		public CustomItem burger;

		public GameObject nut_ellaFab;

		public CustomItem nut_ella;

		public GameObject boiledeggFab;

		public CustomItem boiledegg;

		public GameObject carrotstickFab;

		public CustomItem carrotstick;

		public GameObject meadFab;

		public CustomItem mead;

		public GameObject hatFab;

		public CustomItem hat;

		public GameObject fireFab1;

		public CustomPiece fire1;

		public GameObject fireFab2;

		public CustomPiece fire2;

		public GameObject fireFab3;

		private CustomPiece fire3;

		public GameObject eggFab;

		public GameObject deggFab;

		public GameObject porkFab;

		private static bool _isAddingExtraItem;

		public ConfigEntry<bool> ConesEnable { get; private set; }

		public BoneAppetit()
		{
			Instance = this;
		}

		[UsedImplicitly]
		public void Awake()
		{
			CreateConfigValues();
			AssetLoad();
			AddSkills();
			PrefabManager.OnVanillaPrefabsAvailable += LoadSounds;
			ItemManager.OnItemsRegistered += NewDrops;
			SynchronizationManager.OnConfigurationSynchronized += delegate(object obj, ConfigurationSynchronizationEventArgs attr)
			{
				if (attr.InitialSynchronization)
				{
					Logger.LogMessage((object)"Initial Config sync event received");
					LoadFood();
				}
				else
				{
					Logger.LogMessage((object)"Config sync event received");
				}
			};
			_harmony = Harmony.CreateAndPatchAll(typeof(BoneAppetit).Assembly, "com.rockerkitten.boneappetit");
		}

		[UsedImplicitly]
		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		public void CreateConfigValues()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Expected O, but got Unknown
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Expected O, but got Unknown
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Expected O, but got Unknown
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Expected O, but got Unknown
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Expected O, but got Unknown
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Expected O, but got Unknown
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Expected O, but got Unknown
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Expected O, but got Unknown
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Expected O, but got Unknown
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Expected O, but got Unknown
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c4: Expected O, but got Unknown
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Expected O, but got Unknown
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0301: Expected O, but got Unknown
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_032b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Expected O, but got Unknown
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Expected O, but got Unknown
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Expected O, but got Unknown
			//IL_0371: Unknown result type (might be due to invalid IL or missing references)
			//IL_037b: Expected O, but got Unknown
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ae: Expected O, but got Unknown
			//IL_03ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b8: Expected O, but got Unknown
			//IL_03dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03eb: Expected O, but got Unknown
			//IL_03eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f5: Expected O, but got Unknown
			//IL_041a: Unknown result type (might be due to invalid IL or missing references)
			//IL_041f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0428: Expected O, but got Unknown
			//IL_0428: Unknown result type (might be due to invalid IL or missing references)
			//IL_0432: Expected O, but got Unknown
			//IL_0457: Unknown result type (might be due to invalid IL or missing references)
			//IL_045c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0465: Expected O, but got Unknown
			//IL_0465: Unknown result type (might be due to invalid IL or missing references)
			//IL_046f: Expected O, but got Unknown
			//IL_0494: Unknown result type (might be due to invalid IL or missing references)
			//IL_0499: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a2: Expected O, but got Unknown
			//IL_04a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ac: Expected O, but got Unknown
			//IL_04d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04df: Expected O, but got Unknown
			//IL_04df: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e9: Expected O, but got Unknown
			//IL_050e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0513: Unknown result type (might be due to invalid IL or missing references)
			//IL_051c: Expected O, but got Unknown
			//IL_051c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0526: Expected O, but got Unknown
			//IL_054b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0550: Unknown result type (might be due to invalid IL or missing references)
			//IL_0559: Expected O, but got Unknown
			//IL_0559: Unknown result type (might be due to invalid IL or missing references)
			//IL_0563: Expected O, but got Unknown
			//IL_0588: Unknown result type (might be due to invalid IL or missing references)
			//IL_058d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0596: Expected O, but got Unknown
			//IL_0596: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a0: Expected O, but got Unknown
			//IL_05c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d3: Expected O, but got Unknown
			//IL_05d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05dd: Expected O, but got Unknown
			//IL_0602: Unknown result type (might be due to invalid IL or missing references)
			//IL_0607: Unknown result type (might be due to invalid IL or missing references)
			//IL_0610: Expected O, but got Unknown
			//IL_0610: Unknown result type (might be due to invalid IL or missing references)
			//IL_061a: Expected O, but got Unknown
			//IL_063f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0644: Unknown result type (might be due to invalid IL or missing references)
			//IL_064d: Expected O, but got Unknown
			//IL_064d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0657: Expected O, but got Unknown
			//IL_067c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0681: Unknown result type (might be due to invalid IL or missing references)
			//IL_068a: Expected O, but got Unknown
			//IL_068a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0694: Expected O, but got Unknown
			//IL_06b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06be: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c7: Expected O, but got Unknown
			//IL_06c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d1: Expected O, but got Unknown
			//IL_06f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0704: Expected O, but got Unknown
			//IL_0704: Unknown result type (might be due to invalid IL or missing references)
			//IL_070e: Expected O, but got Unknown
			//IL_0733: Unknown result type (might be due to invalid IL or missing references)
			//IL_0738: Unknown result type (might be due to invalid IL or missing references)
			//IL_0741: Expected O, but got Unknown
			//IL_0741: Unknown result type (might be due to invalid IL or missing references)
			//IL_074b: Expected O, but got Unknown
			//IL_0770: Unknown result type (might be due to invalid IL or missing references)
			//IL_0775: Unknown result type (might be due to invalid IL or missing references)
			//IL_077e: Expected O, but got Unknown
			//IL_077e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0788: Expected O, but got Unknown
			//IL_07ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_07b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_07c7: Expected O, but got Unknown
			//IL_07c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_07d1: Expected O, but got Unknown
			//IL_07f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_07fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0803: Unknown result type (might be due to invalid IL or missing references)
			//IL_0810: Expected O, but got Unknown
			//IL_0810: Unknown result type (might be due to invalid IL or missing references)
			//IL_081a: Expected O, but got Unknown
			//IL_0843: Unknown result type (might be due to invalid IL or missing references)
			//IL_0848: Unknown result type (might be due to invalid IL or missing references)
			//IL_0850: Unknown result type (might be due to invalid IL or missing references)
			//IL_085d: Expected O, but got Unknown
			//IL_085d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0867: Expected O, but got Unknown
			//IL_088c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0891: Unknown result type (might be due to invalid IL or missing references)
			//IL_0899: Unknown result type (might be due to invalid IL or missing references)
			//IL_08a6: Expected O, but got Unknown
			//IL_08a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_08b0: Expected O, but got Unknown
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = true;
			NexusId = ((BaseUnityPlugin)this).Config.Bind<int>("Hidden", "NexusId", 1250, new ConfigDescription("NexusId", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = false,
				Browsable = false,
				ReadOnly = true
			} }));
			ConesEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Cones", "Enable", true, new ConfigDescription("All Cones Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			PorkRindEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Pork Rind", "Enable", true, new ConfigDescription("Pork Rind Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			KabobEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Kabob", "Enable", true, new ConfigDescription("Kabob Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			FriedLoxEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Fried Lox", "Enable", true, new ConfigDescription("Fried Lox Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			GlazedCarrotEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Glazed Carrots", "Enable", true, new ConfigDescription("Glazed Carrots Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			BaconEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Bacon", "Enable", true, new ConfigDescription("Bacon Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			SmokedFishEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Smoked Fish", "Enable", true, new ConfigDescription("Smoked Fish Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			PancakesEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Pancakes", "Enable", true, new ConfigDescription("Pancakes Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			PizzaEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Pizza", "Enable", true, new ConfigDescription("Pizza Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			CoffeeEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Coffee", "Enable", true, new ConfigDescription("Coffee Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			LatteEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Latte", "Enable", true, new ConfigDescription("Latte Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			PorridgeEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Porridge", "Enable", true, new ConfigDescription("Porridge Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			PBJEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("PBJ", "Enable", true, new ConfigDescription("PBJ Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			CakeEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Cake", "Enable", true, new ConfigDescription("Birthday Cake Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			HaggisEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Haggis", "Enable", true, new ConfigDescription("Haggis Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			CandiedTurnipEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Candied Turnip", "Enable", true, new ConfigDescription("Candied Turnip Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			MoochiEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Moochi", "Enable", true, new ConfigDescription("Moochi Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			Nut_EllaEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Nut_Ella", "Enable", true, new ConfigDescription("Nut_Ella Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			BurgerEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Burger", "Enable", true, new ConfigDescription("Burger Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			OmletteEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Omlette", "Enable", true, new ConfigDescription("Omlette Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			BrothEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Broth", "Enable", true, new ConfigDescription("Broth Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			FishStewEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Fish Stew", "Enable", true, new ConfigDescription("Fish Stew Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			ButterEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Butter", "Enable", true, new ConfigDescription("Butter Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			BloodSausageEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Blood Sausage", "Enable", true, new ConfigDescription("Blood Sausage Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			BoiledEggEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Boiled Egg", "Enable", true, new ConfigDescription("Boiled Egg Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			CarrotSticksEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Carrot Sticks", "Enable", true, new ConfigDescription("Carrot Sticks Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			CheffHatEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Chef Hat", "Enable", true, new ConfigDescription("Chef Hat Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			MeadEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Mead", "Enable", true, new ConfigDescription("Mead Enable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			GrillOriginal = ((BaseUnityPlugin)this).Config.Bind<bool>("Original", "Enable", true, new ConfigDescription("Use original grill", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			SmokelessEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Smokeless", "Enable", true, new ConfigDescription("Enable to allow building of smokeless fires", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			CookingSkillEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("Cooking Skill", "Enable Cooking Skill", true, new ConfigDescription("Enable Cooking Skill", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = 1
			} }));
			BonusWhenCookingEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Cooking Skill", "Enable Cooking Bonus", true, new ConfigDescription("Enable Cooking Bonus", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = 2
			} }));
			HatXpGain = ((BaseUnityPlugin)this).Config.Bind<float>("Cooking Skill", "Chef Hat XP Gain", 5f, new ConfigDescription("XP Gain multiplier when cooking while wearing the Chef Hat", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = 3
			} }));
			HatSEMessage = ((BaseUnityPlugin)this).Config.Bind<bool>("Cooking Skill", "Enable Chef Hat Message", true, new ConfigDescription("Enable Message when equipping the Chef Hat", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = false,
				Order = 4
			} }));
		}

		public void LoadFood()
		{
			icecream.Recipe.Recipe.m_enabled = ConesEnable.Value;
			porkrind.Recipe.Recipe.m_enabled = PorkRindEnable.Value;
			kabob.Recipe.Recipe.m_enabled = KabobEnable.Value;
			friedlox.Recipe.Recipe.m_enabled = FriedLoxEnable.Value;
			glazedcarrot.Recipe.Recipe.m_enabled = GlazedCarrotEnable.Value;
			bacon.Recipe.Recipe.m_enabled = BaconEnable.Value;
			smokedfish.Recipe.Recipe.m_enabled = SmokedFishEnable.Value;
			pancake.Recipe.Recipe.m_enabled = PancakesEnable.Value;
			pizza.Recipe.Recipe.m_enabled = PizzaEnable.Value;
			coffee.Recipe.Recipe.m_enabled = CoffeeEnable.Value;
			latte.Recipe.Recipe.m_enabled = LatteEnable.Value;
			firecream.Recipe.Recipe.m_enabled = ConesEnable.Value;
			electriccream.Recipe.Recipe.m_enabled = ConesEnable.Value;
			acidcream.Recipe.Recipe.m_enabled = ConesEnable.Value;
			porridge.Recipe.Recipe.m_enabled = PorridgeEnable.Value;
			pbj.Recipe.Recipe.m_enabled = PBJEnable.Value;
			cake.Recipe.Recipe.m_enabled = CakeEnable.Value;
			haggis.Recipe.Recipe.m_enabled = HaggisEnable.Value;
			candiedTurnip.Recipe.Recipe.m_enabled = CandiedTurnipEnable.Value;
			moochi.Recipe.Recipe.m_enabled = MoochiEnable.Value;
			nut_ella.Recipe.Recipe.m_enabled = Nut_EllaEnable.Value;
			burger.Recipe.Recipe.m_enabled = BurgerEnable.Value;
			omlette.Recipe.Recipe.m_enabled = OmletteEnable.Value;
			broth.Recipe.Recipe.m_enabled = BrothEnable.Value;
			fishStew.Recipe.Recipe.m_enabled = FishStewEnable.Value;
			butter.Recipe.Recipe.m_enabled = ButterEnable.Value;
			bloodsausage.Recipe.Recipe.m_enabled = BloodSausageEnable.Value;
			boiledegg.Recipe.Recipe.m_enabled = BoiledEggEnable.Value;
			carrotstick.Recipe.Recipe.m_enabled = CarrotSticksEnable.Value;
			mead.Recipe.Recipe.m_enabled = MeadEnable.Value;
			fire1.Piece.m_enabled = SmokelessEnable.Value;
			fire2.Piece.m_enabled = SmokelessEnable.Value;
			fire3.Piece.m_enabled = SmokelessEnable.Value;
		}

		public void AssetLoad()
		{
			GrillAssetBundle = AssetUtils.LoadAssetBundleFromResources("grill", Assembly.GetExecutingAssembly());
			FoodAssetBundle = AssetUtils.LoadAssetBundleFromResources("customfood", Assembly.GetExecutingAssembly());
			CookingSprite = FoodAssetBundle.LoadAsset<Sprite>("rkcookingsprite");
			Logger.LogMessage((object)"Prepping Kitchen...");
			LoadDropFab();
			Logger.LogMessage((object)"Big thanks to MeatwareMonster!");
		}

		public void LoadSounds()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected O, but got Unknown
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Expected O, but got Unknown
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Expected O, but got Unknown
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Expected O, but got Unknown
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Expected O, but got Unknown
			try
			{
				GameObject prefab = Cache.GetPrefab<GameObject>("sfx_build_hammer_stone");
				GameObject prefab2 = Cache.GetPrefab<GameObject>("vfx_Place_stone_wall_2x1");
				GameObject prefab3 = Cache.GetPrefab<GameObject>("sfx_cooking_station_done");
				GameObject prefab4 = Cache.GetPrefab<GameObject>("sfx_rock_destroyed");
				GameObject prefab5 = Cache.GetPrefab<GameObject>("vfx_FireAddFuel");
				GameObject prefab6 = Cache.GetPrefab<GameObject>("sfx_FireAddFuel");
				GameObject prefab7 = Cache.GetPrefab<GameObject>("sfx_rock_hit");
				GameObject prefab8 = Cache.GetPrefab<GameObject>("vfx_HearthAddFuel");
				EffectList val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[2]
				{
					new EffectData
					{
						m_prefab = prefab
					},
					new EffectData
					{
						m_prefab = prefab2
					}
				};
				buildStone = val;
				val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[1]
				{
					new EffectData
					{
						m_prefab = prefab3
					}
				};
				cookingSound = val;
				val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[1]
				{
					new EffectData
					{
						m_prefab = prefab4
					}
				};
				breakStone = val;
				val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[1]
				{
					new EffectData
					{
						m_prefab = prefab7
					}
				};
				hitStone = val;
				val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[1]
				{
					new EffectData
					{
						m_prefab = prefab
					}
				};
				buildKitten = val;
				val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[2]
				{
					new EffectData
					{
						m_prefab = prefab8
					},
					new EffectData
					{
						m_prefab = prefab6
					}
				};
				hearthAddFuel = val;
				val = new EffectList();
				val.m_effectPrefabs = (EffectData[])(object)new EffectData[2]
				{
					new EffectData
					{
						m_prefab = prefab5
					},
					new EffectData
					{
						m_prefab = prefab6
					}
				};
				fireAddFuel = val;
				Logger.LogMessage((object)"Loaded Game VFX and SFX");
				Butter();
				Nut_Ella();
				IceCream();
				PorkRind();
				Kabob();
				FriedLox();
				GlazedCarrot();
				Bacon();
				SmokedFish();
				Pancakes();
				Pizza();
				Coffee();
				Latte();
				FireCream();
				ElectricCream();
				AcidCream();
				Porridge();
				PBJ();
				Cake();
				Haggis();
				CandiedTurnip();
				Moochi();
				Broth();
				FishStew();
				BloodSausage();
				Burger();
				Omlette();
				BoiledEgg();
				CarrotSticks();
				ChefHatt();
				Mead();
				LoadGrillItem();
				LoadGriddle();
				Oven();
				LoadFire();
				LoadHearth();
				Prepstation();
				Brazier();
				fireVol = AudioMan.instance.m_ambientLoopSource;
			}
			catch (Exception ex)
			{
				Logger.LogError((object)("Error while running OnVanillaLoad: " + ex.Message));
			}
			finally
			{
				Logger.LogMessage((object)"Load Complete. Bone Appetit yall.");
				PrefabManager.OnVanillaPrefabsAvailable -= LoadSounds;
			}
		}

		public void NewDrops()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Expected O, but got Unknown
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Expected O, but got Unknown
			GameObject prefab = PrefabManager.Instance.GetPrefab("Boar");
			GameObject prefab2 = PrefabManager.Instance.GetPrefab("Hatchling");
			GameObject prefab3 = PrefabManager.Instance.GetPrefab("Seagal");
			GameObject prefab4 = PrefabManager.Instance.GetPrefab("Crow");
			GameObject prefab5 = PrefabManager.Instance.GetPrefab("rk_pork");
			GameObject prefab6 = PrefabManager.Instance.GetPrefab("rk_egg");
			GameObject prefab7 = PrefabManager.Instance.GetPrefab("rk_dragonegg");
			DropOnDestroyed component = prefab3.GetComponent<DropOnDestroyed>();
			component.m_dropWhenDestroyed.m_drops.Add(new DropData
			{
				m_item = prefab6,
				m_stackMin = 1,
				m_stackMax = 1,
				m_weight = 1f
			});
			component.m_dropWhenDestroyed.m_oneOfEach = true;
			component.m_dropWhenDestroyed.m_dropMax = 2;
			component.m_dropWhenDestroyed.m_dropMin = 2;
			component.m_dropWhenDestroyed.m_dropChance = 1f;
			component.m_spawnYStep = 0.3f;
			component.m_spawnYOffset = 0.5f;
			DropOnDestroyed component2 = prefab4.GetComponent<DropOnDestroyed>();
			component2.m_dropWhenDestroyed.m_drops.Add(new DropData
			{
				m_item = prefab6,
				m_stackMin = 1,
				m_stackMax = 1,
				m_weight = 1f
			});
			component2.m_dropWhenDestroyed.m_oneOfEach = true;
			component2.m_dropWhenDestroyed.m_dropMax = 2;
			component2.m_dropWhenDestroyed.m_dropMin = 2;
			component2.m_dropWhenDestroyed.m_dropChance = 1f;
			component2.m_spawnYStep = 0.3f;
			component2.m_spawnYOffset = 0.5f;
			prefab.GetComponent<CharacterDrop>().m_drops.Add(new Drop
			{
				m_prefab = prefab5,
				m_amountMin = 1,
				m_amountMax = 1,
				m_chance = 1f,
				m_levelMultiplier = true,
				m_onePerPlayer = false
			});
			prefab2.GetComponent<CharacterDrop>().m_drops.Add(new Drop
			{
				m_prefab = prefab7,
				m_amountMin = 1,
				m_amountMax = 1,
				m_chance = 1f,
				m_levelMultiplier = true,
				m_onePerPlayer = false
			});
			ItemManager.OnItemsRegistered -= NewDrops;
		}

		public void AddSkills()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			if (CookingSkillEnable.Value)
			{
				rkCookingSkill = SkillManager.Instance.AddSkill(new SkillConfig
				{
					Identifier = "com.rockerkitten.boneappetit",
					Name = "Gore-mand",
					Description = "Learn to cook and eat like a Viking!",
					Icon = CookingSprite,
					IncreaseStep = 1f
				});
			}
		}

		public void LoadDropFab()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			porkFab = FoodAssetBundle.LoadAsset<GameObject>("rk_pork");
			ItemManager.Instance.AddItem(new CustomItem(porkFab, false));
			eggFab = FoodAssetBundle.LoadAsset<GameObject>("rk_egg");
			ItemManager.Instance.AddItem(new CustomItem(eggFab, false));
			deggFab = FoodAssetBundle.LoadAsset<GameObject>("rk_dragonegg");
			ItemManager.Instance.AddItem(new CustomItem(deggFab, false));
		}

		private void LoadGrillItem()
		{
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Expected O, but got Unknown
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Expected O, but got Unknown
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Expected O, but got Unknown
			GameObject val;
			if (GrillOriginal.Value)
			{
				val = GrillAssetBundle.LoadAsset<GameObject>("rk_grill");
				if ((Object)(object)val.GetComponent<WearNTear>() == (Object)null)
				{
					WearNTear val2 = val.AddComponent<WearNTear>();
					val2.m_broken = val;
					val2.m_new = val;
					val2.m_wet = val;
					val2.m_worn = val;
					val2.m_noSupportWear = false;
				}
				if ((Object)(object)val.GetComponent<WearNTear>() != (Object)null)
				{
					WearNTear component = val.GetComponent<WearNTear>();
					component.m_supports = false;
					component.m_noSupportWear = false;
				}
			}
			else
			{
				val = FoodAssetBundle.LoadAsset<GameObject>("rk_grill");
				if ((Object)(object)val.GetComponent<WearNTear>() == (Object)null)
				{
					WearNTear val3 = val.AddComponent<WearNTear>();
					val3.m_broken = val;
					val3.m_new = val;
					val3.m_wet = val;
					val3.m_worn = val;
				}
				if ((Object)(object)val.GetComponent<WearNTear>() != (Object)null)
				{
					WearNTear component2 = val.GetComponent<WearNTear>();
					component2.m_supports = false;
					component2.m_noSupportWear = false;
				}
			}
			GameObject obj = val;
			PieceConfig val4 = new PieceConfig();
			val4.CraftingStation = "forge";
			val4.AllowedInDungeons = false;
			val4.Enabled = GrillOriginal.Value;
			val4.PieceTable = "_HammerPieceTable";
			val4.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig
				{
					Item = "Stone",
					Amount = 10,
					Recover = true
				},
				new RequirementConfig
				{
					Item = "Iron",
					Amount = 2,
					Recover = true
				}
			};
			CustomPiece val5 = new CustomPiece(obj, true, val4);
			Piece component3 = val.GetComponent<Piece>();
			component3.m_placeEffect = buildKitten;
			WearNTear component4 = val.GetComponent<WearNTear>();
			component4.m_hitEffect = hitStone;
			component4.m_destroyedEffect = breakStone;
			CraftingStation component5 = val.GetComponent<CraftingStation>();
			component5.m_craftItemEffects = cookingSound;
			PieceManager.Instance.AddPiece(val5);
		}

		private void LoadGriddle()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			GameObject val = GrillAssetBundle.LoadAsset<GameObject>("rk_griddle");
			PieceConfig val2 = new PieceConfig();
			val2.CraftingStation = "";
			val2.AllowedInDungeons = false;
			val2.Enabled = true;
			val2.PieceTable = "_HammerPieceTable";
			val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
			{
				new RequirementConfig
				{
					Item = "Stone",
					Amount = 10,
					Recover = true
				}
			};
			CustomPiece val3 = new CustomPiece(val, true, val2);
			Piece component = val.GetComponent<Piece>();
			component.m_placeEffect = buildStone;
			CraftingStation component2 = val.GetComponent<CraftingStation>();
			component2.m_craftItemEffects = cookingSound;
			WearNTear component3 = val.GetComponent<WearNTear>();
			component3.m_destroyedEffect = breakStone;
			component3.m_hitEffect = hitStone;
			PieceManager.Instance.AddPiece(val3);
		}

		private void Oven()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_005e: 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_006f: 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_0080: Expected O, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			GameObject val = GrillAssetBundle.LoadAsset<GameObject>("rk_oven");
			PieceConfig val2 = new PieceConfig();
			val2.CraftingStation = "";
			val2.AllowedInDungeons = false;
			val2.Enabled = true;
			val2.PieceTable = "_HammerPieceTable";
			val2.ExtendStation = "rk_grill";
			val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
			{
				new RequirementConfig
				{
					Item = "SurtlingCore",
					Amount = 2,
					Recover = true
				},
				new RequirementConfig
				{
					Item = "TrophySurtling",
					Amount = 1,
					Recover = true
				},
				new RequirementConfig
				{
					Item = "Stone",
					Amount = 10,
					Recover = true
				}
			};
			CustomPiece val3 = new CustomPiece(val, true, val2);
			Piece component = val.GetComponent<Piece>();
			component.m_placeEffect = buildStone;
			WearNTear component2 = val.GetComponent<WearNTear>();
			component2.m_supports = false;
			component2.m_noSupportWear = false;
			PieceManager.Instance.AddPiece(val3);
		}

		private void Prepstation()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			GameObject val = GrillAssetBundle.LoadAsset<GameObject>("rk_prep");
			PieceConfig val2 = new PieceConfig();
			val2.PieceTable = "_HammerPieceTable";
			val2.AllowedInDungeons = false;
			val2.CraftingStation = "forge";
			val2.Enabled = true;
			val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
			{
				new RequirementConfig
				{
					Item = "Wood",
					Amount = 4,
					Recover = true
				},
				new RequirementConfig
				{
					Item = "Tin",
					Amount = 5,
					Recover = true
				},
				new RequirementConfig
				{
					Item = "Stone",
					Amount = 3,
					Recover = true
				}
			};
			CustomPiece val3 = new CustomPiece(val, true, val2);
			Piece component = val.GetComponent<Piece>();
			component.m_placeEffect = buildKitten;
			WearNTear component2 = val.GetComponent<WearNTear>();
			component2.m_hitEffect = hitStone;
			component2.m_destroyedEffect = breakStone;
			fireVol = val.GetComponentInChildren<AudioSource>();
			PieceManager.Instance.AddPiece(val3);
		}

		private void IceCream()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			icecream_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_icecream");
			GameObject obj = icecream_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "Ice Cream";
			val.Enabled = ConesEnable.Value;
			val.Amount = 2;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "FreezeGland",
					Amount = 4
				},
				new RequirementConfig
				{
					Item = "Blueberries",
					Amount = 8
				},
				new RequirementConfig
				{
					Item = "Honey",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "rk_dragonegg",
					Amount = 1
				}
			};
			icecream = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(icecream);
		}

		private void Nut_Ella()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			nut_ellaFab = FoodAssetBundle.LoadAsset<GameObject>("rk_nut_ella");
			GameObject obj = nut_ellaFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Nut-Ella";
			val.Enabled = Nut_EllaEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig
				{
					Item = "BeechSeeds",
					Amount = 6
				},
				new RequirementConfig
				{
					Item = "rk_butter",
					Amount = 1
				}
			};
			nut_ella = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(nut_ella);
		}

		private void CarrotSticks()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			carrotstickFab = FoodAssetBundle.LoadAsset<GameObject>("rk_carrotsticks");
			GameObject obj = carrotstickFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Carrot Sticks";
			val.Enabled = CarrotSticksEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig
				{
					Item = "Carrot",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "rk_nut_ella",
					Amount = 1
				}
			};
			carrotstick = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(carrotstick);
		}

		private void BoiledEgg()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			boiledeggFab = FoodAssetBundle.LoadAsset<GameObject>("rk_boiledegg");
			GameObject obj = boiledeggFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Boiled Egg";
			val.Enabled = BoiledEggEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
			{
				new RequirementConfig
				{
					Item = "rk_egg",
					Amount = 2
				}
			};
			boiledegg = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(boiledegg);
		}

		private void Butter()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			butterFab = FoodAssetBundle.LoadAsset<GameObject>("rk_butter");
			GameObject obj = butterFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Carrot Butter";
			val.Enabled = ButterEnable.Value;
			val.Amount = 2;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
			{
				new RequirementConfig
				{
					Item = "CarrotSeeds",
					Amount = 8
				}
			};
			butter = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(butter);
		}

		private void Broth()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			brothFab = FoodAssetBundle.LoadAsset<GameObject>("rk_broth");
			GameObject obj = brothFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Bone Broth";
			val.Enabled = BrothEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig
				{
					Item = "BoneFragments",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "rk_butter",
					Amount = 1
				}
			};
			broth = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(broth);
		}

		private void FishStew()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			fishStewFab = FoodAssetBundle.LoadAsset<GameObject>("rk_fishstew");
			GameObject obj = fishStewFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Fish Stew";
			val.Enabled = FishStewEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "rk_broth",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "FishRaw",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "Thistle",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "rk_egg",
					Amount = 2
				}
			};
			fishStew = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(fishStew);
		}

		private void Burger()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			burgerFab = FoodAssetBundle.LoadAsset<GameObject>("rk_burger");
			GameObject obj = burgerFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Burger";
			val.Enabled = BurgerEnable.Value;
			val.Amount = 2;
			val.CraftingStation = "rk_grill";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "RawMeat",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "LoxMeat",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "Turnip",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "Bread",
					Amount = 1
				}
			};
			burger = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(burger);
		}

		private void BloodSausage()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			bloodsausageFab = FoodAssetBundle.LoadAsset<GameObject>("rk_bloodsausage");
			GameObject obj = bloodsausageFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Blood Sausage";
			val.Enabled = BloodSausageEnable.Value;
			val.Amount = 2;
			val.CraftingStation = "rk_grill";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "Entrails",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "Bloodbag",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "Thistle",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "rk_pork",
					Amount = 2
				}
			};
			bloodsausage = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(bloodsausage);
		}

		private void Omlette()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			omletteFab = FoodAssetBundle.LoadAsset<GameObject>("rk_omlette");
			GameObject obj = omletteFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Omlette";
			val.Enabled = OmletteEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_griddle";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "rk_egg",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "Thistle",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "rk_pork",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "rk_butter",
					Amount = 1
				}
			};
			omlette = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(omlette);
		}

		private void PorkRind()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			porkrind_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_porkrind");
			GameObject obj = porkrind_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "Pork Rinds";
			val.Enabled = PorkRindEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_griddle";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
			{
				new RequirementConfig
				{
					Item = "LeatherScraps",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "rk_pork",
					Amount = 1
				}
			};
			porkrind = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(porkrind);
		}

		private void Haggis()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			haggisFab = FoodAssetBundle.LoadAsset<GameObject>("rk_haggis");
			GameObject obj = haggisFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Haggis";
			val.Enabled = HaggisEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "RawMeat",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "Carrot",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "Entrails",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "Turnip",
					Amount = 2
				}
			};
			haggis = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(haggis);
		}

		private void CandiedTurnip()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Expected O, but got Unknown
			candiedTurnipFab = FoodAssetBundle.LoadAsset<GameObject>("rk_candiedturnip");
			GameObject obj = candiedTurnipFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Candied Turnip";
			val.Enabled = CandiedTurnipEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_grill";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
			{
				new RequirementConfig
				{
					Item = "Thistle",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "Honey",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "Turnip",
					Amount = 2
				}
			};
			candiedTurnip = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(candiedTurnip);
		}

		private void Moochi()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			moochiFab = FoodAssetBundle.LoadAsset<GameObject>("rk_moochi");
			GameObject obj = moochiFab;
			ItemConfig val = new ItemConfig();
			val.Name = "Moochi";
			val.Enabled = MoochiEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "rk_dragonegg",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "Honey",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "FreezeGland",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "Blueberries",
					Amount = 4
				}
			};
			moochi = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(moochi);
		}

		private void Kabob()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			kabob_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_kabob");
			GameObject obj = kabob_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "Kabob";
			val.Enabled = KabobEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_grill";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "Turnip",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "Carrot",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "RawMeat",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "BoneFragments",
					Amount = 2
				}
			};
			kabob = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(kabob);
		}

		private void FriedLox()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			friedlox_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_friedloxmeat");
			GameObject obj = friedlox_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "Chicken Fried Lox Meat";
			val.Enabled = FriedLoxEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_grill";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "LoxMeat",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "BarleyFlour",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "rk_egg",
					Amount = 1
				},
				new RequirementConfig
				{
					Item = "rk_butter",
					Amount = 2
				}
			};
			friedlox = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(friedlox);
		}

		private void GlazedCarrot()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Expected O, but got Unknown
			glazedcarrot_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_glazedcarrots");
			GameObject obj = glazedcarrot_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "Honey Glazed Carrots";
			val.Enabled = GlazedCarrotEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_griddle";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
			{
				new RequirementConfig
				{
					Item = "Carrot",
					Amount = 3
				},
				new RequirementConfig
				{
					Item = "Honey",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "Dandelion",
					Amount = 2
				}
			};
			glazedcarrot = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(glazedcarrot);
		}

		private void Bacon()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			bacon_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_bacon");
			GameObject obj = bacon_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "Bacon";
			val.Enabled = BaconEnable.Value;
			val.Amount = 2;
			val.CraftingStation = "rk_griddle";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
			{
				new RequirementConfig
				{
					Item = "rk_pork",
					Amount = 2
				}
			};
			bacon = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(bacon);
		}

		private void SmokedFish()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			smokedfish_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_smokedfish");
			GameObject obj = smokedfish_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "SmokedFish";
			val.Enabled = SmokedFishEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_griddle";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
			{
				new RequirementConfig
				{
					Item = "FishRaw",
					Amount = 1
				}
			};
			smokedfish = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(smokedfish);
		}

		private void Pancakes()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			pancake_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_pancake");
			GameObject obj = pancake_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "Pancakes";
			val.Enabled = PancakesEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_grill";
			val.MinStationLevel = 2;
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "Honey",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "BarleyFlour",
					Amount = 3
				},
				new RequirementConfig
				{
					Item = "rk_butter",
					Amount = 5
				},
				new RequirementConfig
				{
					Item = "rk_egg",
					Amount = 2
				}
			};
			pancake = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(pancake);
		}

		private void Pizza()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			pizza_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_pizza");
			GameObject obj = pizza_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "Pizza";
			val.Enabled = PizzaEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_grill";
			val.MinStationLevel = 2;
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4]
			{
				new RequirementConfig
				{
					Item = "Mushroom",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "BarleyFlour",
					Amount = 3
				},
				new RequirementConfig
				{
					Item = "rk_egg",
					Amount = 2
				},
				new RequirementConfig
				{
					Item = "RawMeat",
					Amount = 2
				}
			};
			pizza = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(pizza);
		}

		private void Coffee()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			coffee_prefab = FoodAssetBundle.LoadAsset<GameObject>("rk_coffee");
			GameObject obj = coffee_prefab;
			ItemConfig val = new ItemConfig();
			val.Name = "Coffee";
			val.Enabled = CoffeeEnable.Value;
			val.Amount = 1;
			val.CraftingStation = "rk_prep";
			val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1]
			{
				new RequirementConfig
				{
					Item = "AncientSeed",
					Amount = 2
				}
			};
			coffee = new CustomItem(obj, false, val);
			ItemManager.Instance.AddItem(coffee);
		}

		private void Latte()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expe

BepInEx/plugins/Smoothbrain-Blacksmithing/Blacksmithing.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using ItemDataManager;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Guid("87603D00-4EC7-40EC-832D-8028E3D19F46")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("Blacksmithing")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/Blacksmithing")]
[assembly: AssemblyTitle("Blacksmithing")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<bda35906-bc26-472d-bd72-d9267117b2c0>Embedded]
	internal sealed class <bda35906-bc26-472d-bd72-d9267117b2c0>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<bda35906-bc26-472d-bd72-d9267117b2c0>Embedded]
	[CompilerGenerated]
	internal sealed class <8ce841e8-c139-4e07-b6b9-7369a341776f>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <8ce841e8-c139-4e07-b6b9-7369a341776f>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <8ce841e8-c139-4e07-b6b9-7369a341776f>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<bda35906-bc26-472d-bd72-d9267117b2c0>Embedded]
	internal sealed class <17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Blacksmithing
{
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	[BepInPlugin("org.bepinex.plugins.blacksmithing", "Blacksmithing", "1.2.4")]
	[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(1)]
	[<8ce841e8-c139-4e07-b6b9-7369a341776f>Nullable(0)]
	public class Blacksmithing : BaseUnityPlugin
	{
		[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)]
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? ShowRangeAsPercent;
		}

		[HarmonyPatch]
		[<8ce841e8-c139-4e07-b6b9-7369a341776f>Nullable(0)]
		private static class AllowRepairingFromInventory
		{
			private static IEnumerable<MethodInfo> TargetMethods()
			{
				return new MethodInfo[4]
				{
					AccessTools.DeclaredMethod(typeof(InventoryGui), "UpdateRepair", (Type[])null, (Type[])null),
					AccessTools.DeclaredMethod(typeof(InventoryGui), "CanRepair", (Type[])null, (Type[])null),
					AccessTools.DeclaredMethod(typeof(InventoryGui), "HaveRepairableItems", (Type[])null, (Type[])null),
					AccessTools.DeclaredMethod(typeof(InventoryGui), "RepairOneItem", (Type[])null, (Type[])null)
				};
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				MethodInfo cheatCheck = AccessTools.DeclaredMethod(typeof(Player), "NoCostCheat", (Type[])null, (Type[])null);
				foreach (CodeInstruction instruction in instructions)
				{
					yield return instruction;
					if (CodeInstructionExtensions.Calls(instruction, cheatCheck))
					{
						yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(Blacksmithing), "CanRepairFromEverywhere", (Type[])null, (Type[])null));
						yield return new CodeInstruction(OpCodes.Or, (object)null);
					}
				}
			}
		}

		[<8ce841e8-c139-4e07-b6b9-7369a341776f>Nullable(0)]
		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		public class CheckCrafting
		{
			[UsedImplicitly]
			public static void Prefix(InventoryGui __instance, out bool __state)
			{
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				__state = __instance.m_craftRecipe?.m_item.m_itemData.Data()["Blacksmithing"] == null;
				if (__instance.m_craftRecipe != null && CheckBlacksmithingItem(__instance.m_craftRecipe.m_item.m_itemData.m_shared))
				{
					__instance.m_craftRecipe.m_item.m_itemData.Data()["Blacksmithing"] = Math.Max(Mathf.RoundToInt(((Character)Player.m_localPlayer).GetSkillFactor(Skill.fromName("Blacksmithing")) * 100f), int.Parse(__instance.m_craftRecipe.m_item.m_itemData.Data()["Blacksmithing"] ?? "0")).ToString();
				}
				SaveCraftingItemPlayer.item = __instance.m_craftRecipe?.m_item.m_itemData;
			}

			[UsedImplicitly]
			public static void Finalizer(InventoryGui __instance, bool __state)
			{
				if (__state)
				{
					__instance.m_craftRecipe?.m_item.m_itemData.Data().Remove("Blacksmithing");
				}
				SaveCraftingItemPlayer.item = null;
			}
		}

		[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)]
		[HarmonyPatch(typeof(FejdStartup), "Awake")]
		public class IncreaseCraftingSkill
		{
			private static bool hasRun;

			[UsedImplicitly]
			public static void Postfix()
			{
				if (!hasRun)
				{
					ApplyTranspilerToAll(new List<MethodInfo> { AccessTools.DeclaredMethod(typeof(InventoryGui), "DoCrafting", (Type[])null, (Type[])null) }, AccessTools.DeclaredMethod(typeof(IncreaseCraftingSkill), "Transpiler", (Type[])null, (Type[])null));
					hasRun = true;
				}
			}

			[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(1)]
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				MethodInfo statIncrement = AccessTools.DeclaredMethod(typeof(PlayerProfile), "IncrementStat", (Type[])null, (Type[])null);
				bool first = true;
				foreach (CodeInstruction instruction in instructions)
				{
					yield return instruction;
					if (first && CodeInstructionExtensions.Calls(instruction, statIncrement))
					{
						first = false;
						yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(IncreaseCraftingSkill), "CheckBlacksmithingIncrease", (Type[])null, (Type[])null));
					}
				}
			}

			private static void CheckBlacksmithingIncrease()
			{
				if (CheckBlacksmithingItem(InventoryGui.instance.m_craftRecipe.m_item.m_itemData.m_shared))
				{
					((Character)(object)Player.m_localPlayer).RaiseSkill("Blacksmithing", 10f);
				}
			}
		}

		[HarmonyPatch(typeof(ItemData), "GetTooltip", new Type[]
		{
			typeof(ItemData),
			typeof(int),
			typeof(bool),
			typeof(float)
		})]
		[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)]
		public class UpdateDurabilityDisplay
		{
			[UsedImplicitly]
			public static void Prefix(bool crafting)
			{
				ApplySkillToDurability.skipDurabilityDisplay = crafting;
			}

			[UsedImplicitly]
			[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(1)]
			public static void Postfix(ItemData item, bool crafting, ref string __result, int qualityLevel)
			{
				if (crafting && item.m_shared.m_useDurability)
				{
					float skillFactor = ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing");
					if (skillFactor > 0f)
					{
						__result = new Regex("(\\$item_durability.*)").Replace(__result, $"$1 (<color=orange>+{Mathf.Round(skillFactor * item.GetMaxDurability(qualityLevel) * (durabilityFactor.Value - 1f))}</color>)");
					}
				}
			}

			[UsedImplicitly]
			public static void Finalizer()
			{
				ApplySkillToDurability.skipDurabilityDisplay = false;
			}
		}

		[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)]
		[HarmonyPatch(typeof(ItemData), "GetMaxDurability", new Type[] { typeof(int) })]
		public class ApplySkillToDurability
		{
			public static bool skipDurabilityDisplay;

			[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(1)]
			private static void Postfix(ItemData __instance, ref float __result)
			{
				if (!skipDurabilityDisplay)
				{
					string text = __instance.Data()["Blacksmithing"];
					if (text != null)
					{
						__result *= 1f + (float)int.Parse(text) * blacksmithing.SkillEffectFactor / 100f * (durabilityFactor.Value - 1f);
					}
				}
			}
		}

		[<8ce841e8-c139-4e07-b6b9-7369a341776f>Nullable(0)]
		[HarmonyPatch(typeof(FejdStartup), "Awake")]
		public class IncreaseMaximumUpgradeLevel
		{
			private static bool hasRun = false;

			private static readonly FieldInfo maxQualityField = AccessTools.DeclaredField(typeof(SharedData), "m_maxQuality");

			[UsedImplicitly]
			public static void Postfix()
			{
				if (!hasRun)
				{
					ApplyTranspilerToAll(new List<MethodInfo>
					{
						AccessTools.DeclaredMethod(typeof(InventoryGui), "UpdateRecipeList", (Type[])null, (Type[])null),
						AccessTools.DeclaredMethod(typeof(InventoryGui), "AddRecipeToList", (Type[])null, (Type[])null),
						AccessTools.DeclaredMethod(typeof(InventoryGui), "UpdateRecipe", (Type[])null, (Type[])null),
						AccessTools.DeclaredMethod(typeof(InventoryGui), "DoCrafting", (Type[])null, (Type[])null),
						AccessTools.DeclaredMethod(typeof(InventoryGui), "SetupUpgradeItem", (Type[])null, (Type[])null)
					}, AccessTools.DeclaredMethod(typeof(IncreaseMaximumUpgradeLevel), "Transpiler", (Type[])null, (Type[])null));
					hasRun = true;
				}
			}

			private static int MaxQualityIncrease(SharedData sharedData, int currentQuality)
			{
				return currentQuality + ((upgradeLevelRequirement.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)upgradeLevelRequirement.Value && CheckBlacksmithingItem(sharedData)) ? 1 : 0);
			}

			[UsedImplicitly]
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				foreach (CodeInstruction instruction in instructions)
				{
					if (instruction.opcode == OpCodes.Ldfld && CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)maxQualityField))
					{
						yield return new CodeInstruction(OpCodes.Dup, (object)null);
						yield return instruction;
						yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(IncreaseMaximumUpgradeLevel), "MaxQualityIncrease", (Type[])null, (Type[])null));
					}
					else
					{
						yield return instruction;
					}
				}
			}
		}

		[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)]
		[HarmonyPatch(typeof(Requirement), "GetAmount", new Type[] { typeof(int) })]
		private class IncreaseResourcesRequired
		{
			private static void Postfix(ref int __result, int qualityLevel)
			{
				if (SaveCraftingItemPlayer.item != null && qualityLevel > SaveCraftingItemPlayer.item.m_shared.m_maxQuality)
				{
					__result = Mathf.FloorToInt((float)__result * additionalUpgradePriceFactor.Value);
				}
			}
		}

		[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(2)]
		[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
		{
			typeof(Recipe),
			typeof(bool),
			typeof(int)
		})]
		[<8ce841e8-c139-4e07-b6b9-7369a341776f>Nullable(0)]
		private class SaveCraftingItemPlayer
		{
			public static ItemData item;

			[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(1)]
			private static void Prefix(Recipe recipe, [<8ce841e8-c139-4e07-b6b9-7369a341776f>Nullable(2)] out ItemData __state)
			{
				__state = item;
				item = recipe.m_item.m_itemData;
			}

			private static void Finalizer(ItemData __state)
			{
				item = __state;
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
		[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)]
		private class SaveCraftingItemInventoryGui
		{
			private static void Prefix()
			{
				SaveCraftingItemPlayer.item = InventoryGui.instance.m_selectedRecipe.Value;
			}

			private static void Finalizer()
			{
				SaveCraftingItemPlayer.item = null;
			}
		}

		[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)]
		[HarmonyPatch(typeof(CraftingStation), "GetLevel")]
		private class IncreaseCraftingStationLevel
		{
			[<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(1)]
			private static void Postfix(CraftingStation __instance, ref int __result)
			{
				switch (__instance.m_name)
				{
				case "$piece_workbench":
					if (workbenchFirstLevelIncrease.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)workbenchFirstLevelIncrease.Value)
					{
						__result++;
					}
					if (workbenchSecondLevelIncrease.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)workbenchSecondLevelIncrease.Value)
					{
						__result++;
					}
					break;
				case "$piece_forge":
					if (forgeFirstLevelIncrease.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)forgeFirstLevelIncrease.Value)
					{
						__result++;
					}
					if (forgeSecondLevelIncrease.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)forgeSecondLevelIncrease.Value)
					{
						__result++;
					}
					break;
				case "$piece_blackforge":
					if (blackForgeFirstLevelIncrease.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)blackForgeFirstLevelIncrease.Value)
					{
						__result++;
					}
					if (blackForgeSecondLevelIncrease.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)blackForgeSecondLevelIncrease.Value)
					{
						__result++;
					}
					break;
				case "$piece_magetable":
					if (galdrTableFirstLevelIncrease.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)galdrTableFirstLevelIncrease.Value)
					{
						__result++;
					}
					if (galdrTableSecondLevelIncrease.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)galdrTableSecondLevelIncrease.Value)
					{
						__result++;
					}
					break;
				}
			}
		}

		private const string ModName = "Blacksmithing";

		private const string ModVersion = "1.2.4";

		private const string ModGUID = "org.bepinex.plugins.blacksmithing";

		private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.blacksmithing")
		{
			DisplayName = "Blacksmithing",
			CurrentVersion = "1.2.4",
			MinimumRequiredVersion = "1.2.4"
		};

		private static ConfigEntry<Toggle> serverConfigLocked = null;

		private static ConfigEntry<int> workbenchFirstLevelIncrease = null;

		private static ConfigEntry<int> workbenchSecondLevelIncrease = null;

		private static ConfigEntry<int> forgeFirstLevelIncrease = null;

		private static ConfigEntry<int> forgeSecondLevelIncrease = null;

		private static ConfigEntry<int> blackForgeFirstLevelIncrease = null;

		private static ConfigEntry<int> blackForgeSecondLevelIncrease = null;

		private static ConfigEntry<int> galdrTableFirstLevelIncrease = null;

		private static ConfigEntry<int> galdrTableSecondLevelIncrease = null;

		private static ConfigEntry<int> repairLevelRequirement = null;

		private static ConfigEntry<int> upgradeLevelRequirement = null;

		private static ConfigEntry<float> durabilityFactor = null;

		private static ConfigEntry<float> additionalUpgradePriceFactor = null;

		private static ConfigEntry<float> experienceGainedFactor = null;

		private static ConfigEntry<int> experienceLoss = null;

		private static Skill blacksmithing = null;

		private static readonly Harmony harmony = new Harmony("org.bepinex.plugins.blacksmithing");

		private ConfigEntry<T> config<[<8ce841e8-c139-4e07-b6b9-7369a341776f>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			configSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<8ce841e8-c139-4e07-b6b9-7369a341776f>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Expected O, but got Unknown
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Expected O, but got Unknown
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Expected O, but got Unknown
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Expected O, but got Unknown
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Expected O, but got Unknown
			//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Expected O, but got Unknown
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Expected O, but got Unknown
			//IL_0394: Unknown result type (might be due to invalid IL or missing references)
			//IL_039f: Expected O, but got Unknown
			//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f3: Expected O, but got Unknown
			//IL_043a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0445: Expected O, but got Unknown
			//IL_048c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0497: Expected O, but got Unknown
			//IL_04de: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e9: Expected O, but got Unknown
			//IL_0562: Unknown result type (might be due to invalid IL or missing references)
			//IL_056d: Expected O, but got Unknown
			blacksmithing = new Skill("Blacksmithing", "blacksmithing.png");
			blacksmithing.Description.English("Increases the durability of created armor and weapons.");
			blacksmithing.Name.German("Schmiedekunst");
			blacksmithing.Description.German("Erhöht die Haltbarkeit hergestellter Rüstung und Waffen.");
			blacksmithing.Configurable = false;
			int num = 0;
			serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, new ConfigDescription("If on, the configuration is locked and can be changed by server admins only.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = (num -= 1)
				}
			}));
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			workbenchFirstLevelIncrease = config("2 - Crafting", "Skill Level for first Workbench Upgrade", 10, new ConfigDescription("Minimum skill level to count as one crafting station upgrade for the workbench. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			workbenchSecondLevelIncrease = config("2 - Crafting", "Skill Level for second Workbench Upgrade", 20, new ConfigDescription("Minimum skill level to count as two crafting station upgrades for the workbench. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			forgeFirstLevelIncrease = config("2 - Crafting", "Skill Level for first Forge Upgrade", 30, new ConfigDescription("Minimum skill level to count as one crafting station upgrade for the forge. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			forgeSecondLevelIncrease = config("2 - Crafting", "Skill Level for second Forge Upgrade", 40, new ConfigDescription("Minimum skill level to count as two crafting station upgrades for the forge. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			blackForgeFirstLevelIncrease = config("2 - Crafting", "Skill Level for first Black Forge Upgrade", 50, new ConfigDescription("Minimum skill level to count as one crafting station upgrade for the black forge. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			blackForgeSecondLevelIncrease = config("2 - Crafting", "Skill Level for second Black Forge Upgrade", 60, new ConfigDescription("Minimum skill level to count as two crafting station upgrades for the black forge. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			galdrTableFirstLevelIncrease = config("2 - Crafting", "Skill Level for first Galdr Table Upgrade", 50, new ConfigDescription("Minimum skill level to count as one crafting station upgrade for the galdr table. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			galdrTableSecondLevelIncrease = config("2 - Crafting", "Skill Level for second Galdr Table Upgrade", 60, new ConfigDescription("Minimum skill level to count as two crafting station upgrades for the galdr table. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			repairLevelRequirement = config("2 - Crafting", "Skill Level for Inventory Repair", 70, new ConfigDescription("Minimum skill level to be able to repair items from the inventory. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			upgradeLevelRequirement = config("2 - Crafting", "Skill Level for Extra Upgrade Level", 80, new ConfigDescription("Minimum skill level for an additional upgrade level for armor and weapons. 0 means disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false,
					Order = (num -= 1)
				}
			}));
			durabilityFactor = config("2 - Crafting", "Durability Factor", 2f, new ConfigDescription("Factor for durability of armor and weapons at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = (num -= 1)
				}
			}));
			additionalUpgradePriceFactor = config("2 - Crafting", "Price Factor", 3f, new ConfigDescription("Factor for the price of the additional upgrade.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = (num -= 1)
				}
			}));
			experienceGainedFactor = config("3 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the blacksmithing skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = (num -= 1)
				}
			}));
			experienceGainedFactor.SettingChanged += [<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)] (object _, EventArgs _) =>
			{
				blacksmithing.SkillGainFactor = experienceGainedFactor.Value;
			};
			blacksmithing.SkillGainFactor = experienceGainedFactor.Value;
			experienceLoss = config("3 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the blacksmithing skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = (num -= 1)
				}
			}));
			experienceLoss.SettingChanged += [<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)] (object _, EventArgs _) =>
			{
				blacksmithing.SkillLoss = experienceLoss.Value;
			};
			blacksmithing.SkillLoss = experienceLoss.Value;
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			harmony.PatchAll(executingAssembly);
		}

		private static bool CanRepairFromEverywhere()
		{
			if (repairLevelRequirement.Value > 0)
			{
				return ((Character)(object)Player.m_localPlayer).GetSkillFactor("Blacksmithing") * 100f >= (float)repairLevelRequirement.Value;
			}
			return false;
		}

		private static void ApplyTranspilerToAll(List<MethodInfo> methods, MethodInfo transpiler)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			MethodInfo[] array = methods.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				Patches patchInfo = Harmony.GetPatchInfo((MethodBase)array[i]);
				if (patchInfo != null)
				{
					ApplyPatch(patchInfo.Prefixes);
					ApplyPatch(patchInfo.Postfixes);
					ApplyPatch(patchInfo.Finalizers);
				}
			}
			HarmonyMethod val = new HarmonyMethod(transpiler);
			foreach (MethodInfo method in methods)
			{
				harmony.Patch((MethodBase)method, (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			void ApplyPatch(ReadOnlyCollection<Patch> patches)
			{
				methods.AddRange(patches.Select([<17c65fa6-ea81-40bd-a96d-e412ebff2772>NullableContext(0)] (Patch p) => p.PatchMethod));
			}
		}

		private static bool CheckBlacksmithingItem(SharedData item)
		{
			//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: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected I4, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Invalid comparison between Unknown and I4
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Invalid comparison between Unknown and I4
			ItemType itemType = item.m_itemType;
			bool flag;
			switch (itemType - 4)
			{
			default:
				if ((int)itemType == 22)
				{
					goto case 0;
				}
				goto case 4;
			case 0:
			case 1:
			case 2:
			case 3:
			case 7:
			case 8:
			case 10:
			case 13:
				flag = true;
				break;
			case 4:
			case 5:
			case 6:
			case 9:
			case 11:
			case 12:
				flag = false;
				break;
			}
			if (!flag)
			{
				if ((int)item.m_itemType == 3)
				{
					return !item.m_attack.m_consumeItem;
				}
				return false;
			}
			return true;
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[<9e5a7f52-78ce-43f9-a1f9-41fc6c6c5fe7>Embedded]
	[CompilerGenerated]
	internal sealed class <9e5a7f52-78ce-43f9-a1f9-41fc6c6c5fe7>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<9e5a7f52-78ce-43f9-a1f9-41fc6c6c5fe7>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <15a095cb-bc88-488f-a6f1-050fd76f3e43>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <15a095cb-bc88-488f-a6f1-050fd76f3e43>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <15a095cb-bc88-488f-a6f1-050fd76f3e43>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<9e5a7f52-78ce-43f9-a1f9-41fc6c6c5fe7>Embedded]
	internal sealed class <debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[<9e5a7f52-78ce-43f9-a1f9-41fc6c6c5fe7>Embedded]
	[CompilerGenerated]
	internal sealed class <43d2c077-bf15-4a26-9d81-ab109138f392>RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public <43d2c077-bf15-4a26-9d81-ab109138f392>RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
	[PublicAPI]
	[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
	internal abstract class OwnConfigEntryBase
	{
		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		public object LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
	[PublicAPI]
	[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
	internal class SyncedConfigEntry<[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)] T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(2)]
	[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
	internal abstract class CustomSyncedValueBase
	{
		public object LocalBaseValue;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(1)]
		public readonly string Identifier;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(1)]
		public readonly Type Type;

		private object boxedValue;

		protected bool localIsOwner;

		public object BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action ValueChanged;

		[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
	[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
	internal sealed class CustomSyncedValue<[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)] T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
	[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
	[PublicAPI]
	internal class ConfigSync
	{
		[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)]
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
			public static ZRpc currentRpc;

			[HarmonyPrefix]
			[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)]
		private static class RegisterClientRPCPatch
		{
			[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)]
		private class ParsedConfigs
		{
			[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>();

			[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix([<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
			public object value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)]
		private static class PreventSavingServerInfo
		{
			[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)]
		private static class PreventConfigRereadChangingValues
		{
			[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		public string DisplayName;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		public string CurrentVersion;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		public string MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		private OwnConfigEntryBase lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 1, 0, 1 })]
		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		[method: <debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(2)]
		[field: <15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		public event Action<bool> SourceOfTruthChanged;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		[method: <debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(2)]
		[field: <15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		private event Action lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)] T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += [<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)] T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += [<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (object _, EventArgs _) =>
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(([<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 0, 1 })] KeyValuePair<long, string> kv) =>
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out var value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		[return: <15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		private static OwnConfigEntryBase configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		[return: <15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 2, 1 })]
		public static SyncedConfigEntry<T> ConfigData<[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)] T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)] T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage([<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 2, 1 })] IEnumerable<ConfigEntryBase> configs = null, [<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 2, 1 })] IEnumerable<CustomSyncedValueBase> customValues = null, [<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 2, 1 })] IEnumerable<PackageEntry> packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, [<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)] object value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[PublicAPI]
	[HarmonyPatch]
	[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(0)]
	[<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(1)]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		private string displayName;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		private string currentVersion;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		private string minimumRequiredVersion;

		public bool ModRequired = true;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		private string ReceivedCurrentVersion;

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		private string ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		[<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)]
		private ConfigSync ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error([<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(2)] ZRpc rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, [<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(new byte[] { 2, 1, 1 })] Action<ZRpc, ZPackage> original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (ZRpc rpc, [<15a095cb-bc88-488f-a6f1-050fd76f3e43>Nullable(1)] ZPackage pkg) =>
				{
					CheckVersion(rpc, pkg, action);
				}));
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy([<debff4c8-e36c-4ef8-b210-82f2f6ece337>NullableContext(0)] (KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<6c5c060f-ffc1-4ed6-be74-bfbd2e392c93>Embedded]
	internal sealed class <6c5c060f-ffc1-4ed6-be74-bfbd2e392c93>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<6c5c060f-ffc1-4ed6-be74-bfbd2e392c93>Embedded]
	internal sealed class <7cc9af3a-59c9-4c56-b738-f03dd5dc807e>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <7cc9af3a-59c9-4c56-b738-f03dd5dc807e>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <7cc9af3a-59c9-4c56-b738-f03dd5dc807e>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<6c5c060f-ffc1-4ed6-be74-bfbd2e392c93>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace SkillManager
{
	[<4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContext(1)]
	[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(0)]
	[PublicAPI]
	internal class Skill
	{
		[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(0)]
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				string key = localizations.FirstOrDefault([<4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance);
				}
			}

			public static Localization ForLanguage([<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)] string language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[PublicAPI]
		[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(0)]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", key);
			}

			public LocalizeKey Portuguese_Brazilian(string key)
			{
				return addForLang("Portuguese_Brazilian", key);
			}

			public LocalizeKey Chinese(string key)
			{
				return addForLang("Chinese", key);
			}

			public LocalizeKey Japanese(string key)
			{
				return addForLang("Japanese", key);
			}

			public LocalizeKey Korean(string key)
			{
				return addForLang("Korean", key);
			}

			public LocalizeKey Hindi(string key)
			{
				return addForLang("Hindi", key);
			}

			public LocalizeKey Thai(string key)
			{
				return addForLang("Thai", key);
			}

			public LocalizeKey Abenaki(string key)
			{
				return addForLang("Abenaki", key);
			}

			public LocalizeKey Croatian(string key)
			{
				return addForLang("Croatian", key);
			}

			public LocalizeKey Georgian(string key)
			{
				return addForLang("Georgian", key);
			}

			public LocalizeKey Greek(string key)
			{
				return addForLang("Greek", key);
			}

			public LocalizeKey Serbian(string key)
			{
				return addForLang("Serbian", key);
			}

			public LocalizeKey Ukrainian(string key)
			{
				return addForLang("Ukrainian", key);
			}

			private LocalizeKey addForLang(string lang, string value)
			{
				Localizations[lang] = value;
				if (Localization.instance.GetSelectedLanguage() == lang)
				{
					Localization.instance.AddWord(Key, value);
				}
				else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
				{
					Localization.instance.AddWord(Key, value);
				}
				return this;
			}

			[HarmonyPriority(300)]
			internal static void AddLocalizedKeys(Localization __instance, string language)
			{
				foreach (LocalizeKey key in keys)
				{
					string value2;
					if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value))
					{
						__instance.AddWord(key.Key, value);
					}
					else if (key.Localizations.TryGetValue("alias", out value2))
					{
						Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
					}
				}
			}
		}

		[<4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
			public string Category;
		}

		[<4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContext(0)]
		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		private static class Patch_Skills_IsSkillValid
		{
			private static void Postfix(SkillType type, ref bool __result)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (!__result && skills.ContainsKey(type))
				{
					__result = true;
				}
			}
		}

		private static readonly Dictionary<SkillType, Skill> skills;

		internal static readonly Dictionary<string, Skill> skillByName;

		private readonly string skillName;

		private readonly string internalSkillName;

		private readonly SkillDef skillDef;

		public readonly LocalizeKey Name;

		public readonly LocalizeKey Description;

		private float skillEffectFactor = 1f;

		private int skillLoss = 5;

		public bool Configurable;

		private static bool InitializedTerminal;

		[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		private static Localization _english;

		[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static bool hasConfigSync;

		[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		private static object _configSync;

		public float SkillGainFactor
		{
			get
			{
				return skillDef.m_increseStep;
			}
			set
			{
				skillDef.m_increseStep = value;
				this.SkillGainFactorChanged?.Invoke(value);
			}
		}

		public float SkillEffectFactor
		{
			get
			{
				return skillEffectFactor;
			}
			set
			{
				skillEffectFactor = value;
				this.SkillEffectFactorChanged?.Invoke(value);
			}
		}

		public int SkillLoss
		{
			get
			{
				return skillLoss;
			}
			set
			{
				skillLoss = value;
				this.SkillLossChanged?.Invoke(value);
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				object obj = _plugin;
				if (obj == null)
				{
					BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First([<4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
					_plugin = val;
					obj = (object)val;
				}
				return (BaseUnityPlugin)obj;
			}
		}

		[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		private static object configSync
		{
			[<4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContext(2)]
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		[method: <4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContext(2)]
		[field: <7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		public event Action<float> SkillGainFactorChanged;

		[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		[method: <4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContext(2)]
		[field: <7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		public event Action<float> SkillEffectFactorChanged;

		[<7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		[method: <4fbbcdd8-44f5-42ee-8482-7c8a04287e9b>NullableContext(2)]
		[field: <7cc9af3a-59c9-4c56-b738-f03dd5dc807e>Nullable(2)]
		public event Action<float> SkillLossChanged;

		public Skill(string englishName, string icon)
			: this(englishName, loadSprite(icon, 64, 64))
		{
		}

		public Skill(string englishName, Sprite icon)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			SkillType val = fromName(englishName);
			string text = new Regex("[^a-zA-Z]").Replace(englishName, "_");
			skills[val] = this;
			skillByName[englishName] = this;
			skillDef = new SkillDef
			{
				m_description = "$skilldesc_" + text,
				m_icon = icon,
				m_increseStep = 1f,
				m_skill = val
			};
			internalSkillName = text;
			skillName = englishName;
			Name = new LocalizeKey("skill_" + ((object)(SkillType)(ref val)).ToString()).English(englishName);
			Description = new LocalizeKey("skilldesc_" + text);
		}

		public static SkillType fromName(string englishName)
		{
			return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName));
		}

		static Skill()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			skills = new Dictionary<SkillType, Skill>();
			skillByName = new Dictionary<string, Skill>();
			InitializedTerminal = false;
			hasConfigSync = true;
			Harmony val = new Harmony("org.bepinex.helpers.skillmanager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null);
		}

		private static void Patch_FejdStartup()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			foreach (Skill skill in skills.Values)
			{
				if (skill.Configurable)
				{
					string key = skill.Name.Key;
					string group = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim();
					string category = Localiza

BepInEx/plugins/Smoothbrain-Building/Building.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: Guid("9BF5432D-9518-4D36-A6C2-A8C62D36B921")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyProduct("Building")]
[assembly: AssemblyCompany("")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/Building")]
[assembly: AssemblyTitle("Building")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<680b7d75-0b47-4f39-bc2c-2a712fa958fc>Embedded]
	internal sealed class <680b7d75-0b47-4f39-bc2c-2a712fa958fc>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<680b7d75-0b47-4f39-bc2c-2a712fa958fc>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <cfdf0136-75e9-4db0-8de8-ad8627f7c15b>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <cfdf0136-75e9-4db0-8de8-ad8627f7c15b>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <cfdf0136-75e9-4db0-8de8-ad8627f7c15b>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<680b7d75-0b47-4f39-bc2c-2a712fa958fc>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Building
{
	[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(1)]
	[<cfdf0136-75e9-4db0-8de8-ad8627f7c15b>Nullable(0)]
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	[BepInPlugin("org.bepinex.plugins.building", "Building", "1.2.4")]
	public class Building : BaseUnityPlugin
	{
		[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)]
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public bool? ShowRangeAsPercent;
		}

		[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "UpdatePlacement")]
		private static class ChangeStaminaUsage
		{
			private static float stamina;

			[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(1)]
			private static void Prefix(Player __instance, [<cfdf0136-75e9-4db0-8de8-ad8627f7c15b>Nullable(2)] out ItemData __state)
			{
				__state = ((Humanoid)__instance).GetRightItem();
				if (__state?.m_shared.m_name == "$item_hammer")
				{
					stamina = __state.m_shared.m_attack.m_attackStamina;
					Attack attack = __state.m_shared.m_attack;
					attack.m_attackStamina *= Mathf.Max(0f, 1f - ((Character)(object)__instance).GetSkillFactor("Building") * (float)staminaReductionPerLevel.Value);
				}
			}

			[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(2)]
			private static void Finalizer(ItemData __state)
			{
				if (__state?.m_shared.m_name == "$item_hammer")
				{
					__state.m_shared.m_attack.m_attackStamina = stamina;
				}
			}
		}

		[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)]
		[HarmonyPatch(typeof(WearNTear), "OnPlaced")]
		public class AddZDO
		{
			public static bool forFree;

			[UsedImplicitly]
			[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(1)]
			private static void Postfix(WearNTear __instance)
			{
				((Component)__instance).GetComponent<ZNetView>().GetZDO().Set("BuildingSkill Level", ((Character)(object)Player.m_localPlayer).GetSkillFactor("Building"));
				__instance.m_health *= 1f + ((Component)__instance).GetComponent<ZNetView>().GetZDO().GetFloat("BuildingSkill Level", 0f) * (healthFactor.Value - 1f);
				if (freeBuildLevelRequirement.Value > 0)
				{
					forFree = Random.Range((float)freeBuildLevelRequirement.Value / 100f, 5.5f) <= ((Character)(object)Player.m_localPlayer).GetSkillFactor("Building");
				}
				((Component)__instance).GetComponent<ZNetView>().GetZDO().Set("BuildingSkill FreeBuild", forFree);
				((Character)(object)Player.m_localPlayer).RaiseSkill("Building");
			}
		}

		[HarmonyPatch(typeof(WearNTear), "Awake")]
		[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)]
		private class IncreaseHealth
		{
			[UsedImplicitly]
			[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(1)]
			private static void Prefix(WearNTear __instance)
			{
				float health = __instance.m_health;
				float num = 1f;
				ZDO zDO = ((Component)__instance).GetComponent<ZNetView>().GetZDO();
				__instance.m_health = health * ((num + ((zDO != null) ? new float?(zDO.GetFloat("BuildingSkill Level", 0f)) : null) * (healthFactor.Value - 1f)) ?? 1f);
			}
		}

		[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)]
		[HarmonyPatch(typeof(WearNTear), "GetMaterialProperties")]
		private class BuildHigher
		{
			[UsedImplicitly]
			[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(1)]
			private static void Postfix(WearNTear __instance, ref float maxSupport, ref float minSupport, ref float horizontalLoss, ref float verticalLoss)
			{
				ZNetView nview = __instance.m_nview;
				float? obj;
				if (nview == null)
				{
					obj = null;
				}
				else
				{
					ZDO zDO = nview.GetZDO();
					obj = ((zDO != null) ? new float?(zDO.GetFloat("BuildingSkill Level", 0f)) : null);
				}
				float num = obj ?? ((Character)(object)Player.m_localPlayer)?.GetSkillFactor("Building") ?? 0f;
				maxSupport *= 1f + num * (maximumSupportFactor.Value - 1f);
				horizontalLoss *= 1f - num * (1f - supportLossFactor.Value);
				verticalLoss *= 1f - num * (1f - supportLossFactor.Value);
			}
		}

		[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "UpdatePlacement")]
		private class ResetFlag
		{
			private static void Finalizer()
			{
				AddZDO.forFree = false;
			}
		}

		[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "ConsumeResources")]
		private class BuildingIsFree
		{
			private class SkipConsumeResourcesException : Exception
			{
			}

			[HarmonyPriority(800)]
			private static void Prefix()
			{
				if (AddZDO.forFree)
				{
					throw new SkipConsumeResourcesException();
				}
			}

			[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(1)]
			[return: <cfdf0136-75e9-4db0-8de8-ad8627f7c15b>Nullable(2)]
			private static Exception Finalizer(Exception __exception)
			{
				return (__exception is SkipConsumeResourcesException) ? null : __exception;
			}
		}

		[HarmonyPatch(typeof(Piece), "DropResources")]
		[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)]
		private class RecoverResources
		{
			[<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(1)]
			private static bool Prefix(Piece __instance)
			{
				return !((Component)__instance).GetComponent<ZNetView>().GetZDO().GetBool("BuildingSkill FreeBuild", false);
			}
		}

		[<cfdf0136-75e9-4db0-8de8-ad8627f7c15b>Nullable(0)]
		[HarmonyPatch(typeof(Player), "UpdatePlacement")]
		private static class ReduceHammerDurabilityLoss
		{
			private static bool reduced;

			private static void Prefix(Player __instance)
			{
				reduced = false;
				if (durabilityUsageLevelRequirement.Value > 0 && (float)durabilityUsageLevelRequirement.Value <= ((Character)(object)__instance).GetSkillFactor("Building") * 100f)
				{
					ItemData rightItem = ((Humanoid)__instance).GetRightItem();
					if (rightItem != null)
					{
						SharedData shared = rightItem.m_shared;
						shared.m_useDurabilityDrain *= 0.7f;
						reduced = true;
					}
				}
			}

			private static void Finalizer(Player __instance)
			{
				ItemData rightItem = ((Humanoid)__instance).GetRightItem();
				if (rightItem != null && reduced)
				{
					SharedData shared = rightItem.m_shared;
					shared.m_useDurabilityDrain /= 0.7f;
				}
			}
		}

		private const string ModName = "Building";

		private const string ModVersion = "1.2.4";

		private const string ModGUID = "org.bepinex.plugins.building";

		private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.building")
		{
			DisplayName = "Building",
			CurrentVersion = "1.2.4",
			MinimumRequiredVersion = "1.2.4"
		};

		private static ConfigEntry<Toggle> serverConfigLocked = null;

		private static ConfigEntry<float> maximumSupportFactor = null;

		private static ConfigEntry<float> supportLossFactor = null;

		private static ConfigEntry<float> healthFactor = null;

		private static ConfigEntry<int> freeBuildLevelRequirement = null;

		private static ConfigEntry<int> durabilityUsageLevelRequirement = null;

		private static ConfigEntry<float> experienceGainedFactor = null;

		private static ConfigEntry<int> experienceLoss = null;

		private static ConfigEntry<int> staminaReductionPerLevel = null;

		private static Skill building = null;

		private ConfigEntry<T> config<[<cfdf0136-75e9-4db0-8de8-ad8627f7c15b>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(val);
			syncedConfigEntry.SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<cfdf0136-75e9-4db0-8de8-ad8627f7c15b>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Expected O, but got Unknown
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Expected O, but got Unknown
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Expected O, but got Unknown
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Expected O, but got Unknown
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Expected O, but got Unknown
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Expected O, but got Unknown
			building = new Skill("Building", "building-icon.png");
			building.Description.English("Increases the health of pieces built by you and you can build higher.");
			building.Name.German("Bauen");
			building.Description.German("Erhöht die Lebenspunkte von Bauten, die von dir errichtet wurden und du kannst höher bauen.");
			building.Configurable = false;
			serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			maximumSupportFactor = config("2 - Building", "Maximum Support Factor", 1.5f, new ConfigDescription("Maximum support factor for building pieces at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			supportLossFactor = config("2 - Building", "Support Loss Factor", 0.75f, new ConfigDescription("Support loss factor for vertical and horizontal building at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 1f), Array.Empty<object>()));
			healthFactor = config("2 - Building", "Health Factor", 3f, new ConfigDescription("Health factor for building pieces at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			freeBuildLevelRequirement = config("2 - Building", "Free Build Level Requirement", 50, new ConfigDescription("Minimum required skill level to be able to receive free building pieces. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			durabilityUsageLevelRequirement = config("2 - Building", "Durability Increase Level Requirement", 30, new ConfigDescription("Minimum required skill level to reduce the durability usage of hammers by 30%. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			staminaReductionPerLevel = config("2 - Building", "Stamina Reduction per Level", 1, new ConfigDescription("Reduces the stamina usage while building. Percentage stamina reduction per level. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			experienceGainedFactor = config("3 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the building skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>()));
			experienceGainedFactor.SettingChanged += [<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)] (object _, EventArgs _) =>
			{
				building.SkillGainFactor = experienceGainedFactor.Value;
			};
			building.SkillGainFactor = experienceGainedFactor.Value;
			experienceLoss = config("3 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the building skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			experienceLoss.SettingChanged += [<889aebfa-cfac-4348-afa0-0cb5ddf0f0c5>NullableContext(0)] (object _, EventArgs _) =>
			{
				building.SkillLoss = experienceLoss.Value;
			};
			building.SkillLoss = experienceLoss.Value;
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			Harmony val = new Harmony("org.bepinex.plugins.building");
			val.PatchAll(executingAssembly);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<f63c36ed-642f-48a4-bad2-672b01f013f7>Embedded]
	internal sealed class <f63c36ed-642f-48a4-bad2-672b01f013f7>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<f63c36ed-642f-48a4-bad2-672b01f013f7>Embedded]
	[CompilerGenerated]
	internal sealed class <7174970d-af6f-4179-b759-d90d32d0d949>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <7174970d-af6f-4179-b759-d90d32d0d949>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <7174970d-af6f-4179-b759-d90d32d0d949>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[<f63c36ed-642f-48a4-bad2-672b01f013f7>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace SkillManager
{
	[<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(1)]
	[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(0)]
	[PublicAPI]
	internal class Skill
	{
		[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(0)]
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				string key = localizations.FirstOrDefault([<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance);
				}
			}

			public static Localization ForLanguage([<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)] string language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[PublicAPI]
		[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(0)]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", key);
			}

			public LocalizeKey Portuguese_Brazilian(string key)
			{
				return addForLang("Portuguese_Brazilian", key);
			}

			public LocalizeKey Chinese(string key)
			{
				return addForLang("Chinese", key);
			}

			public LocalizeKey Japanese(string key)
			{
				return addForLang("Japanese", key);
			}

			public LocalizeKey Korean(string key)
			{
				return addForLang("Korean", key);
			}

			public LocalizeKey Hindi(string key)
			{
				return addForLang("Hindi", key);
			}

			public LocalizeKey Thai(string key)
			{
				return addForLang("Thai", key);
			}

			public LocalizeKey Abenaki(string key)
			{
				return addForLang("Abenaki", key);
			}

			public LocalizeKey Croatian(string key)
			{
				return addForLang("Croatian", key);
			}

			public LocalizeKey Georgian(string key)
			{
				return addForLang("Georgian", key);
			}

			public LocalizeKey Greek(string key)
			{
				return addForLang("Greek", key);
			}

			public LocalizeKey Serbian(string key)
			{
				return addForLang("Serbian", key);
			}

			public LocalizeKey Ukrainian(string key)
			{
				return addForLang("Ukrainian", key);
			}

			private LocalizeKey addForLang(string lang, string value)
			{
				Localizations[lang] = value;
				if (Localization.instance.GetSelectedLanguage() == lang)
				{
					Localization.instance.AddWord(Key, value);
				}
				else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
				{
					Localization.instance.AddWord(Key, value);
				}
				return this;
			}

			[HarmonyPriority(300)]
			internal static void AddLocalizedKeys(Localization __instance, string language)
			{
				foreach (LocalizeKey key in keys)
				{
					string value2;
					if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value))
					{
						__instance.AddWord(key.Key, value);
					}
					else if (key.Localizations.TryGetValue("alias", out value2))
					{
						Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
					}
				}
			}
		}

		[<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
			[UsedImplicitly]
			public string Category;
		}

		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		[<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(0)]
		private static class Patch_Skills_IsSkillValid
		{
			private static void Postfix(SkillType type, ref bool __result)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (!__result && skills.ContainsKey(type))
				{
					__result = true;
				}
			}
		}

		private static readonly Dictionary<SkillType, Skill> skills;

		internal static readonly Dictionary<string, Skill> skillByName;

		private readonly string skillName;

		private readonly string internalSkillName;

		private readonly SkillDef skillDef;

		public readonly LocalizeKey Name;

		public readonly LocalizeKey Description;

		private float skillEffectFactor = 1f;

		private int skillLoss = 5;

		public bool Configurable;

		private static bool InitializedTerminal;

		[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		private static Localization _english;

		[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static bool hasConfigSync;

		[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		private static object _configSync;

		public float SkillGainFactor
		{
			get
			{
				return skillDef.m_increseStep;
			}
			set
			{
				skillDef.m_increseStep = value;
				this.SkillGainFactorChanged?.Invoke(value);
			}
		}

		public float SkillEffectFactor
		{
			get
			{
				return skillEffectFactor;
			}
			set
			{
				skillEffectFactor = value;
				this.SkillEffectFactorChanged?.Invoke(value);
			}
		}

		public int SkillLoss
		{
			get
			{
				return skillLoss;
			}
			set
			{
				skillLoss = value;
				this.SkillLossChanged?.Invoke(value);
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				object obj = _plugin;
				if (obj == null)
				{
					BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First([<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
					_plugin = val;
					obj = (object)val;
				}
				return (BaseUnityPlugin)obj;
			}
		}

		[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		private static object configSync
		{
			[<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(2)]
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		[method: <9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(2)]
		[field: <7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		public event Action<float> SkillGainFactorChanged;

		[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		[method: <9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(2)]
		[field: <7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		public event Action<float> SkillEffectFactorChanged;

		[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		[method: <9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(2)]
		[field: <7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)]
		public event Action<float> SkillLossChanged;

		public Skill(string englishName, string icon)
			: this(englishName, loadSprite(icon, 64, 64))
		{
		}

		public Skill(string englishName, Sprite icon)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			SkillType val = fromName(englishName);
			string text = new Regex("[^a-zA-Z]").Replace(englishName, "_");
			skills[val] = this;
			skillByName[englishName] = this;
			skillDef = new SkillDef
			{
				m_description = "$skilldesc_" + text,
				m_icon = icon,
				m_increseStep = 1f,
				m_skill = val
			};
			internalSkillName = text;
			skillName = englishName;
			Name = new LocalizeKey("skill_" + ((object)(SkillType)(ref val)).ToString()).English(englishName);
			Description = new LocalizeKey("skilldesc_" + text);
		}

		public static SkillType fromName(string englishName)
		{
			return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName));
		}

		static Skill()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			skills = new Dictionary<SkillType, Skill>();
			skillByName = new Dictionary<string, Skill>();
			InitializedTerminal = false;
			hasConfigSync = true;
			Harmony val = new Harmony("org.bepinex.helpers.skillmanager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null);
		}

		private static void Patch_FejdStartup()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			foreach (Skill skill in skills.Values)
			{
				if (skill.Configurable)
				{
					string key = skill.Name.Key;
					string group = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim();
					string category = Localization.instance.Localize(key).Trim();
					ConfigEntry<float> skillGain = config(group, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillGainFactor = skillGain.Value;
					skillGain.SettingChanged += [<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillGainFactor = skillGain.Value;
					};
					ConfigEntry<float> skillEffect = config(group, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillEffectFactor = skillEffect.Value;
					skillEffect.SettingChanged += [<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillEffectFactor = skillEffect.Value;
					};
					ConfigEntry<int> skillLoss = config(group, "Skill loss", skill.skillLoss, new ConfigDescription("How much experience to lose on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.skillLoss = skillLoss.Value;
					skillLoss.SettingChanged += [<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.skillLoss = skillLoss.Value;
					};
				}
			}
		}

		private static void Patch_Skills_GetSkillDef([<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)] ref SkillDef __result, List<SkillDef> ___m_skills, SkillType type)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (__result == null)
			{
				SkillDef val = GetSkillDef(type);
				if (val != null)
				{
					___m_skills.Add(val);
					__result = val;
				}
			}
		}

		private static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				SkillType current = key;
				Skill skill = skills[current];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					Skill skill2 = __instance.GetSkill(current);
					skill2.m_level += value;
					skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f);
					((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(SkillType)(ref current)).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon);
					Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level);
					return false;
				}
			}
			return true;
		}

		private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				Skill skill = skills[key];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					__instance.ResetSkill(key);
					Console.instance.Print("Skill " + skill.internalSkillName + " reset");
					return false;
				}
			}
			return true;
		}

		private static void Patch_Skills_OnDeath_Prefix(Skills __instance, [<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(new byte[] { 2, 1 })] ref Dictionary<SkillType, Skill> __state)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				__state = new Dictionary<SkillType, Skill>();
			}
			foreach (KeyValuePair<SkillType, Skill> skill in skills)
			{
				if (__instance.m_skillData.TryGetValue(skill.Key, out var value))
				{
					__state[skill.Key] = value;
					if (skill.Value.skillLoss > 0)
					{
						Skill obj = value;
						obj.m_level -= value.m_level * (float)skill.Value.SkillLoss / 100f;
						value.m_accumulator = 0f;
					}
					__instance.m_skillData.Remove(skill.Key);
				}
			}
		}

		private static void Patch_Skills_OnDeath_Finalizer(Skills __instance, [<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(new byte[] { 2, 1 })] ref Dictionary<SkillType, Skill> __state)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				return;
			}
			foreach (KeyValuePair<SkillType, Skill> item in __state)
			{
				__instance.m_skillData[item.Key] = item.Value;
			}
			__state = null;
		}

		private static void Patch_Terminal_InitTerminal_Prefix()
		{
			InitializedTerminal = Terminal.m_terminalInitialized;
		}

		private static void Patch_Terminal_InitTerminal()
		{
			if (!InitializedTerminal)
			{
				AddSkill(Terminal.commands["raiseskill"]);
				AddSkill(Terminal.commands["resetskill"]);
			}
			static void AddSkill(ConsoleCommand command)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Expected O, but got Unknown
				ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher;
				command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)([<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(0)] () =>
				{
					List<string> list = fetcher.Invoke();
					list.AddRange(skills.Values.Select([<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(0)] (Skill skill) => skill.internalSkillName));
					return list;
				});
			}
		}

		[<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(2)]
		private static SkillDef GetSkillDef(SkillType skillType)
		{
			//IL_0005: 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)
			if (!skills.ContainsKey(skillType))
			{
				return null;
			}
			return skills[skillType].skillDef;
		}

		private static byte[] ReadEmbeddedFileBytes(string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static Texture2D loadTexture(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_001f: Expected O, but got Unknown
			Texture2D val = new Texture2D(0, 0);
			ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name));
			return val;
		}

		private static Sprite loadSprite(string name, int width, int height)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero);
		}

		private static ConfigEntry<T> config<[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)] T>(string group, string name, T value, ConfigDescription description)
		{
			ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description);
			configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T))
				.Invoke(configSync, new object[1] { val });
			return val;
		}

		private static ConfigEntry<T> config<[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(2)] T>(string group, string name, T value, string description)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[PublicAPI]
	[<7174970d-af6f-4179-b759-d90d32d0d949>Nullable(0)]
	[<9a5d51a2-47ec-4585-bd2c-d7c1abee8341>NullableContext(1)]
	internal static class SkillExtensions
	{
		public static float GetSkillFactor(this Character character, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return character.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static float GetSkillFactor(this Skills skills, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return skills.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static void RaiseSkill(this Character character, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			character.RaiseSkill(Skill.fromName(name), value);
		}

		public static void RaiseSkill(this Skills skill, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			skill.RaiseSkill(Skill.fromName(name), value);
		}

		public static void LowerSkill(this Character character, string name, float factor = 1f)
		{
			character.GetSkills().LowerSkill(name, factor);
		}

		public static void LowerSkill(this Skills skills, string name, float factor)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (factor > 0f && skills.m_skillData.TryGetValue(Skill.fromName(name), out var value))
			{
				Skill obj = value;
				obj.m_level -= value.m_level * factor;
				value.m_accumulator = 0f;
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			ZPackage package2 = package;
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package2.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package2 = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package2)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[PublicAPI]
	[HarmonyPatch]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			ZRpc rpc2 = rpc;
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		[HarmonyPrefix]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}

BepInEx/plugins/Smoothbrain-Cooking/Cooking.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using ItemDataManager;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Guid("F5F99B0C-533A-409B-9A59-A8DEC82149D4")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("Cooking")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/Cooking")]
[assembly: AssemblyTitle("Cooking")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<cd4dd43d-2e26-4542-b987-ac6ec51d950c>Embedded]
	internal sealed class <cd4dd43d-2e26-4542-b987-ac6ec51d950c>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<cd4dd43d-2e26-4542-b987-ac6ec51d950c>Embedded]
	[CompilerGenerated]
	internal sealed class <93cdd52d-93c3-4967-b258-8910f6822e5a>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <93cdd52d-93c3-4967-b258-8910f6822e5a>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <93cdd52d-93c3-4967-b258-8910f6822e5a>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[<cd4dd43d-2e26-4542-b987-ac6ec51d950c>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Cooking
{
	[<93cdd52d-93c3-4967-b258-8910f6822e5a>Nullable(0)]
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	[BepInPlugin("org.bepinex.plugins.cooking", "Cooking", "1.1.14")]
	[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(1)]
	public class Cooking : BaseUnityPlugin
	{
		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public bool? ShowRangeAsPercent;
		}

		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "Awake")]
		public class PlayerAwake
		{
			[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				((Character)__instance).m_nview.Register<int>("Cooking IncreaseSkill", (Action<long, int>)delegate(long _, int factor)
				{
					((Character)(object)__instance).RaiseSkill("Cooking", factor);
				});
			}
		}

		[HarmonyPatch(typeof(Player), "Update")]
		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		public class PlayerUpdate
		{
			[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					((Character)__instance).m_nview.GetZDO().Set("Cooking Skill Factor", ((Character)__instance).GetSkillFactor(Skill.fromName("Cooking")));
				}
			}
		}

		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		[HarmonyPatch(typeof(CookingStation), "RPC_RemoveDoneItem")]
		public class OnCookingDoneItems
		{
			[<93cdd52d-93c3-4967-b258-8910f6822e5a>Nullable(2)]
			public static Player cookingPlayer;

			private static void Prefix(long sender)
			{
				Player val = ((IEnumerable<Player>)Player.s_players).FirstOrDefault((Func<Player, bool>)((Player p) => ((ZDOID)(ref ((Character)p).m_nview.GetZDO().m_uid)).UserID == sender));
				if (val != null)
				{
					cookingPlayer = val;
				}
			}

			[UsedImplicitly]
			public static void Finalizer()
			{
				cookingPlayer = null;
			}
		}

		[HarmonyPatch(typeof(CookingStation), "SpawnItem")]
		[<93cdd52d-93c3-4967-b258-8910f6822e5a>Nullable(0)]
		public class XPOnDoneItems
		{
			private static void Prefix(string name, out ItemDrop __state)
			{
				__state = ObjectDB.instance.GetItemPrefab(name).GetComponent<ItemDrop>();
				AttachCooking(__state, OnCookingDoneItems.cookingPlayer ?? Player.m_localPlayer);
				Player cookingPlayer = OnCookingDoneItems.cookingPlayer;
				if (cookingPlayer != null)
				{
					((Character)cookingPlayer).m_nview.InvokeRPC("Cooking IncreaseSkill", new object[1] { 5 });
				}
			}

			private static void Finalizer(ItemDrop __state)
			{
				__state.m_itemData.Data().Remove<CookingSkill>();
			}
		}

		[<93cdd52d-93c3-4967-b258-8910f6822e5a>Nullable(0)]
		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		public class CheckCooking
		{
			[UsedImplicitly]
			public static void Prefix(InventoryGui __instance)
			{
				if (__instance.m_craftRecipe != null)
				{
					AttachCooking(__instance.m_craftRecipe.m_item, Player.m_localPlayer);
				}
			}

			[UsedImplicitly]
			public static void Finalizer(InventoryGui __instance)
			{
				__instance.m_craftRecipe?.m_item.m_itemData.Data().Remove<CookingSkill>();
			}
		}

		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "EatFood")]
		public class ApplyStatusEffectToPlayer
		{
			[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(1)]
			private static void Postfix(Player __instance, ItemData item, bool __result)
			{
				if ((item.Data().Get<CookingSkill>()?.happy ?? false) && __result)
				{
					((Character)__instance).GetSEMan().AddStatusEffect(StringExtensionMethods.GetStableHashCode("Happy"), false, 0, 0f);
				}
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		public class AddStatusEffect
		{
			[<93cdd52d-93c3-4967-b258-8910f6822e5a>Nullable(2)]
			private static StatusEffect happy;

			[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(1)]
			private static void Postfix(ObjectDB __instance)
			{
				happy = (StatusEffect)(object)ScriptableObject.CreateInstance<IncreaseMovementSpeed>();
				((Object)happy).name = "Happy";
				happy.m_name = "Happy";
				happy.m_icon = loadSprite("happy.png", 64, 64);
				SetValues();
				__instance.m_StatusEffects.Add(happy);
			}

			public static void SetValues()
			{
				if (happy != null)
				{
					happy.m_tooltip = $"You ate a perfect meal. Your movement speed is increased by {(happyBuffStrengthFactor.Value - 1f) * 100f}%.";
					happy.m_ttl = (float)happyBuffDuration.Value * 60f;
				}
			}
		}

		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		public class IncreaseMovementSpeed : StatusEffect
		{
			public override void ModifySpeed(float baseSpeed, ref float speed)
			{
				speed *= happyBuffStrengthFactor.Value;
			}
		}

		[HarmonyPatch(typeof(ItemData), "GetTooltip", new Type[]
		{
			typeof(ItemData),
			typeof(int),
			typeof(bool),
			typeof(float)
		})]
		[<93cdd52d-93c3-4967-b258-8910f6822e5a>Nullable(0)]
		public class UpdateFoodDisplay
		{
			[UsedImplicitly]
			public static void Postfix(ItemData item, bool crafting, ref string __result)
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				if (crafting && item.m_shared.m_food > 0f && item.m_shared.m_foodStamina > 0f)
				{
					float num = (float)Mathf.RoundToInt(((Character)Player.m_localPlayer).GetSkillFactor(Skill.fromName("Cooking")) * 100f / 5f) * 5f / 100f;
					if (num > 0f)
					{
						__result = new Regex("(\\$item_food_health.*?</color>)").Replace(__result, $"$1 (<color=orange>+{Mathf.Round(num * item.m_shared.m_food * (healthIncreaseFactor.Value - 1f))}</color>)");
						__result = new Regex("(\\$item_food_stamina.*?</color>)").Replace(__result, $"$1 (<color=orange>+{Mathf.Round(num * item.m_shared.m_foodStamina * (staminaIncreaseFactor.Value - 1f))}</color>)");
						__result = new Regex("(\\$item_food_regen.*?</color>)").Replace(__result, $"$1 (<color=orange>+{Mathf.Round(num * item.m_shared.m_foodRegen * (regenIncreaseFactor.Value - 1f))}</color>)");
						if (item.m_shared.m_foodEitr > 0f)
						{
							__result = new Regex("(\\$item_food_eitr.*?</color>)").Replace(__result, $"$1 (<color=orange>+{Mathf.Round(num * item.m_shared.m_foodEitr * (eitrIncreaseFactor.Value - 1f))}</color>)");
						}
					}
				}
				if (!crafting)
				{
					CookingSkill? cookingSkill = item.Data().Get<CookingSkill>();
					if (cookingSkill != null && cookingSkill.happy)
					{
						__result += "\nThis food has been cooked perfectly and will make you happy.";
					}
				}
			}

			[UsedImplicitly]
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				FieldInfo food = AccessTools.DeclaredField(typeof(SharedData), "m_food");
				FieldInfo foodStamina = AccessTools.DeclaredField(typeof(SharedData), "m_foodStamina");
				FieldInfo foodRegen = AccessTools.DeclaredField(typeof(SharedData), "m_foodRegen");
				foreach (CodeInstruction instruction in instructions)
				{
					yield return instruction;
					if (instruction.opcode == OpCodes.Ldfld && (CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)food) || CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)foodStamina) || CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)foodRegen)))
					{
						yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(Mathf), "Round", (Type[])null, (Type[])null));
					}
				}
			}
		}

		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "Save")]
		public class SaveFoodBonus
		{
			[UsedImplicitly]
			[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(1)]
			public static void Prefix(Player __instance)
			{
				foreach (Food food in __instance.m_foods)
				{
					__instance.m_knownStations["Cooking Skill " + food.m_name] = food.m_item.Data().Get<CookingSkill>()?.skill ?? 0;
				}
			}
		}

		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "Load")]
		public class LoadFoodBonus
		{
			[UsedImplicitly]
			[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(1)]
			public static void Postfix(Player __instance)
			{
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_007a: Expected O, but got Unknown
				foreach (Food food in __instance.m_foods)
				{
					if (__instance.m_knownStations.TryGetValue("Cooking Skill " + food.m_name, out var value) && value > 0)
					{
						food.m_item.m_shared = (SharedData)AccessTools.DeclaredMethod(typeof(object), "MemberwiseClone", (Type[])null, (Type[])null).Invoke(food.m_item.m_shared, Array.Empty<object>());
						CookingSkill cookingSkill = food.m_item.Data().Add<CookingSkill>();
						if (cookingSkill == null)
						{
							Debug.LogError((object)"COOKINGSKILL IS NULL");
							break;
						}
						cookingSkill.Value = "0" + value;
						cookingSkill.Load();
					}
				}
			}
		}

		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		public class IncreaseCraftingSkill
		{
			[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(1)]
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				MethodInfo statIncrement = AccessTools.DeclaredMethod(typeof(PlayerProfile), "IncrementStat", (Type[])null, (Type[])null);
				bool first = true;
				foreach (CodeInstruction instruction in instructions)
				{
					yield return instruction;
					if (first && CodeInstructionExtensions.Calls(instruction, statIncrement))
					{
						first = false;
						yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(IncreaseCraftingSkill), "CheckCookingIncrease", (Type[])null, (Type[])null));
					}
				}
			}

			private static void CheckCookingIncrease()
			{
				if (InventoryGui.instance.m_craftRecipe.m_item.m_itemData.Data().Get<CookingSkill>() != null)
				{
					((Character)(object)Player.m_localPlayer).RaiseSkill("Cooking", 5f);
				}
			}
		}

		[<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)]
		private class CookingSkill : ItemData
		{
			[<93cdd52d-93c3-4967-b258-8910f6822e5a>Nullable(1)]
			public static readonly Dictionary<SharedData, int> active = new Dictionary<SharedData, int>();

			public bool happy;

			public int skill;

			protected override bool AllowStackingIdenticalValues { get; set; } = true;


			~CookingSkill()
			{
				active.Remove(base.Item.m_shared);
			}

			public override void Save()
			{
				base.Value = (happy ? "1" : "0") + skill;
			}

			public override void Load()
			{
				string value = base.Value;
				active[base.Item.m_shared] = skill;
				if (value.Length > 0)
				{
					happy = value[0] == '1';
					int.TryParse(value.Substring(1), out var result);
					skill = result;
				}
				if (!base.IsCloned)
				{
					SharedData shared = base.Item.m_shared;
					shared.m_food *= 1f + (float)skill * (healthIncreaseFactor.Value - 1f) / 100f;
					SharedData shared2 = base.Item.m_shared;
					shared2.m_foodStamina *= 1f + (float)skill * (staminaIncreaseFactor.Value - 1f) / 100f;
					SharedData shared3 = base.Item.m_shared;
					shared3.m_foodRegen *= 1f + (float)skill * (regenIncreaseFactor.Value - 1f) / 100f;
					if (base.Item.m_shared.m_foodEitr > 0f)
					{
						SharedData shared4 = base.Item.m_shared;
						shared4.m_foodEitr *= 1f + (float)skill * (eitrIncreaseFactor.Value - 1f) / 100f;
					}
				}
			}

			public override void Unload()
			{
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: Expected O, but got Unknown
				base.Item.m_shared = (SharedData)AccessTools.DeclaredMethod(typeof(object), "MemberwiseClone", (Type[])null, (Type[])null).Invoke(base.Item.m_shared, Array.Empty<object>());
				SharedData shared = base.Item.m_shared;
				shared.m_food /= 1f + (float)skill * (healthIncreaseFactor.Value - 1f) / 100f;
				SharedData shared2 = base.Item.m_shared;
				shared2.m_foodStamina /= 1f + (float)skill * (staminaIncreaseFactor.Value - 1f) / 100f;
				SharedData shared3 = base.Item.m_shared;
				shared3.m_foodRegen /= 1f + (float)skill * (regenIncreaseFactor.Value - 1f) / 100f;
				if (base.Item.m_shared.m_foodEitr > 0f)
				{
					SharedData shared4 = base.Item.m_shared;
					shared4.m_foodEitr /= 1f + (float)skill * (eitrIncreaseFactor.Value - 1f) / 100f;
				}
			}
		}

		private const string ModName = "Cooking";

		private const string ModVersion = "1.1.14";

		private const string ModGUID = "org.bepinex.plugins.cooking";

		private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.cooking")
		{
			DisplayName = "Cooking",
			CurrentVersion = "1.1.14",
			MinimumRequiredVersion = "1.1.14"
		};

		private static ConfigEntry<Toggle> serverConfigLocked = null;

		private static ConfigEntry<float> healthIncreaseFactor = null;

		private static ConfigEntry<float> staminaIncreaseFactor = null;

		private static ConfigEntry<float> regenIncreaseFactor = null;

		private static ConfigEntry<float> eitrIncreaseFactor = null;

		private static ConfigEntry<int> happyMinimumLevel = null;

		private static ConfigEntry<int> happyBuffDuration = null;

		private static ConfigEntry<float> happyBuffStrengthFactor = null;

		private static ConfigEntry<float> experienceGainedFactor = null;

		private static ConfigEntry<int> experienceLoss = null;

		private ConfigEntry<T> config<[<93cdd52d-93c3-4967-b258-8910f6822e5a>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			configSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<93cdd52d-93c3-4967-b258-8910f6822e5a>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Expected O, but got Unknown
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Expected O, but got Unknown
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Expected O, but got Unknown
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Expected O, but got Unknown
			//IL_03d6: Unknown result type (might be due to invalid IL or missing references)
			Skill cooking = new Skill("Cooking", "cooking.png");
			cooking.Description.English("Increases health, stamina and health regen for food you cook.");
			cooking.Name.German("Kochen");
			cooking.Description.German("Erhöht die Lebenspunkte, Ausdauer und Lebenspunkteregeneration für von dir gekochtes Essen.");
			cooking.Configurable = false;
			serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			healthIncreaseFactor = config("2 - Cooking", "Health Increase Factor", 1.5f, new ConfigDescription("Factor for the health on food items at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			staminaIncreaseFactor = config("2 - Cooking", "Stamina Increase Factor", 1.5f, new ConfigDescription("Factor for the stamina on food items at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			regenIncreaseFactor = config("2 - Cooking", "Regen Increase Factor", 1.5f, new ConfigDescription("Factor for the health regeneration on food items at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			eitrIncreaseFactor = config("2 - Cooking", "Eitr Increase Factor", 1.5f, new ConfigDescription("Factor for the eitr on food items at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			happyMinimumLevel = config("3 - Happy", "Happy Required Level", 50, new ConfigDescription("Minimum required cooking skill level for a chance to cook perfect food. 0 is disabled", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			happyBuffDuration = config("3 - Happy", "Happy Buff Duration", 3, new ConfigDescription("Duration for the happy buff from eating perfectly cooked food in minutes.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 60), Array.Empty<object>()));
			happyBuffStrengthFactor = config("3 - Happy", "Happy Buff Strength", 1.1f, new ConfigDescription("Factor for the movement speed with the happy buff active.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 3f), Array.Empty<object>()));
			experienceGainedFactor = config("4 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the cooking skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>()));
			experienceGainedFactor.SettingChanged += [<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)] (object _, EventArgs _) =>
			{
				cooking.SkillGainFactor = experienceGainedFactor.Value;
			};
			cooking.SkillGainFactor = experienceGainedFactor.Value;
			experienceLoss = config("4 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the cooking skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			experienceLoss.SettingChanged += [<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)] (object _, EventArgs _) =>
			{
				cooking.SkillLoss = experienceLoss.Value;
			};
			cooking.SkillLoss = experienceLoss.Value;
			float oldHealthIncreaseFactor = healthIncreaseFactor.Value;
			healthIncreaseFactor.SettingChanged += [<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)] (object _, EventArgs _) =>
			{
				foreach (KeyValuePair<SharedData, int> item in CookingSkill.active)
				{
					SharedData key4 = item.Key;
					key4.m_food *= (1f + (float)item.Value * (healthIncreaseFactor.Value - 1f) / 100f) / (1f + (float)item.Value * (oldHealthIncreaseFactor - 1f) / 100f);
				}
				oldHealthIncreaseFactor = healthIncreaseFactor.Value;
			};
			float oldStaminaIncreaseFactor = staminaIncreaseFactor.Value;
			staminaIncreaseFactor.SettingChanged += [<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)] (object _, EventArgs _) =>
			{
				foreach (KeyValuePair<SharedData, int> item2 in CookingSkill.active)
				{
					SharedData key3 = item2.Key;
					key3.m_foodStamina *= (1f + (float)item2.Value * (staminaIncreaseFactor.Value - 1f) / 100f) / (1f + (float)item2.Value * (oldStaminaIncreaseFactor - 1f) / 100f);
				}
				oldStaminaIncreaseFactor = staminaIncreaseFactor.Value;
			};
			float oldRegenIncreaseFactor = regenIncreaseFactor.Value;
			regenIncreaseFactor.SettingChanged += [<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)] (object _, EventArgs _) =>
			{
				foreach (KeyValuePair<SharedData, int> item3 in CookingSkill.active)
				{
					SharedData key2 = item3.Key;
					key2.m_foodRegen *= (1f + (float)item3.Value * (regenIncreaseFactor.Value - 1f) / 100f) / (1f + (float)item3.Value * (oldRegenIncreaseFactor - 1f) / 100f);
				}
				oldRegenIncreaseFactor = regenIncreaseFactor.Value;
			};
			float oldEitrIncreaseFactor = eitrIncreaseFactor.Value;
			eitrIncreaseFactor.SettingChanged += [<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)] (object _, EventArgs _) =>
			{
				foreach (KeyValuePair<SharedData, int> item4 in CookingSkill.active)
				{
					SharedData key = item4.Key;
					key.m_foodEitr *= (1f + (float)item4.Value * (eitrIncreaseFactor.Value - 1f) / 100f) / (1f + (float)item4.Value * (oldEitrIncreaseFactor - 1f) / 100f);
				}
				oldEitrIncreaseFactor = eitrIncreaseFactor.Value;
			};
			happyBuffDuration.SettingChanged += [<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)] (object _, EventArgs _) =>
			{
				AddStatusEffect.SetValues();
			};
			happyBuffStrengthFactor.SettingChanged += [<aa94d3df-58f8-44d5-ac51-35b1a397bc1f>NullableContext(0)] (object _, EventArgs _) =>
			{
				AddStatusEffect.SetValues();
			};
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			new Harmony("org.bepinex.plugins.cooking").PatchAll(executingAssembly);
			ItemInfo.ForceLoadTypes.Add(typeof(CookingSkill));
		}

		private static void AttachCooking(ItemDrop item, Player cook)
		{
			if (item.m_itemData.m_shared.m_food > 0f && item.m_itemData.m_shared.m_foodStamina > 0f)
			{
				CookingSkill cookingSkill = item.m_itemData.Data().Add<CookingSkill>();
				cookingSkill.skill = Mathf.RoundToInt(((Character)cook).m_nview.GetZDO().GetFloat("Cooking Skill Factor", 0f) * 100f / 5f) * 5;
				if (happyMinimumLevel.Value > 0 && Random.Range(0, 100) <= cookingSkill.skill - happyMinimumLevel.Value)
				{
					cookingSkill.happy = true;
				}
				cookingSkill.Save();
				cookingSkill.Load();
			}
		}

		private static byte[] ReadEmbeddedFileBytes(string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			Assembly.GetExecutingAssembly().GetManifestResourceStream("Cooking." + name)?.CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static Texture2D loadTexture(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_001f: Expected O, but got Unknown
			Texture2D val = new Texture2D(0, 0);
			ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name));
			return val;
		}

		private static Sprite loadSprite(string name, int width, int height)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<4df94694-a8da-4d68-ac8d-dce615989ff8>Embedded]
	internal sealed class <4df94694-a8da-4d68-ac8d-dce615989ff8>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<4df94694-a8da-4d68-ac8d-dce615989ff8>Embedded]
	[CompilerGenerated]
	internal sealed class <d2ac5660-2615-449c-87c5-8fed3cbfae9d>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <d2ac5660-2615-449c-87c5-8fed3cbfae9d>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <d2ac5660-2615-449c-87c5-8fed3cbfae9d>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<4df94694-a8da-4d68-ac8d-dce615989ff8>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[<4df94694-a8da-4d68-ac8d-dce615989ff8>Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class <a6774f91-709a-46dc-b188-61bb0f3b2b1b>RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public <a6774f91-709a-46dc-b188-61bb0f3b2b1b>RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
	[PublicAPI]
	[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
	internal abstract class OwnConfigEntryBase
	{
		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		public object LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
	[PublicAPI]
	[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
	internal class SyncedConfigEntry<[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)] T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
	[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(2)]
	internal abstract class CustomSyncedValueBase
	{
		public object LocalBaseValue;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(1)]
		public readonly string Identifier;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(1)]
		public readonly Type Type;

		private object boxedValue;

		protected bool localIsOwner;

		public object BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action ValueChanged;

		[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
	[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
	internal sealed class CustomSyncedValue<[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)] T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
	[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
	internal class ConfigSync
	{
		[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)]
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
			public static ZRpc currentRpc;

			[HarmonyPrefix]
			[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)]
		private class ParsedConfigs
		{
			[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>();

			[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix([<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
			public object value;
		}

		[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		public string DisplayName;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		public string CurrentVersion;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		public string MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		private OwnConfigEntryBase lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 1, 0, 1 })]
		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		[method: <1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(2)]
		[field: <d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		public event Action<bool> SourceOfTruthChanged;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		[method: <1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(2)]
		[field: <d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		private event Action lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)] T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += [<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)] T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += [<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (object _, EventArgs _) =>
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(([<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 0, 1 })] KeyValuePair<long, string> kv) =>
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out var value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		[return: <d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		private static OwnConfigEntryBase configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		[return: <d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 2, 1 })]
		public static SyncedConfigEntry<T> ConfigData<[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)] T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)] T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage([<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 2, 1 })] IEnumerable<ConfigEntryBase> configs = null, [<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 2, 1 })] IEnumerable<CustomSyncedValueBase> customValues = null, [<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 2, 1 })] IEnumerable<PackageEntry> packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, [<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)] object value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(0)]
	[PublicAPI]
	[HarmonyPatch]
	[<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(1)]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		private string displayName;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		private string currentVersion;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		private string minimumRequiredVersion;

		public bool ModRequired = true;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		private string ReceivedCurrentVersion;

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		private string ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		[<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)]
		private ConfigSync ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error([<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(2)] ZRpc rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, [<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(new byte[] { 2, 1, 1 })] Action<ZRpc, ZPackage> original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (ZRpc rpc, [<d2ac5660-2615-449c-87c5-8fed3cbfae9d>Nullable(1)] ZPackage pkg) =>
				{
					CheckVersion(rpc, pkg, action);
				}));
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		[HarmonyPrefix]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy([<1db96211-df8f-4b2e-b85a-882ecc2d84e5>NullableContext(0)] (KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<ee141e81-b8c3-4e7d-958f-424b97b53880>Embedded]
	internal sealed class <ee141e81-b8c3-4e7d-958f-424b97b53880>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<ee141e81-b8c3-4e7d-958f-424b97b53880>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <8ad71c7b-bae5-42a3-8d99-2a973779ee07>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <8ad71c7b-bae5-42a3-8d99-2a973779ee07>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <8ad71c7b-bae5-42a3-8d99-2a973779ee07>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<ee141e81-b8c3-4e7d-958f-424b97b53880>Embedded]
	internal sealed class <5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace SkillManager
{
	[<5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(1)]
	[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(0)]
	[PublicAPI]
	internal class Skill
	{
		[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(0)]
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				string key = localizations.FirstOrDefault([<5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance);
				}
			}

			public static Localization ForLanguage([<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)] string language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[PublicAPI]
		[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(0)]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", key);
			}

			public LocalizeKey Portuguese_Brazilian(string key)
			{
				return addForLang("Portuguese_Brazilian", key);
			}

			public LocalizeKey Chinese(string key)
			{
				return addForLang("Chinese", key);
			}

			public LocalizeKey Japanese(string key)
			{
				return addForLang("Japanese", key);
			}

			public LocalizeKey Korean(string key)
			{
				return addForLang("Korean", key);
			}

			public LocalizeKey Hindi(string key)
			{
				return addForLang("Hindi", key);
			}

			public LocalizeKey Thai(string key)
			{
				return addForLang("Thai", key);
			}

			public LocalizeKey Abenaki(string key)
			{
				return addForLang("Abenaki", key);
			}

			public LocalizeKey Croatian(string key)
			{
				return addForLang("Croatian", key);
			}

			public LocalizeKey Georgian(string key)
			{
				return addForLang("Georgian", key);
			}

			public LocalizeKey Greek(string key)
			{
				return addForLang("Greek", key);
			}

			public LocalizeKey Serbian(string key)
			{
				return addForLang("Serbian", key);
			}

			public LocalizeKey Ukrainian(string key)
			{
				return addForLang("Ukrainian", key);
			}

			private LocalizeKey addForLang(string lang, string value)
			{
				Localizations[lang] = value;
				if (Localization.instance.GetSelectedLanguage() == lang)
				{
					Localization.instance.AddWord(Key, value);
				}
				else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
				{
					Localization.instance.AddWord(Key, value);
				}
				return this;
			}

			[HarmonyPriority(300)]
			internal static void AddLocalizedKeys(Localization __instance, string language)
			{
				foreach (LocalizeKey key in keys)
				{
					string value2;
					if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value))
					{
						__instance.AddWord(key.Key, value);
					}
					else if (key.Localizations.TryGetValue("alias", out value2))
					{
						Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
					}
				}
			}
		}

		[<5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
			[UsedImplicitly]
			public string Category;
		}

		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		[<5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(0)]
		private static class Patch_Skills_IsSkillValid
		{
			private static void Postfix(SkillType type, ref bool __result)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (!__result && skills.ContainsKey(type))
				{
					__result = true;
				}
			}
		}

		private static readonly Dictionary<SkillType, Skill> skills;

		internal static readonly Dictionary<string, Skill> skillByName;

		private readonly string skillName;

		private readonly string internalSkillName;

		private readonly SkillDef skillDef;

		public readonly LocalizeKey Name;

		public readonly LocalizeKey Description;

		private float skillEffectFactor = 1f;

		private int skillLoss = 5;

		public bool Configurable;

		private static bool InitializedTerminal;

		[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		private static Localization _english;

		[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static bool hasConfigSync;

		[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		private static object _configSync;

		public float SkillGainFactor
		{
			get
			{
				return skillDef.m_increseStep;
			}
			set
			{
				skillDef.m_increseStep = value;
				this.SkillGainFactorChanged?.Invoke(value);
			}
		}

		public float SkillEffectFactor
		{
			get
			{
				return skillEffectFactor;
			}
			set
			{
				skillEffectFactor = value;
				this.SkillEffectFactorChanged?.Invoke(value);
			}
		}

		public int SkillLoss
		{
			get
			{
				return skillLoss;
			}
			set
			{
				skillLoss = value;
				this.SkillLossChanged?.Invoke(value);
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				object obj = _plugin;
				if (obj == null)
				{
					BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First([<5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
					_plugin = val;
					obj = (object)val;
				}
				return (BaseUnityPlugin)obj;
			}
		}

		[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		private static object configSync
		{
			[<5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(2)]
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		[method: <5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(2)]
		[field: <8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		public event Action<float> SkillGainFactorChanged;

		[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		[method: <5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(2)]
		[field: <8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		public event Action<float> SkillEffectFactorChanged;

		[<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		[method: <5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(2)]
		[field: <8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)]
		public event Action<float> SkillLossChanged;

		public Skill(string englishName, string icon)
			: this(englishName, loadSprite(icon, 64, 64))
		{
		}

		public Skill(string englishName, Sprite icon)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			SkillType val = fromName(englishName);
			string text = new Regex("[^a-zA-Z]").Replace(englishName, "_");
			skills[val] = this;
			skillByName[englishName] = this;
			skillDef = new SkillDef
			{
				m_description = "$skilldesc_" + text,
				m_icon = icon,
				m_increseStep = 1f,
				m_skill = val
			};
			internalSkillName = text;
			skillName = englishName;
			Name = new LocalizeKey("skill_" + ((object)(SkillType)(ref val)).ToString()).English(englishName);
			Description = new LocalizeKey("skilldesc_" + text);
		}

		public static SkillType fromName(string englishName)
		{
			return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName));
		}

		static Skill()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			skills = new Dictionary<SkillType, Skill>();
			skillByName = new Dictionary<string, Skill>();
			InitializedTerminal = false;
			hasConfigSync = true;
			Harmony val = new Harmony("org.bepinex.helpers.skillmanager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null);
		}

		private static void Patch_FejdStartup()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			foreach (Skill skill in skills.Values)
			{
				if (skill.Configurable)
				{
					string key = skill.Name.Key;
					string group = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim();
					string category = Localization.instance.Localize(key).Trim();
					ConfigEntry<float> skillGain = config(group, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillGainFactor = skillGain.Value;
					skillGain.SettingChanged += [<5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillGainFactor = skillGain.Value;
					};
					ConfigEntry<float> skillEffect = config(group, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillEffectFactor = skillEffect.Value;
					skillEffect.SettingChanged += [<5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillEffectFactor = skillEffect.Value;
					};
					ConfigEntry<int> skillLoss = config(group, "Skill loss", skill.skillLoss, new ConfigDescription("How much experience to lose on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.skillLoss = skillLoss.Value;
					skillLoss.SettingChanged += [<5e6834de-84b5-46b2-8a7a-83dea14c5f5a>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.skillLoss = skillLoss.Value;
					};
				}
			}
		}

		private static void Patch_Skills_GetSkillDef([<8ad71c7b-bae5-42a3-8d99-2a973779ee07>Nullable(2)] ref SkillDef __result, List<SkillDef> ___m_skills, SkillType type)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (__result == null)
			{
				SkillDef val = GetSkillDef(type);
				if (val != null)
				{
					___m_skills.Add(val);
					__result = val;
				}
			}
		}

		private static bool Patch_Skills_CheatRaiseski

BepInEx/plugins/Smoothbrain-DualWield/DualWield.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Guid("497EB368-9410-49A7-A098-9E3905D0DA35")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyProduct("DualWield")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/DualWield")]
[assembly: AssemblyTitle("DualWield")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<8a165406-948f-446d-94e5-058879671328>Embedded]
	internal sealed class <8a165406-948f-446d-94e5-058879671328>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<8a165406-948f-446d-94e5-058879671328>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <609ca11b-4288-43fc-a754-b58364673409>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <609ca11b-4288-43fc-a754-b58364673409>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <609ca11b-4288-43fc-a754-b58364673409>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<8a165406-948f-446d-94e5-058879671328>Embedded]
	internal sealed class <bed75460-308b-41d8-8216-3dc8a843575b>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <bed75460-308b-41d8-8216-3dc8a843575b>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace DualWield
{
	[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
	[<609ca11b-4288-43fc-a754-b58364673409>Nullable(0)]
	[BepInPlugin("org.bepinex.plugins.dualwield", "Dual Wield", "1.0.8")]
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	public class DualWield : BaseUnityPlugin
	{
		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		private struct AnimationBalancing
		{
			public float speed;

			public float damage;

			public float stamina;
		}

		[<609ca11b-4288-43fc-a754-b58364673409>Nullable(0)]
		private struct AnimationBalancingConfig
		{
			public ConfigEntry<float> speed;

			public ConfigEntry<float> damage;

			public ConfigEntry<float> stamina;
		}

		[HarmonyPatch(typeof(Player), "Start")]
		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		private static class Patch_Player_Start
		{
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				if (CustomRuntimeControllers.Count == 0 && Player.m_localPlayer != null)
				{
					CustomRuntimeControllers["Original"] = MakeAOC(new Dictionary<string, string>(), ((Character)__instance).m_animator.runtimeAnimatorController);
					CustomRuntimeControllers["DWswords"] = MakeAOC(replacementMap["DWswords"], ((Character)__instance).m_animator.runtimeAnimatorController);
					CustomRuntimeControllers["DWaxes"] = MakeAOC(replacementMap["DWaxes"], ((Character)__instance).m_animator.runtimeAnimatorController);
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "EquipItem")]
		[<609ca11b-4288-43fc-a754-b58364673409>Nullable(0)]
		private static class Patch_Humanoid_EquipItem
		{
			private static bool CheckDualOneHandedWeaponEquip(Humanoid __instance, ItemData item, bool triggerEquipEffects)
			{
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Invalid comparison between Unknown and I4
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Invalid comparison between Unknown and I4
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val != null)
				{
					ItemData rightItem = ((Humanoid)val).m_rightItem;
					if (rightItem != null && (int)rightItem.m_shared.m_itemType == 3 && ((Humanoid)val).m_rightItem.m_shared.m_skillType == item.m_shared.m_skillType && (int)item.m_shared.m_skillType != 5 && !DualWieldExclusion.Contains(((Object)item.m_dropPrefab).name))
					{
						if (((Humanoid)val).m_leftItem != null)
						{
							((Humanoid)val).UnequipItem(((Humanoid)val).m_leftItem, triggerEquipEffects);
						}
						((Humanoid)val).m_leftItem = item;
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				List<CodeInstruction> instrs = instructions.ToList();
				int i = 0;
				while (i < instrs.Count)
				{
					yield return instrs[i];
					if (i >= 4 && instrs[i - 4].opcode == OpCodes.Ldarg_1 && instrs[i - 1].opcode == OpCodes.Ldc_I4_3 && instrs[i].opcode == OpCodes.Bne_Un)
					{
						yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						yield return new CodeInstruction(OpCodes.Ldarg_1, (object)null);
						yield return new CodeInstruction(OpCodes.Ldarg_2, (object)null);
						yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(Patch_Humanoid_EquipItem), "CheckDualOneHandedWeaponEquip", (Type[])null, (Type[])null));
						yield return new CodeInstruction(OpCodes.Brtrue, instrs[i].operand);
					}
					int num = i + 1;
					i = num;
				}
			}

			private static void Prefix()
			{
				Patch_Humanoid_SetupEquipment.ManipulatingEquipment = true;
			}

			private static void Postfix()
			{
				Patch_Humanoid_SetupEquipment.ManipulatingEquipment = false;
			}
		}

		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		[HarmonyPatch(typeof(Humanoid), "UnequipAllItems")]
		private static class Patch_Humanoid_UnequipAllItems
		{
			private static void Prefix()
			{
				Patch_Humanoid_SetupEquipment.ManipulatingEquipment = true;
			}

			private static void Postfix()
			{
				Patch_Humanoid_SetupEquipment.ManipulatingEquipment = false;
			}
		}

		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		[HarmonyPatch(typeof(Humanoid), "SetupEquipment")]
		private static class Patch_Humanoid_SetupEquipment
		{
			public static bool ManipulatingEquipment;

			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
			private static void Prefix(Humanoid __instance)
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Invalid comparison between Unknown and I4
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val != null && !ManipulatingEquipment && ((Humanoid)val).m_rightItem == null)
				{
					ItemData leftItem = ((Humanoid)val).m_leftItem;
					if (leftItem != null && (int)leftItem.m_shared.m_itemType == 3)
					{
						ItemData leftItem2 = ((Humanoid)val).m_leftItem;
						((Humanoid)val).UnequipItem(((Humanoid)val).m_leftItem, false);
						((Humanoid)val).m_rightItem = leftItem2;
						((Humanoid)val).m_rightItem.m_equipped = true;
						((Humanoid)val).m_leftItem = null;
					}
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "ShowHandItems")]
		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		private static class SwapHiddenItemsEquipOrder
		{
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				FieldInfo leftHand = AccessTools.DeclaredField(typeof(Humanoid), "m_hiddenLeftItem");
				FieldInfo rightHand = AccessTools.DeclaredField(typeof(Humanoid), "m_hiddenRightItem");
				foreach (CodeInstruction instruction in instructions)
				{
					if (CodeInstructionExtensions.LoadsField(instruction, leftHand, false))
					{
						yield return new CodeInstruction(OpCodes.Ldfld, (object)rightHand);
					}
					else if (CodeInstructionExtensions.LoadsField(instruction, rightHand, false))
					{
						yield return new CodeInstruction(OpCodes.Ldfld, (object)leftHand);
					}
					else
					{
						yield return instruction;
					}
				}
			}
		}

		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		[HarmonyPatch(typeof(VisEquipment), "SetWeaponTrails")]
		private static class Patch_VisEquipment_SetWeaponTrails
		{
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
			private static void Postfix(VisEquipment __instance, bool enabled)
			{
				if (Object.op_Implicit((Object)(object)__instance.m_leftItemInstance))
				{
					MeleeWeaponTrail[] componentsInChildren = __instance.m_leftItemInstance.GetComponentsInChildren<MeleeWeaponTrail>();
					for (int i = 0; i < componentsInChildren.Length; i++)
					{
						componentsInChildren[i].Emit = enabled;
					}
				}
			}
		}

		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		[HarmonyPatch(typeof(VisEquipment), "AttachItem")]
		private static class Patch_VisEquipment_AttachBackItem
		{
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
			private static void Postfix(VisEquipment __instance, Transform joint)
			{
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				if (__instance.m_isPlayer)
				{
					if ((Object)(object)joint == (Object)(object)__instance.m_backMelee && joint.childCount > 1)
					{
						joint.GetChild(1).localPosition = new Vector3(-0.003f, 0f, 0.003f);
						joint.GetChild(1).localEulerAngles = new Vector3(0f, 80f, 0f);
					}
					if ((Object)(object)joint == (Object)(object)__instance.m_backTool && joint.childCount > 1)
					{
						joint.GetChild(1).localPosition = new Vector3(-0.0008f, -0.0052f, 0f);
						joint.GetChild(1).localEulerAngles = new Vector3(20f, 0f, 0f);
					}
				}
			}
		}

		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		[HarmonyPatch(typeof(ZSyncAnimation), "RPC_SetTrigger")]
		private static class Patch_ZSyncAnimation_RPC_SetTrigger
		{
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
			private static void Prefix(ZSyncAnimation __instance, string name)
			{
				Player player = ((Component)__instance).GetComponent<Player>();
				if (player == null)
				{
					return;
				}
				SharedData val = sharedData([<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)] (VisEquipment v) => v.m_currentRightItemHash);
				SharedData data2 = sharedData([<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)] (VisEquipment v) => v.m_currentLeftItemHash);
				if (!HasAttack(data2) && !HasAttack(val))
				{
					return;
				}
				string key = "Original";
				if (Onehanded(data2) && Onehanded(val))
				{
					key = "DWswords";
					if (name == "mace_secondary" || val.m_attack.m_attackAnimation == "swing_axe" || val.m_secondaryAttack.m_attackAnimation == "axe_secondary")
					{
						key = "DWaxes";
					}
				}
				if (CustomRuntimeControllers.TryGetValue(key, out var value))
				{
					FastReplaceRAC(player, value);
				}
				[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(2)]
				bool HasAttack(SharedData data)
				{
					if (!HasAttackName(data?.m_attack.m_attackAnimation))
					{
						return HasAttackName(data?.m_secondaryAttack.m_attackAnimation);
					}
					return true;
				}
				[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(2)]
				bool HasAttackName(string anim)
				{
					if (anim == null || !name.StartsWith(anim, StringComparison.Ordinal) || anim.Length > name.Length + 1)
					{
						return anim == "swing_axe";
					}
					return true;
				}
				[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(2)]
				static bool Onehanded(SharedData data)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: Invalid comparison between Unknown and I4
					if (data == null)
					{
						return false;
					}
					return (int)data.m_itemType == 3;
				}
				[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
				[return: <609ca11b-4288-43fc-a754-b58364673409>Nullable(2)]
				SharedData sharedData(Func<VisEquipment, int> eq)
				{
					int num = eq(((Humanoid)player).m_visEquipment);
					if (num == 0)
					{
						return null;
					}
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(num);
					if (itemPrefab == null)
					{
						return null;
					}
					return itemPrefab.GetComponent<ItemDrop>()?.m_itemData.m_shared;
				}
			}
		}

		[HarmonyPatch(typeof(Attack), "OnAttackTrigger")]
		[<609ca11b-4288-43fc-a754-b58364673409>Nullable(0)]
		private static class Patch_Attack_OnAttackTrigger
		{
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
			private class DmgFactor
			{
				public float dmgFactor;

				public float knockback;
			}

			private static HitPointType? originalHitpointType;

			private static readonly Dictionary<SharedData, DmgFactor> alteredSharedData = new Dictionary<SharedData, DmgFactor>();

			private static void ApplyDmgFactor(bool reverse, string attackAnimation)
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Invalid comparison between Unknown and I4
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Invalid comparison between Unknown and I4
				foreach (KeyValuePair<SharedData, DmgFactor> alteredSharedDatum in alteredSharedData)
				{
					SharedData key = alteredSharedDatum.Key;
					SkillType skillType = key.m_skillType;
					bool flag = (((int)skillType == 3 || (int)skillType == 7) ? true : false);
					bool flag2 = flag;
					if (flag2)
					{
						bool flag3 = ((attackAnimation == "axe_secondary" || attackAnimation == "mace_secondary") ? true : false);
						flag2 = flag3;
					}
					if (flag2)
					{
						if (reverse)
						{
							key.m_attackForce = alteredSharedDatum.Value.knockback;
						}
						else
						{
							alteredSharedDatum.Value.knockback = key.m_attackForce;
							key.m_attackForce = 0f;
						}
					}
					float num = (reverse ? (1f / alteredSharedDatum.Value.dmgFactor) : alteredSharedDatum.Value.dmgFactor);
					((DamageTypes)(ref key.m_damages)).Modify(num);
					key.m_backstabBonus /= num;
				}
			}

			private static void Prefix(Attack __instance)
			{
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Invalid comparison between Unknown and I4
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_005f: Invalid comparison between Unknown and I4
				//IL_0101: Unknown result type (might be due to invalid IL or missing references)
				//IL_0112: Unknown result type (might be due to invalid IL or missing references)
				//IL_0145: Unknown result type (might be due to invalid IL or missing references)
				//IL_014a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0151: Unknown result type (might be due to invalid IL or missing references)
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_0189: Unknown result type (might be due to invalid IL or missing references)
				//IL_018b: Unknown result type (might be due to invalid IL or missing references)
				//IL_016c: Unknown result type (might be due to invalid IL or missing references)
				//IL_016e: Unknown result type (might be due to invalid IL or missing references)
				if (!(__instance.m_character is Player))
				{
					return;
				}
				SharedData val = __instance.m_character.m_leftItem?.m_shared;
				if (val == null)
				{
					return;
				}
				SharedData val2 = __instance.m_character.m_rightItem?.m_shared;
				if (val2 == null || (int)val.m_itemType != 3 || (int)val2.m_itemType != 3)
				{
					return;
				}
				if (attackMap.TryGetValue(((Object)((AnimatorClipInfo)(ref ((Character)__instance.m_character).m_animator.GetCurrentAnimatorClipInfo(0)[0])).clip).name, out var value) && balancingMap.TryGetValue(val2.m_skillType, out var value2))
				{
					float dmgFactor = value2[value].damage.Value / 100f;
					alteredSharedData.Add(val2, new DmgFactor
					{
						dmgFactor = dmgFactor
					});
					if (val2 != val)
					{
						alteredSharedData.Add(val, new DmgFactor
						{
							dmgFactor = dmgFactor
						});
					}
					ApplyDmgFactor(reverse: false, __instance.m_attackAnimation);
				}
				originalHitpointType = __instance.m_hitPointtype;
				__instance.m_hitPointtype = (HitPointType)2;
				__instance.m_attackAngle = 0f - __instance.m_attackAngle;
				__instance.m_weapon = __instance.m_character.m_leftItem;
				SkillType skillType = __instance.m_character.m_leftItem.m_shared.m_skillType;
				if (skillMap.TryGetValue(skillType, out var value3))
				{
					__instance.m_character.m_leftItem.m_shared.m_skillType = value3;
				}
				__instance.DoMeleeAttack();
				__instance.m_character.m_leftItem.m_shared.m_skillType = skillType;
				__instance.m_weapon = __instance.m_character.m_rightItem;
				__instance.m_attackAngle = 0f - __instance.m_attackAngle;
			}

			private static void Postfix(Attack __instance)
			{
				//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)
				if (originalHitpointType.HasValue)
				{
					__instance.m_hitPointtype = originalHitpointType.Value;
					originalHitpointType = null;
				}
				ApplyDmgFactor(reverse: true, __instance.m_attackAnimation);
				alteredSharedData.Clear();
			}
		}

		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "GetRandomSkillFactor")]
		private static class Patch_Skills_GetRandomSkillFactor
		{
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
			private static bool Prefix(Player __instance, SkillType skill, ref float __result)
			{
				//IL_0005: 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)
				if (skillMap.ContainsValue(skill))
				{
					__result = 0.03f + ((Character)__instance).GetSkillFactor(skill) * 1.5f;
					return false;
				}
				return true;
			}
		}

		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		[HarmonyPatch(typeof(Attack), "GetAttackStamina")]
		private static class Patch_Attack_GetAttackStamina
		{
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
			private static bool Prefix(Attack __instance, ref float __result)
			{
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0098: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
				bool flag = Onehanded(__instance.m_character.m_rightItem) && Onehanded(__instance.m_character.m_leftItem);
				if (__instance.m_character is Player && flag && balancingMap.TryGetValue(__instance.m_weapon.m_shared.m_skillType, out var value))
				{
					float value2 = value[(__instance.m_attackChainLevels > 1) ? (__instance.m_currentAttackCainLevel + 1) : 0].stamina.Value;
					__result = value2 - value2 / 6f * ((Character)__instance.m_character).GetSkillFactor(__instance.m_weapon.m_shared.m_skillType) - value2 / 6f * ((Character)__instance.m_character).GetSkillFactor(skillMap[__instance.m_weapon.m_shared.m_skillType]);
					return false;
				}
				return true;
				[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(2)]
				static bool Onehanded(ItemData item)
				{
					//IL_000b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0011: Invalid comparison between Unknown and I4
					if (item == null)
					{
						return false;
					}
					return (int)item.m_shared.m_itemType == 3;
				}
			}
		}

		[HarmonyPatch(typeof(Attack), "DoMeleeAttack")]
		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)]
		private static class Patch_Attack_DoMeleeAttack
		{
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(1)]
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator gen)
			{
				MethodInfo quaternionCreator = AccessTools.DeclaredMethod(typeof(Quaternion), "Euler", new Type[3]
				{
					typeof(float),
					typeof(float),
					typeof(float)
				}, (Type[])null);
				FieldInfo attackAngle = AccessTools.DeclaredField(typeof(Attack), "m_attackAngle");
				List<CodeInstruction> instrs = instructions.ToList();
				int i = 0;
				while (i < instrs.Count)
				{
					if (instrs[i].opcode == OpCodes.Neg && instrs[i + 2].opcode == OpCodes.Call && CodeInstructionExtensions.OperandIs(instrs[i + 2], (MemberInfo)quaternionCreator))
					{
						Label label = gen.DefineLabel();
						yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						yield return new CodeInstruction(OpCodes.Ldfld, (object)attackAngle);
						yield return new CodeInstruction(OpCodes.Ldc_R4, (object)0f);
						yield return new CodeInstruction(OpCodes.Ble, (object)label);
						yield return new CodeInstruction(OpCodes.Neg, (object)null);
						instrs[i + 1].labels.Add(label);
					}
					else
					{
						yield return instrs[i];
					}
					if (instrs[i].opcode == OpCodes.Ldfld && CodeInstructionExtensions.OperandIs(instrs[i], (MemberInfo)attackAngle))
					{
						yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(Mathf), "Abs", new Type[1] { typeof(float) }, (Type[])null));
					}
					int num = i + 1;
					i = num;
				}
			}
		}

		private const string ModName = "Dual Wield";

		private const string ModVersion = "1.0.8";

		private const string ModGUID = "org.bepinex.plugins.dualwield";

		private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.dualwield")
		{
			DisplayName = "Dual Wield",
			CurrentVersion = "1.0.8"
		};

		private static ConfigEntry<Toggle> serverConfigLocked = null;

		private static ConfigEntry<string> dualWieldExclusionList = null;

		private static ConfigEntry<float> experienceGainFactor = null;

		private static ConfigEntry<int> experienceLoss = null;

		private static ConfigEntry<Toggle> singleOffhandSkill = null;

		private static AssetBundle asset = null;

		private static readonly Dictionary<string, Dictionary<string, string>> replacementMap = new Dictionary<string, Dictionary<string, string>>();

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

		private static readonly Dictionary<string, AnimationClip> ExternalAnimations = new Dictionary<string, AnimationClip>();

		private static readonly Dictionary<string, RuntimeAnimatorController> CustomRuntimeControllers = new Dictionary<string, RuntimeAnimatorController>();

		private static readonly List<string> DualWieldExclusion = new List<string>();

		private static readonly Dictionary<SkillType, SkillType> skillMap = new Dictionary<SkillType, SkillType>();

		private static readonly Dictionary<SkillType, AnimationBalancing[]> balancingMapDefault = new Dictionary<SkillType, AnimationBalancing[]>
		{
			{
				(SkillType)7,
				new AnimationBalancing[4]
				{
					new AnimationBalancing
					{
						speed = 0.6f,
						damage = 0.9f,
						stamina = 40f
					},
					new AnimationBalancing
					{
						speed = 0.8f,
						damage = 0.9f,
						stamina = 20f
					},
					new AnimationBalancing
					{
						speed = 0.7f,
						damage = 0.95f,
						stamina = 20f
					},
					new AnimationBalancing
					{
						speed = 0.6f,
						damage = 1.7f,
						stamina = 30f
					}
				}
			},
			{
				(SkillType)3,
				new AnimationBalancing[4]
				{
					new AnimationBalancing
					{
						speed = 0.8f,
						damage = 0.6f,
						stamina = 35f
					},
					new AnimationBalancing
					{
						speed = 1.2f,
						damage = 0.65f,
						stamina = 14f
					},
					new AnimationBalancing
					{
						speed = 1.3f,
						damage = 0.75f,
						stamina = 15f
					},
					new AnimationBalancing
					{
						speed = 1.5f,
						damage = 0.75f,
						stamina = 15f
					}
				}
			},
			{
				(SkillType)2,
				new AnimationBalancing[4]
				{
					new AnimationBalancing
					{
						speed = 1.4f,
						damage = 0.3f,
						stamina = 32f
					},
					new AnimationBalancing
					{
						speed = 1.4f,
						damage = 0.2f,
						stamina = 9f
					},
					new AnimationBalancing
					{
						speed = 1.4f,
						damage = 0.2f,
						stamina = 9f
					},
					new AnimationBalancing
					{
						speed = 2f,
						damage = 1.4f,
						stamina = 27f
					}
				}
			},
			{
				(SkillType)1,
				new AnimationBalancing[4]
				{
					new AnimationBalancing
					{
						speed = 1f,
						damage = 0.5f,
						stamina = 40f
					},
					new AnimationBalancing
					{
						speed = 1f,
						damage = 0.9f,
						stamina = 15f
					},
					new AnimationBalancing
					{
						speed = 1f,
						damage = 0.9f,
						stamina = 15f
					},
					new AnimationBalancing
					{
						speed = 1.2f,
						damage = 0.9f,
						stamina = 20f
					}
				}
			}
		};

		private static readonly Dictionary<SkillType, AnimationBalancingConfig[]> balancingMap = new Dictionary<SkillType, AnimationBalancingConfig[]>();

		private ConfigEntry<T> config<[<609ca11b-4288-43fc-a754-b58364673409>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			configSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<609ca11b-4288-43fc-a754-b58364673409>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		private static void InitSwordAnimation()
		{
			replacementMap["DWswords"] = new Dictionary<string, string>
			{
				["fight idle"] = "BlockExternal",
				["Block idle"] = "BlockExternal"
			};
			foreach (KeyValuePair<string, int> item in attackMap)
			{
				replacementMap["DWswords"][item.Key] = ((item.Value == 0) ? "DualSwordsSpecial" : $"Attack{item.Value}External");
			}
		}

		private static void InitAxesAnimation()
		{
			replacementMap["DWaxes"] = new Dictionary<string, string>
			{
				["fight idle"] = "BlockExternal",
				["Block idle"] = "BlockExternal"
			};
			foreach (KeyValuePair<string, int> item in attackMap)
			{
				replacementMap["DWaxes"][item.Key] = ((item.Value == 0) ? "DualAxesSpecial" : $"Attack{item.Value}External");
			}
		}

		public void Awake()
		{
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Expected O, but got Unknown
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Expected O, but got Unknown
			//IL_06f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0540: Unknown result type (might be due to invalid IL or missing references)
			//IL_0528: Unknown result type (might be due to invalid IL or missing references)
			//IL_0563: Unknown result type (might be due to invalid IL or missing references)
			//IL_056e: Expected O, but got Unknown
			//IL_057d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0582: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0607: Expected O, but got Unknown
			//IL_0616: Unknown result type (might be due to invalid IL or missing references)
			//IL_061b: Unknown result type (might be due to invalid IL or missing references)
			//IL_066c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0654: Unknown result type (might be due to invalid IL or missing references)
			//IL_068f: Unknown result type (might be due to invalid IL or missing references)
			//IL_069a: Expected O, but got Unknown
			List<Skill> skills = new List<Skill>();
			Skill skill = new Skill("Dual Axes", "dualaxes.png");
			skill.Description.English("Increases the damage done with your left hand, when dual wielding axes.");
			skill.Configurable = false;
			skills.Add(skill);
			skill = new Skill("Dual Clubs", "dualclubs.png");
			skill.Description.English("Increases the damage done with your left hand, when dual wielding clubs.");
			skill.Configurable = false;
			skills.Add(skill);
			skill = new Skill("Dual Knives", "dualknives.png");
			skill.Description.English("Increases the damage done with your left hand, when dual wielding knives.");
			skill.Configurable = false;
			skills.Add(skill);
			skill = new Skill("Dual Swords", "dualswords.png");
			skill.Description.English("Increases the damage done with your left hand, when dual wielding swords.");
			skill.Configurable = false;
			skills.Add(skill);
			skill = new Skill("Dual Offhand", "dualswords.png");
			skill.Description.English("Increases the damage done with your left hand, when dual wielding.");
			skill.Configurable = false;
			skills.Add(skill);
			serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			dualWieldExclusionList = config("1 - General", "Dual Wield Exclusion", "", "List prefab names of weapons that should be excluded from being dual-wielded. Comma separated.");
			dualWieldExclusionList.SettingChanged += UpdateExclusionList;
			experienceGainFactor = config("1 - General", "Dual Wield Experience Factor", 1f, new ConfigDescription("Factor for experience gained for the dual wielding skills.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
			experienceGainFactor.SettingChanged += [<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)] (object _, EventArgs _) =>
			{
				foreach (Skill item in skills)
				{
					item.SkillGainFactor = experienceGainFactor.Value;
				}
			};
			foreach (Skill item2 in skills)
			{
				item2.SkillGainFactor = experienceGainFactor.Value;
			}
			experienceLoss = config("1 - General", "Skill Experience Loss", 5, new ConfigDescription("How much experience to lose in the dual wielding skills on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			experienceLoss.SettingChanged += [<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)] (object _, EventArgs _) =>
			{
				foreach (Skill item3 in skills)
				{
					item3.SkillLoss = experienceLoss.Value;
				}
			};
			foreach (Skill item4 in skills)
			{
				item4.SkillLoss = experienceLoss.Value;
			}
			singleOffhandSkill = config("1 - General", "Single Offhand Skill", Toggle.Off, new ConfigDescription("If on, all weapon types share a single offhand skill.", (AcceptableValueBase)null, Array.Empty<object>()));
			singleOffhandSkill.SettingChanged += [<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)] (object _, EventArgs _) =>
			{
				ToggleOffhandSkill();
			};
			ToggleOffhandSkill();
			asset = GetAssetBundle("dwanimations");
			ExternalAnimations["Attack1External"] = asset.LoadAsset<AnimationClip>("Attack1");
			ExternalAnimations["Attack2External"] = asset.LoadAsset<AnimationClip>("Attack2");
			ExternalAnimations["Attack3External"] = asset.LoadAsset<AnimationClip>("Attack3");
			ExternalAnimations["BlockExternal"] = asset.LoadAsset<AnimationClip>("DWblock");
			ExternalAnimations["DualSwordsSpecial"] = asset.LoadAsset<AnimationClip>("DWspecial");
			ExternalAnimations["DualAxesSpecial"] = asset.LoadAsset<AnimationClip>("DWspecial2");
			attackMap["Sword-Attack-R4"] = 0;
			attackMap["Knife JumpAttack"] = 0;
			attackMap["MaceAltAttack"] = 0;
			attackMap["Attack1"] = 1;
			attackMap["Attack2"] = 2;
			attackMap["Attack3"] = 3;
			attackMap["Axe Secondary Attack"] = 0;
			attackMap["axe_swing"] = 1;
			attackMap["Axe combo 2"] = 2;
			attackMap["Axe combo 3"] = 3;
			attackMap["knife_slash0"] = 1;
			attackMap["knife_slash1"] = 2;
			attackMap["knife_slash2"] = 3;
			InitSwordAnimation();
			InitAxesAnimation();
			foreach (KeyValuePair<SkillType, AnimationBalancing[]> item5 in balancingMapDefault)
			{
				AnimationBalancingConfig[] array = new AnimationBalancingConfig[4];
				for (int i = 0; i < item5.Value.Length; i++)
				{
					AnimationBalancing animationBalancing = item5.Value[i];
					string text = ((i == 0) ? "Special attack" : $"Attack {i}");
					int num = i;
					AnimationBalancingConfig animationBalancingConfig = default(AnimationBalancingConfig);
					SkillType key = item5.Key;
					animationBalancingConfig.damage = config("2 - " + ((object)(SkillType)(ref key)).ToString(), text + " - Damage", animationBalancing.damage * 100f, new ConfigDescription((i == 0) ? $"The damage dealt by the special attack with {item5.Key} as a percentage of the weapon damage." : $"The damage dealt by the {i}. attack of the {item5.Key} attack combo as a percentage of the weapon damage.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 500f), Array.Empty<object>()));
					key = item5.Key;
					animationBalancingConfig.speed = config("2 - " + ((object)(SkillType)(ref key)).ToString(), text + " - Speed", animationBalancing.speed * 100f, new ConfigDescription((i == 0) ? $"The attack speed of the special attack with {item5.Key} as a percentage." : $"The attack speed of the {i}. attack of the {item5.Key} attack combo. Provided as a percentage.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 300f), Array.Empty<object>()));
					key = item5.Key;
					animationBalancingConfig.stamina = config("2 - " + ((object)(SkillType)(ref key)).ToString(), text + " - Stamina", animationBalancing.stamina, new ConfigDescription((i == 0) ? $"The stamina usage of the special attack with {item5.Key}." : $"The stamina usage of the {i}. attack of the {item5.Key} attack combo.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 200f), Array.Empty<object>()));
					array[num] = animationBalancingConfig;
				}
				balancingMap[item5.Key] = array;
			}
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			new Harmony("org.bepinex.plugins.dualwield").PatchAll(executingAssembly);
			UpdateExclusionList(null, null);
			AnimationSpeedManager.Add(delegate(Character character, double speed)
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Expected O, but got Unknown
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0091: Invalid comparison between Unknown and I4
				//IL_0095: Unknown result type (might be due to invalid IL or missing references)
				//IL_009b: Invalid comparison between Unknown and I4
				//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
				if (!character.IsPlayer() || !character.InAttack())
				{
					return speed;
				}
				Player val = (Player)character;
				if (((Humanoid)val).m_currentAttack == null)
				{
					return speed;
				}
				AnimatorClipInfo[] currentAnimatorClipInfo = character.m_animator.GetCurrentAnimatorClipInfo(0);
				if (currentAnimatorClipInfo.Length == 0)
				{
					return speed;
				}
				if (!attackMap.TryGetValue(((Object)((AnimatorClipInfo)(ref currentAnimatorClipInfo[0])).clip).name, out var value))
				{
					return speed;
				}
				float num2 = 1f;
				SharedData val2 = sharedData(((Humanoid)val).m_visEquipment.m_currentLeftItemHash);
				if (val2 != null)
				{
					SharedData val3 = sharedData(((Humanoid)val).m_visEquipment.m_currentRightItemHash);
					if (val3 != null && (int)val2.m_itemType == 3 && (int)val3.m_itemType == 3 && balancingMap.TryGetValue(val3.m_skillType, out var value2))
					{
						num2 = value2[value].speed.Value / 100f;
					}
				}
				return speed * (double)num2;
			}, 200);
			[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(2)]
			static SharedData sharedData(int hash)
			{
				if (hash != 0)
				{
					GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(hash);
					if (itemPrefab == null)
					{
						return null;
					}
					return itemPrefab.GetComponent<ItemDrop>()?.m_itemData.m_shared;
				}
				return null;
			}
		}

		private static void ToggleOffhandSkill()
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: 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_004c: 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)
			skillMap.Clear();
			if (singleOffhandSkill.Value == Toggle.On)
			{
				skillMap.Add((SkillType)1, Skill.fromName("Dual Offhand"));
				skillMap.Add((SkillType)2, Skill.fromName("Dual Offhand"));
				skillMap.Add((SkillType)3, Skill.fromName("Dual Offhand"));
				skillMap.Add((SkillType)7, Skill.fromName("Dual Offhand"));
			}
			else
			{
				skillMap.Add((SkillType)7, Skill.fromName("Dual Axes"));
				skillMap.Add((SkillType)3, Skill.fromName("Dual Clubs"));
				skillMap.Add((SkillType)2, Skill.fromName("Dual Knives"));
				skillMap.Add((SkillType)1, Skill.fromName("Dual Swords"));
			}
		}

		[<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(2)]
		private static void UpdateExclusionList(object sender, EventArgs e)
		{
			DualWieldExclusion.Clear();
			string[] array = dualWieldExclusionList.Value.Split(new char[1] { ',' });
			foreach (string text in array)
			{
				DualWieldExclusion.Add(text.Trim());
			}
		}

		private static AssetBundle GetAssetBundle(string filename)
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			string name = executingAssembly.GetManifestResourceNames().Single([<bed75460-308b-41d8-8216-3dc8a843575b>NullableContext(0)] (string str) => str.EndsWith(filename));
			using Stream stream = executingAssembly.GetManifestResourceStream(name);
			return AssetBundle.LoadFromStream(stream);
		}

		private static RuntimeAnimatorController MakeAOC(Dictionary<string, string> replacement, RuntimeAnimatorController ORIGINAL)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			AnimatorOverrideController val = new AnimatorOverrideController(ORIGINAL);
			List<KeyValuePair<AnimationClip, AnimationClip>> list = new List<KeyValuePair<AnimationClip, AnimationClip>>();
			AnimationClip[] animationClips = ((RuntimeAnimatorController)val).animationClips;
			foreach (AnimationClip val2 in animationClips)
			{
				string name = ((Object)val2).name;
				if (replacement.TryGetValue(name, out var value))
				{
					AnimationClip val3 = Object.Instantiate<AnimationClip>(ExternalAnimations[value]);
					((Object)val3).name = name;
					list.Add(new KeyValuePair<AnimationClip, AnimationClip>(val2, val3));
				}
				else
				{
					list.Add(new KeyValuePair<AnimationClip, AnimationClip>(val2, val2));
				}
			}
			val.ApplyOverrides((IList<KeyValuePair<AnimationClip, AnimationClip>>)list);
			return (RuntimeAnimatorController)(object)val;
		}

		private static void FastReplaceRAC(Player player, RuntimeAnimatorController replace)
		{
			if (!((Object)(object)((Character)player).m_animator.runtimeAnimatorController == (Object)(object)replace))
			{
				((Character)player).m_animator.runtimeAnimatorController = replace;
				((Character)player).m_animator.Update(Time.deltaTime);
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[<2b550267-ccb8-434d-84a4-44d01aac047c>Embedded]
	[CompilerGenerated]
	internal sealed class <2b550267-ccb8-434d-84a4-44d01aac047c>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<2b550267-ccb8-434d-84a4-44d01aac047c>Embedded]
	[CompilerGenerated]
	internal sealed class <d2b0d9c7-451b-45e8-b94e-204254fe16ef>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <d2b0d9c7-451b-45e8-b94e-204254fe16ef>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <d2b0d9c7-451b-45e8-b94e-204254fe16ef>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[<2b550267-ccb8-434d-84a4-44d01aac047c>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <37698de1-01d5-448f-b7fa-bc865853fde7>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <37698de1-01d5-448f-b7fa-bc865853fde7>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[<2b550267-ccb8-434d-84a4-44d01aac047c>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class <7bc13511-6d1c-42c9-a70d-6babe1471fef>RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public <7bc13511-6d1c-42c9-a70d-6babe1471fef>RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
	[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		public object LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
	[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
	[PublicAPI]
	internal class SyncedConfigEntry<[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)] T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
	[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(2)]
	internal abstract class CustomSyncedValueBase
	{
		public object LocalBaseValue;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(1)]
		public readonly string Identifier;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(1)]
		public readonly Type Type;

		private object boxedValue;

		protected bool localIsOwner;

		public object BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action ValueChanged;

		[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
	[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
	internal sealed class CustomSyncedValue<[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)] T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
	[PublicAPI]
	[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)]
		private static class SnatchCurrentlyHandlingRPC
		{
			[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
			public static ZRpc currentRpc;

			[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)]
		internal static class RegisterRPCPatch
		{
			[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)]
		private static class RegisterClientRPCPatch
		{
			[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)]
		private class ParsedConfigs
		{
			[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>();

			[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix([<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
			public object value;
		}

		[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)]
		private static class PreventConfigRereadChangingValues
		{
			[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		public string DisplayName;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		public string CurrentVersion;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		public string MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		private OwnConfigEntryBase lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 1, 0, 1 })]
		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		[method: <37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(2)]
		[field: <d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		public event Action<bool> SourceOfTruthChanged;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		[method: <37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(2)]
		[field: <d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		private event Action lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)] T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += [<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)] T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += [<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (object _, EventArgs _) =>
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(([<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 0, 1 })] KeyValuePair<long, string> kv) =>
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out var value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		[return: <d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		private static OwnConfigEntryBase configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		[return: <d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 2, 1 })]
		public static SyncedConfigEntry<T> ConfigData<[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)] T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)] T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage([<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 2, 1 })] IEnumerable<ConfigEntryBase> configs = null, [<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 2, 1 })] IEnumerable<CustomSyncedValueBase> customValues = null, [<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 2, 1 })] IEnumerable<PackageEntry> packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, [<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)] object value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(1)]
	[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(0)]
	[PublicAPI]
	[HarmonyPatch]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		private string displayName;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		private string currentVersion;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		private string minimumRequiredVersion;

		public bool ModRequired = true;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		private string ReceivedCurrentVersion;

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		private string ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		[<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)]
		private ConfigSync ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error([<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(2)] ZRpc rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, [<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(new byte[] { 2, 1, 1 })] Action<ZRpc, ZPackage> original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (ZRpc rpc, [<d2b0d9c7-451b-45e8-b94e-204254fe16ef>Nullable(1)] ZPackage pkg) =>
				{
					CheckVersion(rpc, pkg, action);
				}));
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		[HarmonyPrefix]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy([<37698de1-01d5-448f-b7fa-bc865853fde7>NullableContext(0)] (KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<6e5788b8-36cf-46fb-8ecd-dad57269b732>Embedded]
	internal sealed class <6e5788b8-36cf-46fb-8ecd-dad57269b732>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<6e5788b8-36cf-46fb-8ecd-dad57269b732>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <bb6a3867-4b90-42f6-96d2-9a57b61dcf65>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <bb6a3867-4b90-42f6-96d2-9a57b61dcf65>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <bb6a3867-4b90-42f6-96d2-9a57b61dcf65>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<6e5788b8-36cf-46fb-8ecd-dad57269b732>Embedded]
	internal sealed class <f25e9aa0-de79-496d-b56d-08c41612c5fa>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <f25e9aa0-de79-496d-b56d-08c41612c5fa>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace SkillManager
{
	[<bb6a3867-4b90-42f6-96d2-9a57b61dcf65>Nullable(0)]
	[<f25e9aa0-de79-496d-b56d-08c41612c5fa>NullableContext(1)]
	[PublicAPI]
	internal class Skill
	{
		[<bb6a3867-4b90-42f6-96d2-9a57b61dcf65>Nullable(0)]
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				string key = localizations.FirstOrDefault([<f25e9aa0-de79-496d-b56d-08c41612c5fa>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance);
				}
			}

			public static Localization ForLanguage([<bb6a3867-4b90-42f6-96d2-9a57b61dcf65>Nullable(2)] string language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[<bb6a3867-4b90-42f6-96d2-9a57b61dcf65>Nullable(0)]
		[PublicAPI]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", ke

BepInEx/plugins/Smoothbrain-Farming/Farming.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Guid("783AACE5-C2D7-4FDD-9A56-59E2A3D87389")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("Farming")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/Farming")]
[assembly: AssemblyTitle("Farming")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: <0cde21f6-6839-46d3-961b-afbb16e1581a>RefSafetyRules(11)]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<7db33b1b-d591-4637-8d70-6c5d74b7e580>Embedded]
	internal sealed class <7db33b1b-d591-4637-8d70-6c5d74b7e580>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<7db33b1b-d591-4637-8d70-6c5d74b7e580>Embedded]
	internal sealed class <b5a5032b-4025-409e-a888-abb6bd5abd39>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <b5a5032b-4025-409e-a888-abb6bd5abd39>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <b5a5032b-4025-409e-a888-abb6bd5abd39>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<7db33b1b-d591-4637-8d70-6c5d74b7e580>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[<7db33b1b-d591-4637-8d70-6c5d74b7e580>Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class <0cde21f6-6839-46d3-961b-afbb16e1581a>RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public <0cde21f6-6839-46d3-961b-afbb16e1581a>RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Farming
{
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	[BepInPlugin("org.bepinex.plugins.farming", "Farming", "2.1.9")]
	[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
	[<b5a5032b-4025-409e-a888-abb6bd5abd39>Nullable(0)]
	public class Farming : BaseUnityPlugin
	{
		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public bool? ShowRangeAsPercent;
		}

		[HarmonyPatch(typeof(Plant), "GetGrowTime")]
		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		public class MakePlantsGrowFaster
		{
			[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
			private static void Postfix(Plant __instance, ref float __result)
			{
				__result /= 1f + __instance.m_nview.GetZDO().GetFloat("Farming Skill Level", 0f) * (growSpeedFactor.Value - 1f);
			}
		}

		[HarmonyPatch(typeof(Player), "PlacePiece")]
		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		public class PlayerIsPlantingPlants
		{
			public static bool planting;

			private static void Prefix()
			{
				planting = true;
			}

			private static void Finalizer()
			{
				planting = false;
			}
		}

		[HarmonyPatch(typeof(Plant), "Awake")]
		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		public class SaveSkillLevel
		{
			[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
			private static void Postfix(Plant __instance)
			{
				//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
				if (PlayerIsPlantingPlants.planting)
				{
					__instance.m_nview.GetZDO().Set("Farming Skill Level", ((Character)(object)Player.m_localPlayer).GetSkillFactor("Farming"));
					((Character)(object)Player.m_localPlayer).RaiseSkill("Farming");
				}
				if (ignoreBiomeLevel.Value > 0)
				{
					ZNetView nview = __instance.m_nview;
					float? obj;
					if (nview == null)
					{
						obj = null;
					}
					else
					{
						ZDO zDO = nview.GetZDO();
						obj = ((zDO != null) ? new float?(zDO.GetFloat("Farming Skill Level", 0f)) : null);
					}
					if (obj >= (float)ignoreBiomeLevel.Value / 100f)
					{
						__instance.m_biome = (Biome)(-1);
					}
				}
			}
		}

		[HarmonyPatch(typeof(Plant), "Grow")]
		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		public class SaveSkillFactor
		{
			public static float skillFactor;

			[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
			private static void Prefix(Plant __instance)
			{
				skillFactor = __instance.m_nview.GetZDO().GetFloat("Farming Skill Level", 0f);
			}

			private static void Finalizer()
			{
				skillFactor = 0f;
			}
		}

		[HarmonyPatch(typeof(Pickable), "Awake")]
		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		public class IncreaseItemYield
		{
			[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
			private static void Postfix(Pickable __instance)
			{
				ZNetView nview = __instance.m_nview;
				ZDO val = ((nview != null) ? nview.GetZDO() : null);
				if (val != null)
				{
					int num = val.GetInt("Farming Yield Multiplier", 1);
					if (Random.Range(0f, 1f) < SaveSkillFactor.skillFactor)
					{
						int num2 = Mathf.FloorToInt(cropYieldFactor.Value);
						num = num2 + ((Random.Range(0f, 1f) < cropYieldFactor.Value - (float)num2) ? 1 : 0);
						val.Set("Farming Yield Multiplier", num);
					}
					__instance.m_amount *= num;
				}
			}
		}

		[HarmonyPatch(typeof(Plant), "GetHoverText")]
		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		private static class DisplayProgress
		{
			[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
			private static void Postfix(Plant __instance, ref string __result)
			{
				if (showPlantProgressLevel.Value > 0 && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Farming") >= (float)showPlantProgressLevel.Value / 100f)
				{
					__result += $"\n{Math.Min(100.0, Math.Round(__instance.TimeSincePlanted() / (double)__instance.GetGrowTime() * 100.0))}% grown";
				}
			}
		}

		private const string ModName = "Farming";

		private const string ModVersion = "2.1.9";

		private const string ModGUID = "org.bepinex.plugins.farming";

		private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.farming")
		{
			DisplayName = "Farming",
			CurrentVersion = "2.1.9",
			MinimumRequiredVersion = "2.1.9"
		};

		private static ConfigEntry<Toggle> serverConfigLocked = null;

		private static ConfigEntry<float> growSpeedFactor = null;

		private static ConfigEntry<float> cropYieldFactor = null;

		private static ConfigEntry<int> ignoreBiomeLevel = null;

		private static ConfigEntry<float> experienceGainedFactor = null;

		private static ConfigEntry<int> experienceLoss = null;

		public static ConfigEntry<KeyboardShortcut> plantModeToggleHotkey = null;

		public static ConfigEntry<int> increasePlantAmount = null;

		public static ConfigEntry<int> increaseHarvestAmount = null;

		public static ConfigEntry<Toggle> randomRotation = null;

		public static ConfigEntry<KeyboardShortcut> snapModeToggleHotkey = null;

		private static ConfigEntry<int> showPlantProgressLevel = null;

		public static ConfigEntry<int> staminaReductionPerLevel = null;

		private static Skill farming = null;

		private ConfigEntry<T> config<[<b5a5032b-4025-409e-a888-abb6bd5abd39>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			configSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<b5a5032b-4025-409e-a888-abb6bd5abd39>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Expected O, but got Unknown
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Expected O, but got Unknown
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Expected O, but got Unknown
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Expected O, but got Unknown
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Expected O, but got Unknown
			//IL_0333: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Expected O, but got Unknown
			//IL_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b0: Expected O, but got Unknown
			//IL_03ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_03da: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Expected O, but got Unknown
			//IL_03f5: Unknown result type (might be due to invalid IL or missing references)
			farming = new Skill("Farming", "farming.png");
			farming.Description.English("Reduces the time required for plants to grow and increases item yield for harvesting plants.");
			farming.Name.German("Landwirtschaft");
			farming.Description.German("Reduziert die Zeit, bis Pflanzen wachsen und erhöht die Ausbeute beim Ernten von Pflanzen.");
			farming.Configurable = false;
			serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			growSpeedFactor = config("2 - Crops", "Grow Speed Factor", 3f, new ConfigDescription("Speed factor for crop growth at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			cropYieldFactor = config("2 - Crops", "Crop Yield Factor", 2f, new ConfigDescription("Item yield factor for crops at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			showPlantProgressLevel = config("2 - Crops", "Show Progress Level", 30, new ConfigDescription("Required skill level to see the progress of planted crops. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			ignoreBiomeLevel = config("2 - Crops", "Ignore Biome Level", 50, new ConfigDescription("Required skill level to ignore the required biome of planted crops. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			increasePlantAmount = config("2 - Crops", "Plant Increase Interval", 20, new ConfigDescription("Level interval to increase the number of crops planted at the same time. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			increaseHarvestAmount = config("2 - Crops", "Harvest Increase Interval", 20, new ConfigDescription("Level interval to increase the radius harvested at the same time. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			staminaReductionPerLevel = config("2 - Crops", "Stamina Reduction per Level", 1, new ConfigDescription("Reduces the stamina usage while planting and harvesting your crops. Percentage stamina reduction per level. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			randomRotation = config("2 - Crops", "Random Rotation", Toggle.Off, new ConfigDescription("Rotates each crop randomly. Some people say this looks more natural.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false);
			randomRotation.SettingChanged += [<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)] (object _, EventArgs _) =>
			{
				MassPlant.determineGhostRotations();
			};
			experienceGainedFactor = config("3 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the farming skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>()));
			experienceGainedFactor.SettingChanged += [<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)] (object _, EventArgs _) =>
			{
				farming.SkillGainFactor = experienceGainedFactor.Value;
			};
			farming.SkillGainFactor = experienceGainedFactor.Value;
			experienceLoss = config("3 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the farming skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			experienceLoss.SettingChanged += [<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)] (object _, EventArgs _) =>
			{
				farming.SkillLoss = experienceLoss.Value;
			};
			farming.SkillLoss = experienceLoss.Value;
			plantModeToggleHotkey = config<KeyboardShortcut>("3 - Other", "Toggle Mass Plant Hotkey", new KeyboardShortcut((KeyCode)304, Array.Empty<KeyCode>()), new ConfigDescription("Shortcut to press to toggle between the single plant mode and the mass plant mode. Please note that you have to stand still, to toggle this.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false);
			snapModeToggleHotkey = config<KeyboardShortcut>("3 - Other", "Toggle Snapping Hotkey", new KeyboardShortcut((KeyCode)306, Array.Empty<KeyCode>()), new ConfigDescription("Shortcut to press to toggle between snapping mode and not snapping. Please note that you have to stand still, to toggle this.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false);
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			new Harmony("org.bepinex.plugins.farming").PatchAll(executingAssembly);
		}
	}
	public static class MassHarvest
	{
		[HarmonyPatch(typeof(Pickable), "Interact")]
		private class HarvestNearbyPickables
		{
			private static bool isPicked = false;

			private static readonly int itemMask = LayerMask.NameToLayer("item");

			private static readonly int plantMask = LayerMask.GetMask(new string[2] { "piece_nonsolid", "item" });

			[HarmonyPriority(300)]
			[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
			private static void Postfix(Pickable __instance)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				if (isPicked || Farming.increaseHarvestAmount.Value == 0 || !isFarmingPickable(__instance))
				{
					return;
				}
				isPicked = true;
				Collider[] array = Physics.OverlapSphere(((Component)__instance).transform.position, (float)(int)(((Character)(object)Player.m_localPlayer).GetSkillFactor("Farming") * 100f / (float)Farming.increaseHarvestAmount.Value) * 1.5f, plantMask);
				foreach (Collider val in array)
				{
					object obj = ((Component)val).GetComponent<Pickable>();
					if (obj == null)
					{
						Transform parent = ((Component)val).transform.parent;
						obj = ((parent != null) ? ((Component)parent).GetComponent<Pickable>() : null);
					}
					Pickable val2 = (Pickable)obj;
					if (val2 != null && (Object)(object)val2 != (Object)(object)__instance && isFarmingPickable(val2))
					{
						val2.Interact((Humanoid)(object)Player.m_localPlayer, false, false);
					}
				}
				isPicked = false;
				[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
				static bool isFarmingPickable(Pickable pickable)
				{
					if (((Component)pickable).gameObject.layer == itemMask)
					{
						return pickable.m_amount > 1;
					}
					return true;
				}
			}
		}
	}
	[<b5a5032b-4025-409e-a888-abb6bd5abd39>Nullable(0)]
	[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
	[HarmonyPatch]
	public class MassPlant
	{
		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "UpdatePlacement")]
		private static class ChangeStaminaUsage
		{
			private static float stamina;

			[<b5a5032b-4025-409e-a888-abb6bd5abd39>Nullable(2)]
			private static ItemData item;

			[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(1)]
			private static void Prefix(Player __instance)
			{
				if (((Humanoid)__instance).GetRightItem()?.m_shared.m_name == "$item_cultivator")
				{
					item = ((Humanoid)__instance).GetRightItem();
					stamina = item.m_shared.m_attack.m_attackStamina;
					Attack attack = item.m_shared.m_attack;
					attack.m_attackStamina *= Mathf.Max(0f, 1f - ((Character)(object)__instance).GetSkillFactor("Farming") * (float)Farming.staminaReductionPerLevel.Value);
				}
				placeSuccessful = false;
			}

			private static void Finalizer()
			{
				if (item != null)
				{
					item.m_shared.m_attack.m_attackStamina = stamina;
					item = null;
				}
			}
		}

		[<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)]
		private struct PlantingCell
		{
			public Vector3 pos;

			public PlacementStatus valid;
		}

		private static Vector3 ghostCenterPosition;

		private static Quaternion ghostRotation;

		private static float[] randomGhostRotations = new float[1];

		private static Piece placedPiece = null;

		private static List<PlantingCell> placements = new List<PlantingCell>();

		private static bool placeSuccessful = false;

		private static bool massPlanting = true;

		private static bool snapping = true;

		private const float plantSpacing = 1.8f;

		private static readonly int _plantSpaceMask = LayerMask.GetMask(new string[5] { "Default", "static_solid", "Default_small", "piece", "piece_nonsolid" });

		private static bool invalidatedGhosts = true;

		[<b5a5032b-4025-409e-a888-abb6bd5abd39>Nullable(new byte[] { 1, 2 })]
		private static GameObject[] _placementGhosts = (GameObject[])(object)new GameObject[1];

		private static readonly Piece _fakeResourcePiece;

		private static readonly int RippleDistance;

		private static readonly int ValueNoise;

		private static int GridWidth()
		{
			return 1 + Mathf.FloorToInt(((Character)(object)Player.m_localPlayer).GetSkillFactor("Farming") * (100f / (float)Farming.increasePlantAmount.Value)) / 2;
		}

		private static int GridHeight()
		{
			return 1 + Mathf.FloorToInt(Mathf.Min(((Character)(object)Player.m_localPlayer).GetSkillFactor("Farming"), 0.999f) * (100f / (float)Farming.increasePlantAmount.Value) + 1f) / 2;
		}

		[HarmonyPatch(typeof(Player), "PlacePiece")]
		[HarmonyPostfix]
		public static void PlacePiecePostfix(Player __instance, ref bool __result, Piece piece)
		{
			placeSuccessful = __result;
			if (__result)
			{
				placedPiece = piece;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "UpdatePlacement")]
		public static void UpdatePlacementPostfix(Player __instance, bool takeInput, float dt)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			if (Farming.increasePlantAmount.Value == 0 || !placeSuccessful || !Object.op_Implicit((Object)(object)((Component)placedPiece).gameObject.GetComponent<Plant>()) || !massPlanting)
			{
				return;
			}
			Heightmap val = Heightmap.FindHeightmap(ghostCenterPosition);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			for (int i = 1; i < placements.Count; i++)
			{
				Vector3 pos = placements[i].pos;
				if (placedPiece.m_cultivatedGroundOnly && !val.IsCultivated(pos))
				{
					continue;
				}
				if (!__instance.m_noPlacementCost && !__instance.HaveRequirements(placedPiece, (RequirementMode)0))
				{
					break;
				}
				if ((int)placements[i].valid != 0)
				{
					continue;
				}
				try
				{
					Farming.PlayerIsPlantingPlants.planting = true;
					Quaternion val2 = Quaternion.Euler(new Vector3(0f, randomGhostRotations[i], 0f)) * ghostRotation;
					GameObject val3 = Object.Instantiate<GameObject>(((Component)placedPiece).gameObject, pos, val2);
					Piece component = val3.GetComponent<Piece>();
					if (Object.op_Implicit((Object)(object)component))
					{
						component.SetCreator(__instance.GetPlayerID());
					}
					placedPiece.m_placeEffect.Create(pos, val2, val3.transform, 1f, -1);
				}
				finally
				{
					Farming.PlayerIsPlantingPlants.planting = false;
				}
				Game.instance.GetPlayerProfile().IncrementStat((PlayerStatType)2, 1f);
				__instance.ConsumeResources(placedPiece.m_resources, 0, -1);
			}
		}

		private static List<PlantingCell> BuildPlantingGridPositions(Vector3 originPos, Plant placedPlant, Quaternion rotation)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_065b: 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_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0674: Unknown result type (might be due to invalid IL or missing references)
			//IL_0679: Unknown result type (might be due to invalid IL or missing references)
			//IL_067b: Unknown result type (might be due to invalid IL or missing references)
			//IL_067d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0686: Unknown result type (might be due to invalid IL or missing references)
			//IL_0692: Unknown result type (might be due to invalid IL or missing references)
			//IL_0694: Unknown result type (might be due to invalid IL or missing references)
			//IL_0697: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06de: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_063a: Unknown result type (might be due to invalid IL or missing references)
			//IL_063c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0373: Unknown result type (might be due to invalid IL or missing references)
			//IL_0307: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0623: Unknown result type (might be due to invalid IL or missing references)
			//IL_0628: Unknown result type (might be due to invalid IL or missing references)
			//IL_062a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0402: Unknown result type (might be due to invalid IL or missing references)
			//IL_040b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0410: Unknown result type (might be due to invalid IL or missing references)
			//IL_041e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0420: Unknown result type (might be due to invalid IL or missing references)
			//IL_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_042b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0430: Unknown result type (might be due to invalid IL or missing references)
			//IL_043e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0440: Unknown result type (might be due to invalid IL or missing references)
			//IL_0442: Unknown result type (might be due to invalid IL or missing references)
			//IL_0444: Unknown result type (might be due to invalid IL or missing references)
			//IL_0449: Unknown result type (might be due to invalid IL or missing references)
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_045a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Unknown result type (might be due to invalid IL or missing references)
			//IL_046a: Unknown result type (might be due to invalid IL or missing references)
			//IL_046f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0499: Unknown result type (might be due to invalid IL or missing references)
			//IL_049e: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0481: Unknown result type (might be due to invalid IL or missing references)
			//IL_0483: Unknown result type (might be due to invalid IL or missing references)
			//IL_0485: Unknown result type (might be due to invalid IL or missing references)
			//IL_0487: Unknown result type (might be due to invalid IL or missing references)
			//IL_048c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0491: Unknown result type (might be due to invalid IL or missing references)
			//IL_0505: Unknown result type (might be due to invalid IL or missing references)
			//IL_050a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0518: Unknown result type (might be due to invalid IL or missing references)
			//IL_051a: Unknown result type (might be due to invalid IL or missing references)
			//IL_051c: Unknown result type (might be due to invalid IL or missing references)
			//IL_051e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0523: Unknown result type (might be due to invalid IL or missing references)
			//IL_052f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0534: Unknown result type (might be due to invalid IL or missing references)
			//IL_0542: Unknown result type (might be due to invalid IL or missing references)
			//IL_0544: Unknown result type (might be due to invalid IL or missing references)
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0573: Unknown result type (might be due to invalid IL or missing references)
			//IL_0578: Unknown result type (might be due to invalid IL or missing references)
			//IL_0586: Unknown result type (might be due to invalid IL or missing references)
			//IL_0588: Unknown result type (might be due to invalid IL or missing references)
			//IL_058a: Unknown result type (might be due to invalid IL or missing references)
			//IL_058c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0591: Unknown result type (might be due to invalid IL or missing references)
			//IL_059d: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_055b: Unknown result type (might be due to invalid IL or missing references)
			//IL_055d: Unknown result type (might be due to invalid IL or missing references)
			//IL_055f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0561: Unknown result type (might be due to invalid IL or missing references)
			//IL_0566: Unknown result type (might be due to invalid IL or missing references)
			//IL_056b: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d9: Unknown result type (might be due to invalid IL or missing references)
			float num = placedPlant.m_growRadius * 2f;
			int num2 = ((!massPlanting) ? 1 : GridHeight());
			int num3 = ((!massPlanting) ? 1 : GridWidth());
			int num4 = num2;
			int num5 = num3;
			if (num3 == 1)
			{
				num3 = 3;
			}
			if (num2 == 1)
			{
				num2 = 3;
			}
			List<Vector3> list = new List<Vector3>(num3 * num2);
			Vector3 val = rotation * Vector3.left * num;
			Vector3 val2 = rotation * Vector3.forward * num;
			Vector3 val3 = originPos - val2 * (float)(num3 - 1) / 2f - val * (float)(num2 - 1) / 2f;
			for (int j = 0; j < num3; j++)
			{
				Vector3 val4 = val3;
				for (int k = 0; k < num2; k++)
				{
					list.Add(val4);
					val4 += val;
				}
				val3 += val2;
			}
			Vector3 val6;
			if (snapping)
			{
				int mask = LayerMask.GetMask(new string[1] { "piece_nonsolid" });
				HashSet<Vector3> snappingPositions = new HashSet<Vector3>();
				float num6 = float.MaxValue;
				foreach (Vector3 item in list)
				{
					Collider[] array = Physics.OverlapSphere(item, num * 1.8f * 1.5f, mask);
					foreach (Collider val5 in array)
					{
						if (Object.op_Implicit((Object)(object)((Component)val5).GetComponent<Plant>()) || Object.op_Implicit((Object)(object)((Component)val5).GetComponent<Pickable>()))
						{
							Vector3 position = ((Component)val5).transform.position;
							HashSet<Vector3> hashSet = snappingPositions;
							val6 = position;
							val6.y = 0f;
							hashSet.Add(val6);
							num6 = Mathf.Min(num6, Utils.DistanceXZ(item, position));
						}
					}
				}
				if (num6 < num * 1.8f)
				{
					Quaternion val7 = Quaternion.identity;
					if (snappingPositions.Count > 1 && list.Count > 1)
					{
						Vector3 firstSnapPos = snappingPositions.OrderBy(delegate(Vector3 p)
						{
							//IL_0007: Unknown result type (might be due to invalid IL or missing references)
							//IL_0008: Unknown result type (might be due to invalid IL or missing references)
							//IL_0036: Unknown result type (might be due to invalid IL or missing references)
							//IL_0041: Unknown result type (might be due to invalid IL or missing references)
							//IL_0046: Unknown result type (might be due to invalid IL or missing references)
							//IL_004b: Unknown result type (might be due to invalid IL or missing references)
							float num13 = snappingPositions.Where((Vector3 s) => s != p).Min((Vector3 s) => Utils.DistanceXZ(s, p));
							Vector3 val20 = p - originPos;
							return num13 + ((Vector3)(ref val20)).magnitude / 1000f;
						}).First();
						Vector3 val8 = snappingPositions.Where((Vector3 p) => p != firstSnapPos).OrderBy(delegate(Vector3 p)
						{
							//IL_0001: Unknown result type (might be due to invalid IL or missing references)
							//IL_0006: Unknown result type (might be due to invalid IL or missing references)
							//IL_000c: Unknown result type (might be due to invalid IL or missing references)
							//IL_0018: Unknown result type (might be due to invalid IL or missing references)
							//IL_001d: Unknown result type (might be due to invalid IL or missing references)
							//IL_0022: Unknown result type (might be due to invalid IL or missing references)
							float num12 = Utils.DistanceXZ(firstSnapPos, p);
							Vector3 val19 = p - originPos;
							return num12 + ((Vector3)(ref val19)).magnitude / 1000f;
						}).First();
						float num7 = Vector3.SignedAngle(list[0] - list[1], firstSnapPos - val8, Vector3.up);
						num7 = (num7 + 225f) % 90f - 45f;
						val7 = Quaternion.Euler(0f, num7, 0f);
						for (int m = 0; m < list.Count; m++)
						{
							list[m] = val7 * (list[m] - originPos) + originPos;
						}
					}
					float num8 = float.MaxValue;
					Vector3 val9 = Vector3.zero;
					int num9 = 0;
					while (val9 == Vector3.zero && num9 < list.Count)
					{
						Collider[] array = Physics.OverlapSphere(list[num9], num * 1.8f, mask);
						foreach (Collider val10 in array)
						{
							if (!Object.op_Implicit((Object)(object)((Component)val10).GetComponent<Plant>()) && !Object.op_Implicit((Object)(object)((Component)val10).GetComponent<Pickable>()))
							{
								continue;
							}
							float num10 = Utils.DistanceXZ(list[num9], ((Component)val10).transform.position);
							if (!((double)num10 - 0.001 < (double)num8))
							{
								continue;
							}
							num8 = num10;
							val6 = list[num9];
							val6.y = 0f;
							Vector3 val11 = val6;
							val6 = ((Component)val10).transform.position;
							val6.y = 0f;
							val9 = val11 - val6;
							val6 = list[num9];
							val6.y = 0f;
							Vector3 val12 = val6 + val7 * val;
							val6 = ((Component)val10).transform.position;
							val6.y = 0f;
							val6 = val12 - val6;
							if (((Vector3)(ref val6)).sqrMagnitude < ((Vector3)(ref val9)).sqrMagnitude)
							{
								val9 += val7 * val;
							}
							else
							{
								val6 = list[num9];
								val6.y = 0f;
								Vector3 val13 = val6 - val7 * val;
								val6 = ((Component)val10).transform.position;
								val6.y = 0f;
								val6 = val13 - val6;
								if (((Vector3)(ref val6)).sqrMagnitude < ((Vector3)(ref val9)).sqrMagnitude)
								{
									val9 -= val7 * val;
								}
							}
							val6 = list[num9];
							val6.y = 0f;
							Vector3 val14 = val6 + val7 * val2;
							val6 = ((Component)val10).transform.position;
							val6.y = 0f;
							val6 = val14 - val6;
							if (((Vector3)(ref val6)).sqrMagnitude < ((Vector3)(ref val9)).sqrMagnitude)
							{
								val9 += val7 * val2;
								continue;
							}
							val6 = list[num9];
							val6.y = 0f;
							Vector3 val15 = val6 - val7 * val2;
							val6 = ((Component)val10).transform.position;
							val6.y = 0f;
							val6 = val15 - val6;
							if (((Vector3)(ref val6)).sqrMagnitude < ((Vector3)(ref val9)).sqrMagnitude)
							{
								val9 -= val7 * val2;
							}
						}
						num9++;
					}
					int num11 = 0;
					while (val9 != Vector3.zero && num11 < list.Count)
					{
						List<Vector3> list2 = list;
						int l = num11;
						list2[l] -= val9;
						num11++;
					}
				}
			}
			List<PlantingCell> list3 = new List<PlantingCell>();
			Heightmap val16 = Heightmap.FindHeightmap(originPos);
			foreach (Vector3 item2 in list)
			{
				val6 = item2;
				val6.y = ZoneSystem.instance.GetGroundHeight(item2);
				Vector3 val17 = val6;
				PlacementStatus valid = (PlacementStatus)0;
				if (((Component)placedPlant).GetComponent<Piece>().m_cultivatedGroundOnly && !val16.IsCultivated(val17))
				{
					valid = (PlacementStatus)9;
				}
				else if (!HasGrowSpace(val17, ((Component)placedPlant).gameObject))
				{
					valid = (PlacementStatus)1;
				}
				list3.Add(new PlantingCell
				{
					pos = val17,
					valid = valid
				});
			}
			if (num5 == 1)
			{
				list3 = ((num4 == 1) ? new List<PlantingCell> { list3[4] } : new List<PlantingCell>
				{
					list3[2],
					list3[3]
				});
			}
			int index = (from g in list3.Select([<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)] (PlantingCell c, int i) => new Tuple<PlantingCell, int>(c, i))
				where (int)g.Item1.valid == 0
				select g).OrderBy([<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)] (Tuple<PlantingCell, int> g) =>
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val18 = originPos - g.Item1.pos;
				return ((Vector3)(ref val18)).magnitude;
			}).FirstOrDefault()?.Item2 ?? 0;
			PlantingCell value = list3[index];
			list3[index] = list3[0];
			list3[0] = value;
			return list3;
		}

		private static bool HasGrowSpace(Vector3 newPos, GameObject go)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			Plant component = go.GetComponent<Plant>();
			if (component != null)
			{
				Collider[] array = (Collider[])(object)new Collider[1];
				return Physics.OverlapSphereNonAlloc(newPos, component.m_growRadius, array, _plantSpaceMask) == 0;
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "SetupPlacementGhost")]
		public static void SetupPlacementGhostPostfix(Player __instance)
		{
			DestroyGhosts();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
		public static void UpdatePlacementGhostPostfix(Player __instance, bool flashGuardStone)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Invalid comparison between Unknown and I4
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			GameObject placementGhost = __instance.m_placementGhost;
			if (!Object.op_Implicit((Object)(object)placementGhost) || !placementGhost.activeSelf)
			{
				SetGhostsActive(active: false);
				return;
			}
			ghostCenterPosition = placementGhost.transform.position;
			ghostRotation = placementGhost.transform.rotation;
			if (Farming.increasePlantAmount.Value == 0)
			{
				SetGhostsActive(active: false);
				return;
			}
			KeyboardShortcut value = Farming.snapModeToggleHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				snapping = !snapping;
			}
			value = Farming.plantModeToggleHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				massPlanting = !massPlanting;
			}
			Plant component = placementGhost.GetComponent<Plant>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				SetGhostsActive(active: false);
				return;
			}
			if (!EnsureGhostsBuilt(__instance))
			{
				SetGhostsActive(active: false);
				return;
			}
			Requirement val = placementGhost.GetComponent<Piece>().m_resources.First([<a8ffcd71-216a-4891-b825-f0d31b2f992a>NullableContext(0)] (Requirement r) => Object.op_Implicit((Object)(object)r.m_resItem) && r.m_amount > 0);
			_fakeResourcePiece.m_resources[0].m_resItem = val.m_resItem;
			_fakeResourcePiece.m_resources[0].m_amount = val.m_amount;
			placements = BuildPlantingGridPositions(placementGhost.transform.position, component, placementGhost.transform.rotation);
			_placementGhosts[0] = placementGhost;
			for (int i = 0; i < _placementGhosts.Length; i++)
			{
				if (i == 1 && !massPlanting)
				{
					SetGhostsActive(active: false);
					break;
				}
				Vector3 pos = placements[i].pos;
				Requirement obj = _fakeResourcePiece.m_resources[0];
				obj.m_amount += val.m_amount;
				_placementGhosts[i].transform.position = pos;
				_placementGhosts[i].transform.rotation = Quaternion.Euler(new Vector3(0f, randomGhostRotations[i], 0f)) * placementGhost.transform.rotation;
				_placementGhosts[i].SetActive(true);
				PlacementStatus val2 = placements[i].valid;
				if (i == 0)
				{
					__instance.m_placementStatus = val2;
				}
				if ((int)val2 == 0 && !__instance.m_noPlacementCost && !__instance.HaveRequirements(_fakeResourcePiece, (RequirementMode)0))
				{
					val2 = (PlacementStatus)1;
				}
				_placementGhosts[i].GetComponent<Piece>().SetInvalidPlacementHeightlight((int)val2 > 0);
			}
		}

		public static void determineGhostRotations()
		{
			for (int i = 1; i < randomGhostRotations.Length; i++)
			{
				randomGhostRotations[i] = ((Farming.randomRotation.Value == Farming.Toggle.Off) ? 0f : Random.Range(0f, 360f));
			}
		}

		private static bool EnsureGhostsBuilt(Player player)
		{
			int num = GridHeight() * GridWidth();
			if (invalidatedGhosts || _placementGhosts.Length != num)
			{
				DestroyGhosts();
				if (_placementGhosts.Length != num)
				{
					_placementGhosts = (GameObject[])(object)new GameObject[num];
					randomGhostRotations = new float[num];
				}
				determineGhostRotations();
				PieceTable buildPieces = player.m_buildPieces;
				if (buildPieces != null)
				{
					GameObject selectedPrefab = buildPieces.GetSelectedPrefab();
					if (selectedPrefab != null)
					{
						if (selectedPrefab.GetComponent<Piece>().m_repairPiece)
						{
							return false;
						}
						for (int i = 1; i < _placementGhosts.Length; i++)
						{
							_placementGhosts[i] = SetupMyGhost(selectedPrefab);
						}
						invalidatedGhosts = false;
						goto IL_009b;
					}
				}
				return false;
			}
			goto IL_009b;
			IL_009b:
			return true;
		}

		private static void DestroyGhosts()
		{
			foreach (GameObject item in _placementGhosts.Skip(1))
			{
				if (Object.op_Implicit((Object)(object)item))
				{
					Object.Destroy((Object)(object)item);
				}
			}
			invalidatedGhosts = true;
		}

		private static void SetGhostsActive(bool active)
		{
			foreach (GameObject item in _placementGhosts.Skip(1))
			{
				if (Object.op_Implicit((Object)(object)item))
				{
					item.SetActive(active);
				}
			}
		}

		private static GameObject SetupMyGhost(GameObject prefab)
		{
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Expected O, but got Unknown
			ZNetView.m_forceDisableInit = true;
			GameObject val = Object.Instantiate<GameObject>(prefab);
			ZNetView.m_forceDisableInit = false;
			((Object)val).name = ((Object)prefab).name;
			Joint[] componentsInChildren = val.GetComponentsInChildren<Joint>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren[i]);
			}
			Rigidbody[] componentsInChildren2 = val.GetComponentsInChildren<Rigidbody>();
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren2[i]);
			}
			int layer = LayerMask.NameToLayer("ghost");
			Transform[] componentsInChildren3 = val.GetComponentsInChildren<Transform>();
			for (int i = 0; i < componentsInChildren3.Length; i++)
			{
				((Component)componentsInChildren3[i]).gameObject.layer = layer;
			}
			TerrainModifier[] componentsInChildren4 = val.GetComponentsInChildren<TerrainModifier>();
			for (int i = 0; i < componentsInChildren4.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren4[i]);
			}
			GuidePoint[] componentsInChildren5 = val.GetComponentsInChildren<GuidePoint>();
			for (int i = 0; i < componentsInChildren5.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren5[i]);
			}
			Light[] componentsInChildren6 = val.GetComponentsInChildren<Light>();
			for (int i = 0; i < componentsInChildren6.Length; i++)
			{
				Object.Destroy((Object)(object)componentsInChildren6[i]);
			}
			Transform val2 = val.transform.Find("_GhostOnly");
			if (Object.op_Implicit((Object)(object)val2))
			{
				((Component)val2).gameObject.SetActive(true);
			}
			MeshRenderer[] componentsInChildren7 = val.GetComponentsInChildren<MeshRenderer>();
			foreach (MeshRenderer val3 in componentsInChildren7)
			{
				if (!((Object)(object)((Renderer)val3).sharedMaterial == (Object)null))
				{
					Material[] sharedMaterials = ((Renderer)val3).sharedMaterials;
					for (int j = 0; j < sharedMaterials.Length; j++)
					{
						Material val4 = new Material(sharedMaterials[j]);
						val4.SetFloat(RippleDistance, 0f);
						val4.SetFloat(ValueNoise, 0f);
						sharedMaterials[j] = val4;
					}
					((Renderer)val3).sharedMaterials = sharedMaterials;
					((Renderer)val3).shadowCastingMode = (ShadowCastingMode)0;
				}
			}
			return val;
		}

		static MassPlant()
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			Piece val = new Piece();
			val.m_dlc = string.Empty;
			val.m_resources = (Requirement[])(object)new Requirement[1]
			{
				new Requirement()
			};
			_fakeResourcePiece = val;
			RippleDistance = Shader.PropertyToID("_RippleDistance");
			ValueNoise = Shader.PropertyToID("_ValueNoise");
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<b5509434-75c9-46e3-9688-bbb1c34cd430>Embedded]
	internal sealed class <b5509434-75c9-46e3-9688-bbb1c34cd430>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<b5509434-75c9-46e3-9688-bbb1c34cd430>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<b5509434-75c9-46e3-9688-bbb1c34cd430>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <11702941-09ed-4371-bd9d-d2610094a257>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <11702941-09ed-4371-bd9d-d2610094a257>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<b5509434-75c9-46e3-9688-bbb1c34cd430>Embedded]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
	[PublicAPI]
	[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
	internal abstract class OwnConfigEntryBase
	{
		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		public object LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
	[PublicAPI]
	[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
	internal class SyncedConfigEntry<[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)] T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(2)]
	[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
	internal abstract class CustomSyncedValueBase
	{
		public object LocalBaseValue;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(1)]
		public readonly string Identifier;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(1)]
		public readonly Type Type;

		private object boxedValue;

		protected bool localIsOwner;

		public object BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action ValueChanged;

		[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
	[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
	[PublicAPI]
	internal sealed class CustomSyncedValue<[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)] T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
	[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
	[PublicAPI]
	internal class ConfigSync
	{
		[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)]
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
			public static ZRpc currentRpc;

			[HarmonyPrefix]
			[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)]
		private class ParsedConfigs
		{
			[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>();

			[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix([<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
			public object value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		public string DisplayName;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		public string CurrentVersion;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		public string MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		private OwnConfigEntryBase lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(new byte[] { 1, 0, 1 })]
		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		[method: <11702941-09ed-4371-bd9d-d2610094a257>NullableContext(2)]
		[field: <0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		public event Action<bool> SourceOfTruthChanged;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		[method: <11702941-09ed-4371-bd9d-d2610094a257>NullableContext(2)]
		[field: <0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		private event Action lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)] T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += [<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)] T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += [<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (object _, EventArgs _) =>
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(([<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(new byte[] { 0, 1 })] KeyValuePair<long, string> kv) =>
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out var value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		[return: <0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		private static OwnConfigEntryBase configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		[return: <0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(new byte[] { 2, 1 })]
		public static SyncedConfigEntry<T> ConfigData<[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)] T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)] T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage([<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(new byte[] { 2, 1 })] IEnumerable<ConfigEntryBase> configs = null, [<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(new byte[] { 2, 1 })] IEnumerable<CustomSyncedValueBase> customValues = null, [<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(new byte[] { 2, 1 })] IEnumerable<PackageEntry> packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where([<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, [<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)] object value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[HarmonyPatch]
	[PublicAPI]
	[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(0)]
	[<11702941-09ed-4371-bd9d-d2610094a257>NullableContext(1)]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		private string displayName;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		private string currentVersion;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		private string minimumRequiredVersion;

		public bool ModRequired = true;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		private string ReceivedCurrentVersion;

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		private string ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		[<0a3ab4d0-6a37-403a-b7d0-31e1c1f47994>Nullable(2)]
		private ConfigSync ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}

BepInEx/plugins/Smoothbrain-Lumberjacking/Lumberjacking.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Guid("3FED9927-9CAF-4D3B-B992-44F009724EB9")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("Lumberjacking")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/Lumberjacking")]
[assembly: AssemblyTitle("Lumberjacking")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<8519ee65-14c9-4e0d-8271-bb6eb6259348>Embedded]
	internal sealed class <8519ee65-14c9-4e0d-8271-bb6eb6259348>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<8519ee65-14c9-4e0d-8271-bb6eb6259348>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <5354af4d-874b-415c-b6b9-ccbe838fda37>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <5354af4d-874b-415c-b6b9-ccbe838fda37>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <5354af4d-874b-415c-b6b9-ccbe838fda37>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<8519ee65-14c9-4e0d-8271-bb6eb6259348>Embedded]
	internal sealed class <7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Lumberjacking
{
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	[BepInPlugin("org.bepinex.plugins.lumberjacking", "Lumberjacking", "1.0.4")]
	public class Lumberjacking : BaseUnityPlugin
	{
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		[HarmonyPatch(typeof(Skills), "Awake")]
		public class RemoveWoodcutting
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			[UsedImplicitly]
			public static void Prefix(Skills __instance)
			{
				__instance.m_skills.RemoveAll(delegate(SkillDef s)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0009: Invalid comparison between Unknown and I4
					//IL_0030: Unknown result type (might be due to invalid IL or missing references)
					//IL_0036: Expected O, but got Unknown
					if ((int)s.m_skill == 13)
					{
						SkillDef val = (SkillDef)lumberjacking.GetType().GetField("skillDef", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(lumberjacking);
						val.m_icon = s.m_icon;
						return true;
					}
					return false;
				});
			}
		}

		[HarmonyPatch]
		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(0)]
		[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
		private class RemoveWoodcuttingFromSkillFunctions
		{
			public static IEnumerable<MethodBase> TargetMethods()
			{
				return new MethodInfo[2]
				{
					AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null),
					AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null)
				};
			}

			public static void Prefix(ref string name)
			{
				if (name == "Woodcutting")
				{
					name += " ";
				}
			}
		}

		[HarmonyPatch(typeof(Skills), "GetSkill")]
		public class ReturnDummyWoodcuttingSkill
		{
			[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(2)]
			public static Skill lastSkill;

			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			[UsedImplicitly]
			public static bool Prefix(SkillType skillType, ref Skill __result)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0004: Invalid comparison between Unknown and I4
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Expected O, but got Unknown
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Expected O, but got Unknown
				//IL_002f: Expected O, but got Unknown
				if ((int)skillType == 13)
				{
					Skill val = new Skill(new SkillDef
					{
						m_skill = (SkillType)0,
						m_increseStep = 0f
					});
					lastSkill = val;
					__result = val;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Skills), "GetSkillDef")]
		public class ReturnDummyWoodcuttingSkillDef
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			[UsedImplicitly]
			public static bool Prefix(SkillType type, ref SkillDef __result)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0004: Invalid comparison between Unknown and I4
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Expected O, but got Unknown
				if ((int)type == 13)
				{
					__result = new SkillDef
					{
						m_skill = (SkillType)0,
						m_increseStep = 0f
					};
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		public class MarkWoodcuttingSkillInvalid
		{
			[UsedImplicitly]
			public static bool Prefix(SkillType type, ref bool __result)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Invalid comparison between Unknown and I4
				if (!PreserveWoodcuttingSkillValueLoad.Loading && (int)type == 13)
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Skills), "Load")]
		public class PreserveWoodcuttingSkillValueLoad
		{
			public static bool Loading;

			private static void Prefix()
			{
				Loading = true;
			}

			private static void Finalizer()
			{
				Loading = false;
				PreserveWoodcuttingSkillValueSave.woodCuttingToSave = ReturnDummyWoodcuttingSkill.lastSkill;
			}
		}

		[HarmonyPatch(typeof(Skills), "Save")]
		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(0)]
		[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
		public class PreserveWoodcuttingSkillValueSave
		{
			[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(2)]
			public static Skill woodCuttingToSave;

			private static void Prefix(Skills __instance)
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				if (woodCuttingToSave != null)
				{
					woodCuttingToSave.m_info.m_skill = (SkillType)13;
					__instance.m_skillData[(SkillType)13] = woodCuttingToSave;
				}
			}

			private static void Finalizer(Skills __instance)
			{
				__instance.m_skillData.Remove((SkillType)13);
			}
		}

		[HarmonyPatch(typeof(Terminal), "InitTerminal")]
		public class RemoveWoodcuttingAutocomplete
		{
			[UsedImplicitly]
			public static void Postfix()
			{
				RemoveWoodcutting(Terminal.commands["raiseskill"]);
				RemoveWoodcutting(Terminal.commands["resetskill"]);
				[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
				static void RemoveWoodcutting(ConsoleCommand command)
				{
					//IL_001b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0025: Expected O, but got Unknown
					ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher;
					command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)delegate
					{
						List<string> list = fetcher.Invoke();
						list.Remove("WoodCutting");
						return list;
					};
				}
			}
		}

		[HarmonyPatch(typeof(ImpactEffect), "OnCollisionEnter")]
		public class SetTreeFlag
		{
			public static bool hitByTree;

			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			private static void Prefix(ImpactEffect __instance)
			{
				if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<TreeLog>()))
				{
					hitByTree = true;
				}
			}

			private static void Finalizer()
			{
				hitByTree = false;
			}
		}

		[HarmonyPatch(typeof(Character), "Damage")]
		public class ReduceDamageTakenFromTrees
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			private static void Prefix(Character __instance, HitData hit)
			{
				if (SetTreeFlag.hitByTree)
				{
					Player val = (Player)(object)((__instance is Player) ? __instance : null);
					if (val != null)
					{
						hit.ApplyModifier(1f - ((Character)val).m_nview.GetZDO().GetFloat("Lumberjacking Skill Factor", 0f) * (1f - damageFromTreesFactor.Value));
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "Awake")]
		public class PlayerAwake
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				((Character)__instance).m_nview.Register<int>("Lumberjacking IncreaseSkill", (Action<long, int>)delegate(long _, int factor)
				{
					((Character)(object)__instance).RaiseSkill("Lumberjacking", factor);
				});
			}
		}

		[HarmonyPatch(typeof(Player), "Update")]
		public class PlayerUpdate
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					((Character)__instance).m_nview.GetZDO().Set("Lumberjacking Skill Factor", ((Character)(object)__instance).GetSkillFactor("Lumberjacking"));
				}
			}
		}

		[HarmonyPatch(typeof(SEMan), "ModifyAttack")]
		private class IncreaseDamageDone
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			private static void Prefix(SEMan __instance, ref HitData hitData)
			{
				Character character = __instance.m_character;
				Player val = (Player)(object)((character is Player) ? character : null);
				if (val != null)
				{
					hitData.m_damage.m_chop *= 1f + ((Character)(object)val).GetSkillFactor("Lumberjacking") * damageToTreesFactor.Value;
				}
			}
		}

		[HarmonyPatch(typeof(DropTable), "GetDropList", new Type[] { typeof(int) })]
		private class IncreaseItemYield
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			[HarmonyPriority(100)]
			[UsedImplicitly]
			private static void Postfix(ref List<GameObject> __result)
			{
				if (!SetLumberjackingFlagTreeLog.IsLumberjacking)
				{
					return;
				}
				List<GameObject> list = new List<GameObject>();
				foreach (GameObject item in __result)
				{
					float num = 1f + SetLumberjackingFlagTreeLog.LumberjackingFactor * (lumberjackingYieldFactor.Value - 1f);
					for (int num2 = Mathf.FloorToInt(num + Random.Range(0f, 1f)); num2 > 0; num2--)
					{
						list.Add(item);
					}
				}
				__result = list;
			}
		}

		[HarmonyPatch(typeof(TreeLog), "RPC_Damage")]
		public static class SetLumberjackingFlagTreeLog
		{
			public static bool IsLumberjacking;

			public static float LumberjackingFactor;

			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			private static void Prefix(TreeLog __instance, HitData hit)
			{
				IsLumberjacking = true;
				Character attacker = hit.GetAttacker();
				float? obj;
				if (attacker == null)
				{
					obj = null;
				}
				else
				{
					ZDO zDO = attacker.m_nview.GetZDO();
					obj = ((zDO != null) ? new float?(zDO.GetFloat("Lumberjacking Skill Factor", 0f)) : null);
				}
				float? num = obj;
				LumberjackingFactor = num.GetValueOrDefault();
				if (hit.m_toolTier >= __instance.m_minToolTier && hit.m_damage.m_chop > 0f && __instance.m_nview.IsValid() && __instance.m_nview.IsOwner())
				{
					Character attacker2 = hit.GetAttacker();
					Player val = (Player)(object)((attacker2 is Player) ? attacker2 : null);
					if (val != null)
					{
						((Character)val).m_nview.InvokeRPC("Lumberjacking IncreaseSkill", new object[1] { 1 });
					}
				}
			}

			private static void Finalizer()
			{
				IsLumberjacking = false;
			}
		}

		[HarmonyPatch(typeof(TreeBase), "RPC_Damage")]
		public static class SetLumberjackingFlagTreeBase
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			private static void Prefix(TreeBase __instance, HitData hit)
			{
				SetLumberjackingFlagTreeLog.IsLumberjacking = true;
				Character attacker = hit.GetAttacker();
				float? obj;
				if (attacker == null)
				{
					obj = null;
				}
				else
				{
					ZDO zDO = attacker.m_nview.GetZDO();
					obj = ((zDO != null) ? new float?(zDO.GetFloat("Lumberjacking Skill Factor", 0f)) : null);
				}
				float? num = obj;
				SetLumberjackingFlagTreeLog.LumberjackingFactor = num.GetValueOrDefault();
				if (hit.m_toolTier >= __instance.m_minToolTier && hit.m_damage.m_chop > 0f && __instance.m_nview.IsValid() && __instance.m_nview.IsOwner())
				{
					Character attacker2 = hit.GetAttacker();
					Player val = (Player)(object)((attacker2 is Player) ? attacker2 : null);
					if (val != null)
					{
						((Character)val).m_nview.InvokeRPC("Lumberjacking IncreaseSkill", new object[1] { 1 });
					}
				}
			}

			private static void Finalizer()
			{
				SetLumberjackingFlagTreeLog.IsLumberjacking = false;
			}
		}

		[HarmonyPatch(typeof(Player), "GetRunSpeedFactor")]
		public static class IncreaseRunMovementSpeedInForest
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			private static void Postfix(Player __instance, ref float __result)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				if (WorldGenerator.InForest(((Component)__instance).transform.position))
				{
					__result *= 1f + ((Character)(object)__instance).GetSkillFactor("Lumberjacking") * (forestMovementSpeedFactor.Value - 1f);
				}
			}
		}

		[HarmonyPatch(typeof(Player), "GetJogSpeedFactor")]
		public static class IncreaseJogMovementSpeedInForest
		{
			[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
			private static void Postfix(Player __instance, ref float __result)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				if (WorldGenerator.InForest(((Component)__instance).transform.position))
				{
					__result *= 1f + ((Character)(object)__instance).GetSkillFactor("Lumberjacking") * (forestMovementSpeedFactor.Value - 1f);
				}
			}
		}

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private const string ModName = "Lumberjacking";

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private const string ModVersion = "1.0.4";

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private const string ModGUID = "org.bepinex.plugins.lumberjacking";

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.lumberjacking")
		{
			DisplayName = "Lumberjacking",
			CurrentVersion = "1.0.4"
		};

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private static ConfigEntry<Toggle> serverConfigLocked = null;

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private static ConfigEntry<float> lumberjackingYieldFactor = null;

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private static ConfigEntry<float> damageToTreesFactor = null;

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private static ConfigEntry<float> damageFromTreesFactor = null;

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private static ConfigEntry<float> forestMovementSpeedFactor = null;

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private static ConfigEntry<float> experienceGainedFactor = null;

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private static ConfigEntry<int> experienceLoss = null;

		[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(1)]
		private static Skill lumberjacking = null;

		[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
		private ConfigEntry<T> config<[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(val);
			syncedConfigEntry.SynchronizedConfig = synchronizedSetting;
			return val;
		}

		[<7e1cb554-b248-40ac-982b-f7aac6c2eee7>NullableContext(1)]
		private ConfigEntry<T> config<[<5354af4d-874b-415c-b6b9-ccbe838fda37>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Expected O, but got Unknown
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Expected O, but got Unknown
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Expected O, but got Unknown
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Expected O, but got Unknown
			lumberjacking = new Skill("Lumberjacking", (Sprite)null);
			lumberjacking.Description.English("Increases damage dealt to trees, item yield from trees and reduces damage taken from falling trees. Increases movement speed in forests.");
			lumberjacking.Name.German("Holzfällerei");
			lumberjacking.Description.German("Erhöht den Schaden an Bäumen, sowie die Ausbeute von Bäumen und reduziert den erlittenen Schaden durch Baumschlag. Erhöht die Bewegungsgeschwindigkeit in Wäldern.");
			serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			lumberjackingYieldFactor = config("1 - General", "Tree item yield modifier at level 100", 2f, new ConfigDescription("Item yield from trees will be modified by this value at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			damageToTreesFactor = config("1 - General", "Damage to trees modifier at level 100", 3f, new ConfigDescription("Damage dealt to trees will be modified by this value at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			damageFromTreesFactor = config("1 - General", "Tree fall damage modifier at level 100", 0.3f, new ConfigDescription("Damage from falling trees will be modified by this value at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			forestMovementSpeedFactor = config("1 - General", "Movement speed modifier in forests at level 100", 1.1f, new ConfigDescription("Movement speed in forests will be modified by this value at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 2f), Array.Empty<object>()));
			experienceGainedFactor = config("2 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the lumberjacking skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>()));
			experienceGainedFactor.SettingChanged += delegate
			{
				lumberjacking.SkillGainFactor = experienceGainedFactor.Value;
			};
			lumberjacking.SkillGainFactor = experienceGainedFactor.Value;
			experienceLoss = config("2 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the lumberjacking skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			experienceLoss.SettingChanged += delegate
			{
				lumberjacking.SkillLoss = experienceLoss.Value;
			};
			lumberjacking.SkillLoss = experienceLoss.Value;
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			Harmony val = new Harmony("org.bepinex.plugins.lumberjacking");
			val.PatchAll(executingAssembly);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[<656de66b-2c8b-49cc-932c-f42abf5a1977>Embedded]
	[CompilerGenerated]
	internal sealed class <656de66b-2c8b-49cc-932c-f42abf5a1977>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<656de66b-2c8b-49cc-932c-f42abf5a1977>Embedded]
	[CompilerGenerated]
	internal sealed class <2491b641-76b7-4ab6-964e-1806dce10664>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <2491b641-76b7-4ab6-964e-1806dce10664>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <2491b641-76b7-4ab6-964e-1806dce10664>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<656de66b-2c8b-49cc-932c-f42abf5a1977>Embedded]
	internal sealed class <3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[<656de66b-2c8b-49cc-932c-f42abf5a1977>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
	[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
	internal abstract class OwnConfigEntryBase
	{
		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		public object LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
	[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
	internal class SyncedConfigEntry<[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)] T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
	[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(2)]
	internal abstract class CustomSyncedValueBase
	{
		public object LocalBaseValue;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(1)]
		public readonly string Identifier;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(1)]
		public readonly Type Type;

		private object boxedValue;

		protected bool localIsOwner;

		public object BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action ValueChanged;

		[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
	[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
	[PublicAPI]
	internal sealed class CustomSyncedValue<[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)] T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
	[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)]
		private static class SnatchCurrentlyHandlingRPC
		{
			[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
			public static ZRpc currentRpc;

			[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)]
		private class ParsedConfigs
		{
			[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>();

			[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix([<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
			public object value;
		}

		[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		public string DisplayName;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		public string CurrentVersion;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		public string MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		private OwnConfigEntryBase lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 1, 0, 1 })]
		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		[method: <3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(2)]
		[field: <2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		public event Action<bool> SourceOfTruthChanged;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		[method: <3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(2)]
		[field: <2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		private event Action lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)] T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += [<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)] T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += [<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (object _, EventArgs _) =>
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(([<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 0, 1 })] KeyValuePair<long, string> kv) =>
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out var value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		[return: <2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		private static OwnConfigEntryBase configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		[return: <2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 2, 1 })]
		public static SyncedConfigEntry<T> ConfigData<[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)] T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)] T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage([<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 2, 1 })] IEnumerable<ConfigEntryBase> configs = null, [<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 2, 1 })] IEnumerable<CustomSyncedValueBase> customValues = null, [<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 2, 1 })] IEnumerable<PackageEntry> packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, [<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)] object value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[PublicAPI]
	[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(0)]
	[HarmonyPatch]
	[<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(1)]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		private string displayName;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		private string currentVersion;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		private string minimumRequiredVersion;

		public bool ModRequired = true;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		private string ReceivedCurrentVersion;

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		private string ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		[<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)]
		private ConfigSync ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error([<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(2)] ZRpc rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, [<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(new byte[] { 2, 1, 1 })] Action<ZRpc, ZPackage> original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (ZRpc rpc, [<2491b641-76b7-4ab6-964e-1806dce10664>Nullable(1)] ZPackage pkg) =>
				{
					CheckVersion(rpc, pkg, action);
				}));
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy([<3d5993e3-6241-49e2-a51f-54cb3c93603f>NullableContext(0)] (KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	[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;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace SkillManager
{
	[PublicAPI]
	internal class Skill
	{
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				Localization __instance2 = __instance;
				string key = localizations.FirstOrDefault<KeyValuePair<string, Localization>>((KeyValuePair<string, Localization> l) => l.Value == __instance2).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance2);
				}
			}

			public static Localization ForLanguage(string? language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out Localization value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[PublicAPI]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", key);
			}

			public LocalizeKey Portuguese_Brazilian(string key)
			{
				return addForLang("Portuguese_Brazilian", key);
			}

			public LocalizeKey Chinese(string key)
			{
				return addForLang("Chinese", key);
			}

			public LocalizeKey Japanese(string key)
			{
				return addForLang("Japanese", key);
			}

			public LocalizeKey Korean(string key)
			{
				return addForLang("Korean", key);
			}

			public LocalizeKey Hindi(string key)
			{
				return addForLang("Hindi", key);
			}

			public LocalizeKey Thai(string key)
			{
				return addForLang("Thai", key);
			}

			public LocalizeKey Abenaki(string key)
			{
				return addForLang("Abenaki", key);
			}

			public LocalizeKey Croatian(string key)
			{
				return addForLang("Croatian", key);
			}

			public LocalizeKey Georgian(string key)
			{
				return addForLang("Georgian", key);
			}

			public LocalizeKey Greek(string key)
			{
				return addForLang("Greek", key);
			}

			public LocalizeKey Serbian(string key)
			{
				return addForLang("Serbian", key);
			}

			public LocalizeKey Ukrainian(string key)
			{
				return addForLang("Ukrainian", key);
			}

			private LocalizeKey addForLang(string lang, string value)
			{
				Localizations[lang] = value;
				if (Localization.instance.GetSelectedLanguage() == lang)
				{
					Localization.instance.AddWord(Key, value);
				}
				else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
				{
					Localization.instance.AddWord(Key, value);
				}
				return this;
			}

			[HarmonyPriority(300)]
			internal static void AddLocalizedKeys(Localization __instance, string language)
			{
				foreach (LocalizeKey key in keys)
				{
					string value2;
					if (key.Localizations.TryGetValue(language, out string value) || key.Localizations.TryGetValue("English", out value))
					{
						__instance.AddWord(key.Key, value);
					}
					else if (key.Localizations.TryGetValue("alias", out value2))
					{
						Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
					}
				}
			}
		}

		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public string? Category;
		}

		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		private static class Patch_Skills_IsSkillValid
		{
			private static void Postfix(SkillType type, ref bool __result)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (!__result && skills.ContainsKey(type))
				{
					__result = true;
				}
			}
		}

		private static readonly Dictionary<SkillType, Skill> skills;

		internal static readonly Dictionary<string, Skill> skillByName;

		private readonly string skillName;

		private readonly string internalSkillName;

		private readonly SkillDef skillDef;

		public readonly LocalizeKey Name;

		public readonly LocalizeKey Description;

		private float skillEffectFactor = 1f;

		private int skillLoss = 5;

		public bool Configurable;

		private static bool InitializedTerminal;

		private static Localization? _english;

		private static BaseUnityPlugin? _plugin;

		private static bool hasConfigSync;

		private static object? _configSync;

		public float SkillGainFactor
		{
			get
			{
				return skillDef.m_increseStep;
			}
			set
			{
				skillDef.m_increseStep = value;
				this.SkillGainFactorChanged?.Invoke(value);
			}
		}

		public float SkillEffectFactor
		{
			get
			{
				return skillEffectFactor;
			}
			set
			{
				skillEffectFactor = value;
				this.SkillEffectFactorChanged?.Invoke(value);
			}
		}

		public int SkillLoss
		{
			get
			{
				return skillLoss;
			}
			set
			{
				skillLoss = value;
				this.SkillLossChanged?.Invoke(value);
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				object obj = _plugin;
				if (obj == null)
				{
					BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
					_plugin = val;
					obj = (object)val;
				}
				return (BaseUnityPlugin)obj;
			}
		}

		private static object? configSync
		{
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		public event Action<float>? SkillGainFactorChanged;

		public event Action<float>? SkillEffectFactorChanged;

		public event Action<float>? SkillLossChanged;

		public Skill(string englishName, string icon)
			: this(englishName, loadSprite(icon, 64, 64))
		{
		}

		public Skill(string englishName, Sprite icon)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			SkillType val = fromName(englishName);
			string text = new Regex("[^a-zA-Z]").Replace(englishName, "_");
			skills[val] = this;
			skillByName[englishName] = this;
			skillDef = new SkillDef
			{
				m_description = "$skilldesc_" + text,
				m_icon = icon,
				m_increseStep = 1f,
				m_skill = val
			};
			internalSkillName = text;
			skillName = englishName;
			Name = new LocalizeKey("skill_" + ((object)(SkillType)(ref val)).ToString()).English(englishName);
			Description = new LocalizeKey("skilldesc_" + text);
		}

		public static SkillType fromName(string englishName)
		{
			return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName));
		}

		static Skill()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			skills = new Dictionary<SkillType, Skill>();
			skillByName = new Dictionary<string, Skill>();
			InitializedTerminal = false;
			hasConfigSync = true;
			Harmony val = new Harmony("org.bepinex.helpers.skillmanager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null);
		}

		private static void Patch_FejdStartup()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			foreach (Skill skill in skills.Values)
			{
				if (skill.Configurable)
				{
					string key = skill.Name.Key;
					string group = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim();
					string category = Localization.instance.Localize(key).Trim();
					ConfigEntry<float> skillGain = config(group, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillGainFactor = skillGain.Value;
					skillGain.SettingChanged += delegate
					{
						skill.SkillGainFactor = skillGain.Value;
					};
					ConfigEntry<float> skillEffect = config(group, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillEffectFactor = skillEffect.Value;
					skillEffect.SettingChanged += delegate
					{
						skill.SkillEffectFactor = skillEffect.Value;
					};
					ConfigEntry<int> skillLoss = config(group, "Skill loss", skill.skillLoss, new ConfigDescription("How much experience to lose on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.skillLoss = skillLoss.Value;
					skillLoss.SettingChanged += delegate
					{
						skill.skillLoss = skillLoss.Value;
					};
				}
			}
		}

		private static void Patch_Skills_GetSkillDef(ref SkillDef? __result, List<SkillDef> ___m_skills, SkillType type)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (__result == null)
			{
				SkillDef val = GetSkillDef(type);
				if (val != null)
				{
					___m_skills.Add(val);
					__result = val;
				}
			}
		}

		private static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				SkillType current = key;
				Skill skill = skills[current];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					Skill skill2 = __instance.GetSkill(current);
					skill2.m_level += value;
					skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f);
					((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(SkillType)(ref current)).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon);
					Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level);
					return false;
				}
			}
			return true;
		}

		private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				Skill skill = skills[key];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					__instance.ResetSkill(key);
					Console.instance.Print("Skill " + skill.internalSkillName + " reset");
					return false;
				}
			}
			return true;
		}

		private static void Patch_Skills_OnDeath_Prefix(Skills __instance, ref Dictionary<SkillType, Skill>? __state)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				__state = new Dictionary<SkillType, Skill>();
			}
			foreach (KeyValuePair<SkillType, Skill> skill in skills)
			{
				if (__instance.m_skillData.TryGetValue(skill.Key, out var value))
				{
					__state[skill.Key] = value;
					if (skill.Value.skillLoss > 0)
					{
						Skill obj = value;
						obj.m_level -= value.m_level * (float)skill.Value.SkillLoss / 100f;
						value.m_accumulator = 0f;
					}
					__instance.m_skillData.Remove(skill.Key);
				}
			}
		}

		private static void Patch_Skills_OnDeath_Finalizer(Skills __instance, ref Dictionary<SkillType, Skill>? __state)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				return;
			}
			foreach (KeyValuePair<SkillType, Skill> item in __state)
			{
				__instance.m_skillData[item.Key] = item.Value;
			}
			__state = null;
		}

		private static void Patch_Terminal_InitTerminal_Prefix()
		{
			InitializedTerminal = Terminal.m_terminalInitialized;
		}

		private static void Patch_Terminal_InitTerminal()
		{
			if (!InitializedTerminal)
			{
				AddSkill(Terminal.commands["raiseskill"]);
				AddSkill(Terminal.commands["resetskill"]);
			}
			static void AddSkill(ConsoleCommand command)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Expected O, but got Unknown
				ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher;
				command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)delegate
				{
					List<string> list = fetcher.Invoke();
					list.AddRange(skills.Values.Select((Skill skill) => skill.internalSkillName));
					return list;
				};
			}
		}

		private static SkillDef? GetSkillDef(SkillType skillType)
		{
			//IL_0005: 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)
			if (!skills.ContainsKey(skillType))
			{
				return null;
			}
			return skills[skillType].skillDef;
		}

		private static byte[] ReadEmbeddedFileBytes(string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static Texture2D loadTexture(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_001f: Expected O, but got Unknown
			Texture2D val = new Texture2D(0, 0);
			ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name));
			return val;
		}

		private static Sprite loadSprite(string name, int width, int height)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero);
		}

		private static ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description)
		{
			ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description);
			configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T))
				.Invoke(configSync, new object[1] { val });
			return val;
		}

		private static ConfigEntry<T> config<T>(string group, string name, T value, string description)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[PublicAPI]
	internal static class SkillExtensions
	{
	

BepInEx/plugins/Smoothbrain-Mining/Mining.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: Guid("7210421B-E30E-4DA5-9140-7751B6A324B7")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("Mining")]
[assembly: AssemblyCompany("")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/Mining")]
[assembly: AssemblyTitle("Mining")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<42d333ce-c994-40a6-95a5-90091d85045c>Embedded]
	internal sealed class <42d333ce-c994-40a6-95a5-90091d85045c>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<42d333ce-c994-40a6-95a5-90091d85045c>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <5bf50bb2-bf24-4829-8e75-d27dc884faa3>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <5bf50bb2-bf24-4829-8e75-d27dc884faa3>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <5bf50bb2-bf24-4829-8e75-d27dc884faa3>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<42d333ce-c994-40a6-95a5-90091d85045c>Embedded]
	internal sealed class <ec1d308f-0afa-4689-9776-587e8deaca69>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <ec1d308f-0afa-4689-9776-587e8deaca69>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Mining
{
	[BepInPlugin("org.bepinex.plugins.mining", "Mining", "1.1.4")]
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(1)]
	[<5bf50bb2-bf24-4829-8e75-d27dc884faa3>Nullable(0)]
	public class Mining : BaseUnityPlugin
	{
		[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)]
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public bool? ShowRangeAsPercent;
		}

		[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "Awake")]
		public class PlayerAwake
		{
			[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				((Character)__instance).m_nview.Register<int>("Mining IncreaseSkill", (Action<long, int>)delegate(long _, int factor)
				{
					((Character)(object)__instance).RaiseSkill("Mining", factor);
				});
			}
		}

		[HarmonyPatch(typeof(Player), "Update")]
		[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)]
		public class PlayerUpdate
		{
			[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					((Character)__instance).m_nview.GetZDO().Set("Mining Skill Factor", ((Character)(object)__instance).GetSkillFactor("Mining"));
				}
			}
		}

		[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)]
		[HarmonyPatch(typeof(SEMan), "ModifyAttack")]
		private class IncreaseDamageDone
		{
			[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(1)]
			private static void Prefix(SEMan __instance, ref HitData hitData)
			{
				Character character = __instance.m_character;
				Player val = (Player)(object)((character is Player) ? character : null);
				if (val != null)
				{
					hitData.m_damage.m_pickaxe *= 1f + ((Character)(object)val).GetSkillFactor("Mining") * (miningDamageFactor.Value - 1f);
				}
			}
		}

		[HarmonyPatch(typeof(DropTable), "GetDropList", new Type[] { typeof(int) })]
		[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)]
		private class IncreaseItemYield
		{
			[HarmonyPriority(100)]
			[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(1)]
			[UsedImplicitly]
			private static void Postfix(ref List<GameObject> __result)
			{
				if (!SetMiningFlag.IsMining)
				{
					return;
				}
				List<GameObject> list = new List<GameObject>();
				foreach (GameObject item in __result)
				{
					for (int num = Mathf.FloorToInt(1f + SetMiningFlag.MiningFactor * (miningItemYieldFactor.Value - 1f) + Random.Range(0f, 1f)); num > 0; num--)
					{
						list.Add(item);
					}
				}
				__result = list;
			}
		}

		[<5bf50bb2-bf24-4829-8e75-d27dc884faa3>Nullable(0)]
		[HarmonyPatch(typeof(MineRock5), "RPC_Damage")]
		public static class SetMiningFlag
		{
			public static bool IsMining;

			public static float MiningFactor;

			private static bool Prefix(MineRock5 __instance, HitData hit)
			{
				return HandleMining(hit, delegate
				{
					//IL_002a: Unknown result type (might be due to invalid IL or missing references)
					//IL_002f: Unknown result type (might be due to invalid IL or missing references)
					//IL_0045: Unknown result type (might be due to invalid IL or missing references)
					//IL_004c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0051: Unknown result type (might be due to invalid IL or missing references)
					//IL_0054: Unknown result type (might be due to invalid IL or missing references)
					//IL_0059: Unknown result type (might be due to invalid IL or missing references)
					//IL_005e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0066: Unknown result type (might be due to invalid IL or missing references)
					//IL_006d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0072: Unknown result type (might be due to invalid IL or missing references)
					//IL_007c: Expected O, but got Unknown
					for (int i = 0; i < __instance.m_hitAreas.Count; i++)
					{
						HitArea val = __instance.m_hitAreas[i];
						if (val.m_health > 0f)
						{
							MineRock5 obj = __instance;
							int num = i;
							HitData val2 = new HitData
							{
								m_damage = 
								{
									m_damage = __instance.m_health
								}
							};
							Bounds bounds = val.m_collider.bounds;
							val2.m_point = ((Bounds)(ref bounds)).center;
							val2.m_toolTier = 100;
							val2.m_attacker = hit.m_attacker;
							obj.DamageArea(num, val2);
						}
					}
				}, __instance.m_minToolTier, __instance.m_nview);
			}

			public static bool HandleMining(HitData hit, Action explode, int minToolTier, ZNetView netView)
			{
				Character attacker = hit.GetAttacker();
				Player val = (Player)(object)((attacker is Player) ? attacker : null);
				if (val == null)
				{
					return true;
				}
				IsMining = true;
				ZDO zDO = ((Character)val).m_nview.GetZDO();
				MiningFactor = ((zDO != null) ? zDO.GetFloat("Mining Skill Factor", 0f) : 0f);
				if (hit.m_toolTier >= minToolTier && hit.m_damage.m_pickaxe > 0f && netView.IsValid() && netView.IsOwner())
				{
					((Character)val).m_nview.InvokeRPC("Mining IncreaseSkill", new object[1] { 1 });
					if (explosiveMining && explosionMinimumLevel.Value > 0 && MiningFactor >= (float)explosionMinimumLevel.Value / 100f && Random.Range(0f, 1f) <= (MiningFactor - (float)(explosionMinimumLevel.Value - 10) / 100f) / (1f - (float)(explosionMinimumLevel.Value - 10) / 100f) * explosionChance.Value / 100f)
					{
						explode();
						return false;
					}
				}
				return true;
			}

			private static void Finalizer()
			{
				IsMining = false;
			}
		}

		[HarmonyPatch(typeof(MineRock), "RPC_Hit")]
		[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)]
		public static class SetMiningFlagRock
		{
			[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(1)]
			private static bool Prefix(MineRock __instance, HitData hit)
			{
				if (!SetMiningFlag.IsMining)
				{
					return SetMiningFlag.HandleMining(hit, delegate
					{
						//IL_0056: Unknown result type (might be due to invalid IL or missing references)
						//IL_005b: Unknown result type (might be due to invalid IL or missing references)
						//IL_0067: 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_006e: Unknown result type (might be due to invalid IL or missing references)
						//IL_0071: Unknown result type (might be due to invalid IL or missing references)
						//IL_0076: Unknown result type (might be due to invalid IL or missing references)
						//IL_007b: 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_008a: Unknown result type (might be due to invalid IL or missing references)
						//IL_008f: Unknown result type (might be due to invalid IL or missing references)
						//IL_009a: Expected O, but got Unknown
						for (int i = 0; i < __instance.m_hitAreas.Length; i++)
						{
							Collider val = __instance.m_hitAreas[i];
							float @float = __instance.m_nview.GetZDO().GetFloat($"Health{i}", __instance.m_health);
							if (@float > 0f)
							{
								MineRock obj = __instance;
								long num = 0L;
								HitData val2 = new HitData
								{
									m_damage = 
									{
										m_damage = @float
									}
								};
								Bounds bounds = val.bounds;
								val2.m_point = ((Bounds)(ref bounds)).center;
								val2.m_toolTier = 100;
								val2.m_attacker = hit.m_attacker;
								obj.RPC_Hit(num, val2, i);
							}
						}
						__instance.m_hitAreas = Array.Empty<Collider>();
					}, __instance.m_minToolTier, __instance.m_nview);
				}
				return true;
			}

			private static void Finalizer()
			{
				SetMiningFlag.IsMining = false;
			}
		}

		[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)]
		[HarmonyPatch(typeof(Destructible), "RPC_Damage")]
		public static class SetMiningFlagDestructible
		{
			[<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(1)]
			private static bool Prefix(Destructible __instance, HitData hit)
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Invalid comparison between Unknown and I4
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Invalid comparison between Unknown and I4
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Invalid comparison between Unknown and I4
				if (!SetMiningFlag.IsMining && (int)__instance.m_damages.m_pickaxe != 3 && (int)__instance.m_damages.m_chop == 3 && (int)__instance.m_destructibleType != 2)
				{
					return SetMiningFlag.HandleMining(hit, delegate
					{
						//IL_0006: Unknown result type (might be due to invalid IL or missing references)
						//IL_000b: Unknown result type (might be due to invalid IL or missing references)
						//IL_0021: Unknown result type (might be due to invalid IL or missing references)
						//IL_0028: Unknown result type (might be due to invalid IL or missing references)
						//IL_002d: Unknown result type (might be due to invalid IL or missing references)
						//IL_0032: Unknown result type (might be due to invalid IL or missing references)
						//IL_003a: Unknown result type (might be due to invalid IL or missing references)
						//IL_0041: Unknown result type (might be due to invalid IL or missing references)
						//IL_0046: Unknown result type (might be due to invalid IL or missing references)
						//IL_0050: Expected O, but got Unknown
						__instance.Damage(new HitData
						{
							m_damage = 
							{
								m_damage = __instance.m_health
							},
							m_point = hit.m_point,
							m_toolTier = 100,
							m_attacker = hit.m_attacker
						});
					}, __instance.m_minToolTier, __instance.m_nview);
				}
				return true;
			}

			private static void Finalizer()
			{
				SetMiningFlag.IsMining = false;
			}
		}

		private const string ModName = "Mining";

		private const string ModVersion = "1.1.4";

		private const string ModGUID = "org.bepinex.plugins.mining";

		private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.mining")
		{
			DisplayName = "Mining",
			CurrentVersion = "1.1.4",
			MinimumRequiredVersion = "1.1.4"
		};

		private static ConfigEntry<Toggle> serverConfigLocked = null;

		private static ConfigEntry<float> miningDamageFactor = null;

		private static ConfigEntry<float> miningItemYieldFactor = null;

		private static ConfigEntry<KeyboardShortcut> explosionToggleHotkey = null;

		private static ConfigEntry<int> explosionMinimumLevel = null;

		private static ConfigEntry<float> explosionChance = null;

		private static ConfigEntry<float> experienceGainedFactor = null;

		private static ConfigEntry<int> experienceLoss = null;

		private static bool explosiveMining = true;

		private static Skill mining = null;

		private ConfigEntry<T> config<[<5bf50bb2-bf24-4829-8e75-d27dc884faa3>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			configSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<5bf50bb2-bf24-4829-8e75-d27dc884faa3>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Expected O, but got Unknown
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Expected O, but got Unknown
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Expected O, but got Unknown
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			mining = new Skill("Mining", "mining.png");
			mining.Description.English("Increases damage done while mining and item yield from ore deposits.");
			mining.Name.German("Bergbau");
			mining.Description.German("Erhöht den Schaden während Bergbau-Aktivitäten und erhöht die Ausbeute von Erzvorkommen.");
			mining.Configurable = false;
			serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			miningDamageFactor = config("2 - Mining", "Mining Damage Factor", 3f, new ConfigDescription("Mining damage factor at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			miningItemYieldFactor = config("2 - Mining", "Mining Yield Factor", 2f, new ConfigDescription("Mining yield factor at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>()));
			explosionMinimumLevel = config("2 - Mining", "Mining Explosion Level Requirement", 50, new ConfigDescription("Minimum required skill level to have a chance for the deposit to explode. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			explosionChance = config("2 - Mining", "Mining Explosion Chance", 1f, new ConfigDescription("Mining explosion chance at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			explosionToggleHotkey = config<KeyboardShortcut>("2 - Mining", "Toggle Explosive Mining Hotkey", new KeyboardShortcut((KeyCode)116, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }), new ConfigDescription("Shortcut to press to toggle explosion chance off and on. Please note that you have to stand still, to toggle this.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false);
			experienceGainedFactor = config("3 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the mining skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>()));
			experienceGainedFactor.SettingChanged += [<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)] (object _, EventArgs _) =>
			{
				mining.SkillGainFactor = experienceGainedFactor.Value;
			};
			mining.SkillGainFactor = experienceGainedFactor.Value;
			experienceLoss = config("3 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the mining skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			experienceLoss.SettingChanged += [<ec1d308f-0afa-4689-9776-587e8deaca69>NullableContext(0)] (object _, EventArgs _) =>
			{
				mining.SkillLoss = experienceLoss.Value;
			};
			mining.SkillLoss = experienceLoss.Value;
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			new Harmony("org.bepinex.plugins.mining").PatchAll(executingAssembly);
		}

		private void Update()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			KeyboardShortcut value = explosionToggleHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				explosiveMining = !explosiveMining;
				Debug.Log((object)$"ExplosiveMining: {explosiveMining}");
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null)
				{
					((Character)localPlayer).Message((MessageType)1, $"Explosive Mining: {explosiveMining}", 0, (Sprite)null);
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<ef010791-2f45-41fa-a201-f8d6934c557c>Embedded]
	internal sealed class <ef010791-2f45-41fa-a201-f8d6934c557c>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<ef010791-2f45-41fa-a201-f8d6934c557c>Embedded]
	internal sealed class <7965ec9b-5cb0-4277-a65f-4a113ffb566c>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <7965ec9b-5cb0-4277-a65f-4a113ffb566c>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <7965ec9b-5cb0-4277-a65f-4a113ffb566c>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[<ef010791-2f45-41fa-a201-f8d6934c557c>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace SkillManager
{
	[PublicAPI]
	[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(0)]
	[<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(1)]
	internal class Skill
	{
		[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(0)]
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				string key = localizations.FirstOrDefault([<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance);
				}
			}

			public static Localization ForLanguage([<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)] string language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(0)]
		[PublicAPI]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", key);
			}

			public LocalizeKey Portuguese_Brazilian(string key)
			{
				return addForLang("Portuguese_Brazilian", key);
			}

			public LocalizeKey Chinese(string key)
			{
				return addForLang("Chinese", key);
			}

			public LocalizeKey Japanese(string key)
			{
				return addForLang("Japanese", key);
			}

			public LocalizeKey Korean(string key)
			{
				return addForLang("Korean", key);
			}

			public LocalizeKey Hindi(string key)
			{
				return addForLang("Hindi", key);
			}

			public LocalizeKey Thai(string key)
			{
				return addForLang("Thai", key);
			}

			public LocalizeKey Abenaki(string key)
			{
				return addForLang("Abenaki", key);
			}

			public LocalizeKey Croatian(string key)
			{
				return addForLang("Croatian", key);
			}

			public LocalizeKey Georgian(string key)
			{
				return addForLang("Georgian", key);
			}

			public LocalizeKey Greek(string key)
			{
				return addForLang("Greek", key);
			}

			public LocalizeKey Serbian(string key)
			{
				return addForLang("Serbian", key);
			}

			public LocalizeKey Ukrainian(string key)
			{
				return addForLang("Ukrainian", key);
			}

			private LocalizeKey addForLang(string lang, string value)
			{
				Localizations[lang] = value;
				if (Localization.instance.GetSelectedLanguage() == lang)
				{
					Localization.instance.AddWord(Key, value);
				}
				else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
				{
					Localization.instance.AddWord(Key, value);
				}
				return this;
			}

			[HarmonyPriority(300)]
			internal static void AddLocalizedKeys(Localization __instance, string language)
			{
				foreach (LocalizeKey key in keys)
				{
					string value2;
					if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value))
					{
						__instance.AddWord(key.Key, value);
					}
					else if (key.Localizations.TryGetValue("alias", out value2))
					{
						Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
					}
				}
			}
		}

		[<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
			[UsedImplicitly]
			public string Category;
		}

		[<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(0)]
		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		private static class Patch_Skills_IsSkillValid
		{
			private static void Postfix(SkillType type, ref bool __result)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (!__result && skills.ContainsKey(type))
				{
					__result = true;
				}
			}
		}

		private static readonly Dictionary<SkillType, Skill> skills;

		internal static readonly Dictionary<string, Skill> skillByName;

		private readonly string skillName;

		private readonly string internalSkillName;

		private readonly SkillDef skillDef;

		public readonly LocalizeKey Name;

		public readonly LocalizeKey Description;

		private float skillEffectFactor = 1f;

		private int skillLoss = 5;

		public bool Configurable;

		private static bool InitializedTerminal;

		[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		private static Localization _english;

		[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static bool hasConfigSync;

		[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		private static object _configSync;

		public float SkillGainFactor
		{
			get
			{
				return skillDef.m_increseStep;
			}
			set
			{
				skillDef.m_increseStep = value;
				this.SkillGainFactorChanged?.Invoke(value);
			}
		}

		public float SkillEffectFactor
		{
			get
			{
				return skillEffectFactor;
			}
			set
			{
				skillEffectFactor = value;
				this.SkillEffectFactorChanged?.Invoke(value);
			}
		}

		public int SkillLoss
		{
			get
			{
				return skillLoss;
			}
			set
			{
				skillLoss = value;
				this.SkillLossChanged?.Invoke(value);
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				object obj = _plugin;
				if (obj == null)
				{
					BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First([<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
					_plugin = val;
					obj = (object)val;
				}
				return (BaseUnityPlugin)obj;
			}
		}

		[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		private static object configSync
		{
			[<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(2)]
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		[method: <a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(2)]
		[field: <7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		public event Action<float> SkillGainFactorChanged;

		[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		[method: <a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(2)]
		[field: <7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		public event Action<float> SkillEffectFactorChanged;

		[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		[method: <a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(2)]
		[field: <7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)]
		public event Action<float> SkillLossChanged;

		public Skill(string englishName, string icon)
			: this(englishName, loadSprite(icon, 64, 64))
		{
		}

		public Skill(string englishName, Sprite icon)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			SkillType val = fromName(englishName);
			string text = new Regex("[^a-zA-Z]").Replace(englishName, "_");
			skills[val] = this;
			skillByName[englishName] = this;
			skillDef = new SkillDef
			{
				m_description = "$skilldesc_" + text,
				m_icon = icon,
				m_increseStep = 1f,
				m_skill = val
			};
			internalSkillName = text;
			skillName = englishName;
			Name = new LocalizeKey("skill_" + ((object)(SkillType)(ref val)).ToString()).English(englishName);
			Description = new LocalizeKey("skilldesc_" + text);
		}

		public static SkillType fromName(string englishName)
		{
			return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName));
		}

		static Skill()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			skills = new Dictionary<SkillType, Skill>();
			skillByName = new Dictionary<string, Skill>();
			InitializedTerminal = false;
			hasConfigSync = true;
			Harmony val = new Harmony("org.bepinex.helpers.skillmanager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null);
		}

		private static void Patch_FejdStartup()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			foreach (Skill skill in skills.Values)
			{
				if (skill.Configurable)
				{
					string key = skill.Name.Key;
					string group = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim();
					string category = Localization.instance.Localize(key).Trim();
					ConfigEntry<float> skillGain = config(group, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillGainFactor = skillGain.Value;
					skillGain.SettingChanged += [<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillGainFactor = skillGain.Value;
					};
					ConfigEntry<float> skillEffect = config(group, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillEffectFactor = skillEffect.Value;
					skillEffect.SettingChanged += [<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillEffectFactor = skillEffect.Value;
					};
					ConfigEntry<int> skillLoss = config(group, "Skill loss", skill.skillLoss, new ConfigDescription("How much experience to lose on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.skillLoss = skillLoss.Value;
					skillLoss.SettingChanged += [<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.skillLoss = skillLoss.Value;
					};
				}
			}
		}

		private static void Patch_Skills_GetSkillDef([<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)] ref SkillDef __result, List<SkillDef> ___m_skills, SkillType type)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (__result == null)
			{
				SkillDef val = GetSkillDef(type);
				if (val != null)
				{
					___m_skills.Add(val);
					__result = val;
				}
			}
		}

		private static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				SkillType current = key;
				Skill skill = skills[current];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					Skill skill2 = __instance.GetSkill(current);
					skill2.m_level += value;
					skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f);
					((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(SkillType)(ref current)).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon);
					Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level);
					return false;
				}
			}
			return true;
		}

		private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				Skill skill = skills[key];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					__instance.ResetSkill(key);
					Console.instance.Print("Skill " + skill.internalSkillName + " reset");
					return false;
				}
			}
			return true;
		}

		private static void Patch_Skills_OnDeath_Prefix(Skills __instance, [<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(new byte[] { 2, 1 })] ref Dictionary<SkillType, Skill> __state)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				__state = new Dictionary<SkillType, Skill>();
			}
			foreach (KeyValuePair<SkillType, Skill> skill in skills)
			{
				if (__instance.m_skillData.TryGetValue(skill.Key, out var value))
				{
					__state[skill.Key] = value;
					if (skill.Value.skillLoss > 0)
					{
						Skill obj = value;
						obj.m_level -= value.m_level * (float)skill.Value.SkillLoss / 100f;
						value.m_accumulator = 0f;
					}
					__instance.m_skillData.Remove(skill.Key);
				}
			}
		}

		private static void Patch_Skills_OnDeath_Finalizer(Skills __instance, [<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(new byte[] { 2, 1 })] ref Dictionary<SkillType, Skill> __state)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				return;
			}
			foreach (KeyValuePair<SkillType, Skill> item in __state)
			{
				__instance.m_skillData[item.Key] = item.Value;
			}
			__state = null;
		}

		private static void Patch_Terminal_InitTerminal_Prefix()
		{
			InitializedTerminal = Terminal.m_terminalInitialized;
		}

		private static void Patch_Terminal_InitTerminal()
		{
			if (!InitializedTerminal)
			{
				AddSkill(Terminal.commands["raiseskill"]);
				AddSkill(Terminal.commands["resetskill"]);
			}
			static void AddSkill(ConsoleCommand command)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Expected O, but got Unknown
				ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher;
				command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)([<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(0)] () =>
				{
					List<string> list = fetcher.Invoke();
					list.AddRange(skills.Values.Select([<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(0)] (Skill skill) => skill.internalSkillName));
					return list;
				});
			}
		}

		[<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(2)]
		private static SkillDef GetSkillDef(SkillType skillType)
		{
			//IL_0005: 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)
			if (!skills.ContainsKey(skillType))
			{
				return null;
			}
			return skills[skillType].skillDef;
		}

		private static byte[] ReadEmbeddedFileBytes(string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static Texture2D loadTexture(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_001f: Expected O, but got Unknown
			Texture2D val = new Texture2D(0, 0);
			ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name));
			return val;
		}

		private static Sprite loadSprite(string name, int width, int height)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero);
		}

		private static ConfigEntry<T> config<[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)] T>(string group, string name, T value, ConfigDescription description)
		{
			ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description);
			configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T))
				.Invoke(configSync, new object[1] { val });
			return val;
		}

		private static ConfigEntry<T> config<[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(2)] T>(string group, string name, T value, string description)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[<a04b077c-6bc3-4de9-992c-57dff8e59cc3>NullableContext(1)]
	[<7965ec9b-5cb0-4277-a65f-4a113ffb566c>Nullable(0)]
	[PublicAPI]
	internal static class SkillExtensions
	{
		public static float GetSkillFactor(this Character character, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return character.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static float GetSkillFactor(this Skills skills, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return skills.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static void RaiseSkill(this Character character, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			character.RaiseSkill(Skill.fromName(name), value);
		}

		public static void RaiseSkill(this Skills skill, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			skill.RaiseSkill(Skill.fromName(name), value);
		}

		public static void LowerSkill(this Character character, string name, float factor = 1f)
		{
			character.GetSkills().LowerSkill(name, factor);
		}

		public static void LowerSkill(this Skills skills, string name, float factor)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (factor > 0f && skills.m_skillData.TryGetValue(Skill.fromName(name), out var value))
			{
				Skill obj = value;
				obj.m_level -= value.m_level * factor;
				value.m_accumulator = 0f;
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	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;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			ZPackage package2 = package;
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package2.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package2 = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package2)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[HarmonyPatch]
	[PublicAPI]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			ZRpc rpc2 = rpc;
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}

BepInEx/plugins/Smoothbrain-PackHorse/PackHorse.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: Guid("0C62C6DA-BE1E-46D2-8629-C60E4A3E57EF")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyProduct("PackHorse")]
[assembly: AssemblyCompany("")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/PackHorse")]
[assembly: AssemblyTitle("PackHorse")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<c6f89937-7799-4593-96de-2bcef391f033>Embedded]
	internal sealed class <c6f89937-7799-4593-96de-2bcef391f033>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<c6f89937-7799-4593-96de-2bcef391f033>Embedded]
	[CompilerGenerated]
	internal sealed class <e32a93f9-7fab-4535-ad05-8c0f3c231e06>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <e32a93f9-7fab-4535-ad05-8c0f3c231e06>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <e32a93f9-7fab-4535-ad05-8c0f3c231e06>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<c6f89937-7799-4593-96de-2bcef391f033>Embedded]
	[CompilerGenerated]
	internal sealed class <7092b8ba-5e1a-4ca0-b6c7-58ff72f82001>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <7092b8ba-5e1a-4ca0-b6c7-58ff72f82001>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace PackHorse
{
	[BepInPlugin("org.bepinex.plugins.packhorse", "PackHorse", "1.0.2")]
	public class PackHorse : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(Character), "UpdateWalking")]
		private class AddSkillGain
		{
			private static float skillGainCounter;

			[UsedImplicitly]
			[<7092b8ba-5e1a-4ca0-b6c7-58ff72f82001>NullableContext(1)]
			private static void Postfix(Character __instance, float dt)
			{
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val != null && (Object)(object)val == (Object)(object)Player.m_localPlayer && (double)((Vector3)(ref ((Character)val).m_currentVel)).magnitude > 0.1 && (double)val.GetMaxCarryWeight() * 0.9 <= (double)((Humanoid)val).m_inventory.m_totalWeight)
				{
					skillGainCounter += dt;
					if (skillGainCounter > 1f)
					{
						skillGainCounter = 0f;
						((Character)(object)Player.m_localPlayer).RaiseSkill("PackHorse");
					}
				}
			}
		}

		[HarmonyPatch(typeof(Player), "GetMaxCarryWeight")]
		private class IncreaseCarryWeight
		{
			[<7092b8ba-5e1a-4ca0-b6c7-58ff72f82001>NullableContext(1)]
			[UsedImplicitly]
			private static void Postfix(Player __instance, ref float __result)
			{
				__result *= 1f + ((Character)(object)__instance).GetSkillFactor("PackHorse");
			}
		}

		[<e32a93f9-7fab-4535-ad05-8c0f3c231e06>Nullable(1)]
		private const string ModName = "PackHorse";

		[<e32a93f9-7fab-4535-ad05-8c0f3c231e06>Nullable(1)]
		private const string ModVersion = "1.0.2";

		[<e32a93f9-7fab-4535-ad05-8c0f3c231e06>Nullable(1)]
		private const string ModGUID = "org.bepinex.plugins.packhorse";

		public void Awake()
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			Skill skill = new Skill("PackHorse", "packhorse-icon.png");
			skill.Name.English("Pack horse");
			skill.Description.English("Increases the maximum carry weight.");
			skill.Name.German("Packesel");
			skill.Description.German("Erhöht das maximale Tragegewicht.");
			skill.Configurable = true;
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			Harmony val = new Harmony("org.bepinex.plugins.packhorse");
			val.PatchAll(executingAssembly);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[<26e3c858-cc4f-49f8-8b0d-4e4afb23577f>Embedded]
	[CompilerGenerated]
	internal sealed class <26e3c858-cc4f-49f8-8b0d-4e4afb23577f>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<26e3c858-cc4f-49f8-8b0d-4e4afb23577f>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <ea3f077c-f75e-4a04-a4c6-181a177d988a>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <ea3f077c-f75e-4a04-a4c6-181a177d988a>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <ea3f077c-f75e-4a04-a4c6-181a177d988a>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<26e3c858-cc4f-49f8-8b0d-4e4afb23577f>Embedded]
	internal sealed class <86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace SkillManager
{
	[<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(1)]
	[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(0)]
	[PublicAPI]
	internal class Skill
	{
		[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(0)]
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				string key = localizations.FirstOrDefault([<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance);
				}
			}

			public static Localization ForLanguage([<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)] string language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(0)]
		[PublicAPI]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", key);
			}

			public LocalizeKey Portuguese_Brazilian(string key)
			{
				return addForLang("Portuguese_Brazilian", key);
			}

			public LocalizeKey Chinese(string key)
			{
				return addForLang("Chinese", key);
			}

			public LocalizeKey Japanese(string key)
			{
				return addForLang("Japanese", key);
			}

			public LocalizeKey Korean(string key)
			{
				return addForLang("Korean", key);
			}

			public LocalizeKey Hindi(string key)
			{
				return addForLang("Hindi", key);
			}

			public LocalizeKey Thai(string key)
			{
				return addForLang("Thai", key);
			}

			public LocalizeKey Abenaki(string key)
			{
				return addForLang("Abenaki", key);
			}

			public LocalizeKey Croatian(string key)
			{
				return addForLang("Croatian", key);
			}

			public LocalizeKey Georgian(string key)
			{
				return addForLang("Georgian", key);
			}

			public LocalizeKey Greek(string key)
			{
				return addForLang("Greek", key);
			}

			public LocalizeKey Serbian(string key)
			{
				return addForLang("Serbian", key);
			}

			public LocalizeKey Ukrainian(string key)
			{
				return addForLang("Ukrainian", key);
			}

			private LocalizeKey addForLang(string lang, string value)
			{
				Localizations[lang] = value;
				if (Localization.instance.GetSelectedLanguage() == lang)
				{
					Localization.instance.AddWord(Key, value);
				}
				else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
				{
					Localization.instance.AddWord(Key, value);
				}
				return this;
			}

			[HarmonyPriority(300)]
			internal static void AddLocalizedKeys(Localization __instance, string language)
			{
				foreach (LocalizeKey key in keys)
				{
					string value2;
					if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value))
					{
						__instance.AddWord(key.Key, value);
					}
					else if (key.Localizations.TryGetValue("alias", out value2))
					{
						Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
					}
				}
			}
		}

		[<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)]
			[UsedImplicitly]
			public string Category;
		}

		[<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(0)]
		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		private static class Patch_Skills_IsSkillValid
		{
			private static void Postfix(SkillType type, ref bool __result)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (!__result && skills.ContainsKey(type))
				{
					__result = true;
				}
			}
		}

		private static readonly Dictionary<SkillType, Skill> skills;

		internal static readonly Dictionary<string, Skill> skillByName;

		private readonly string skillName;

		private readonly string internalSkillName;

		private readonly SkillDef skillDef;

		public readonly LocalizeKey Name;

		public readonly LocalizeKey Description;

		private float skillEffectFactor = 1f;

		public bool Configurable;

		private static bool InitializedTerminal;

		[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)]
		private static Localization _english;

		[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static bool hasConfigSync;

		[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)]
		private static object _configSync;

		public float SkillGainFactor
		{
			get
			{
				return skillDef.m_increseStep;
			}
			set
			{
				skillDef.m_increseStep = value;
				this.SkillGainFactorChanged?.Invoke(value);
			}
		}

		public float SkillEffectFactor
		{
			get
			{
				return skillEffectFactor;
			}
			set
			{
				skillEffectFactor = value;
				this.SkillEffectFactorChanged?.Invoke(value);
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				object obj = _plugin;
				if (obj == null)
				{
					BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First([<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
					_plugin = val;
					obj = (object)val;
				}
				return (BaseUnityPlugin)obj;
			}
		}

		[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)]
		private static object configSync
		{
			[<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(2)]
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)]
		[method: <86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(2)]
		[field: <ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)]
		public event Action<float> SkillGainFactorChanged;

		[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)]
		[method: <86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(2)]
		[field: <ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)]
		public event Action<float> SkillEffectFactorChanged;

		public Skill(string englishName, string icon)
			: this(englishName, loadSprite(icon, 64, 64))
		{
		}

		public Skill(string englishName, Sprite icon)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			SkillType val = fromName(englishName);
			string text = new Regex("[^a-zA-Z]").Replace(englishName, "_");
			skills[val] = this;
			skillByName[englishName] = this;
			skillDef = new SkillDef
			{
				m_description = "$skilldesc_" + text,
				m_icon = icon,
				m_increseStep = 1f,
				m_skill = val
			};
			internalSkillName = text;
			skillName = englishName;
			Name = new LocalizeKey("skill_" + ((object)(SkillType)(ref val)).ToString()).English(englishName);
			Description = new LocalizeKey("skilldesc_" + text);
		}

		public static SkillType fromName(string englishName)
		{
			return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName));
		}

		static Skill()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Expected O, but got Unknown
			skills = new Dictionary<SkillType, Skill>();
			skillByName = new Dictionary<string, Skill>();
			InitializedTerminal = false;
			hasConfigSync = true;
			Harmony val = new Harmony("org.bepinex.helpers.skillmanager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void Patch_FejdStartup()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			foreach (Skill skill in skills.Values)
			{
				if (skill.Configurable)
				{
					string key = skill.Name.Key;
					string group = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim();
					string category = Localization.instance.Localize(key).Trim();
					ConfigEntry<float> skillGain = config(group, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillGainFactor = skillGain.Value;
					skillGain.SettingChanged += [<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillGainFactor = skillGain.Value;
					};
					ConfigEntry<float> skillEffect = config(group, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillEffectFactor = skillEffect.Value;
					skillEffect.SettingChanged += [<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillEffectFactor = skillEffect.Value;
					};
				}
			}
		}

		private static void Patch_Skills_GetSkillDef([<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)] ref SkillDef __result, List<SkillDef> ___m_skills, SkillType type)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (__result == null)
			{
				SkillDef val = GetSkillDef(type);
				if (val != null)
				{
					___m_skills.Add(val);
					__result = val;
				}
			}
		}

		private static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				SkillType current = key;
				Skill skill = skills[current];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					Skill skill2 = __instance.GetSkill(current);
					skill2.m_level += value;
					skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f);
					((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(SkillType)(ref current)).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon);
					Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level);
					return false;
				}
			}
			return true;
		}

		private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				Skill skill = skills[key];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					__instance.ResetSkill(key);
					Console.instance.Print("Skill " + skill.internalSkillName + " reset");
					return false;
				}
			}
			return true;
		}

		private static void Patch_Terminal_InitTerminal_Prefix()
		{
			InitializedTerminal = Terminal.m_terminalInitialized;
		}

		private static void Patch_Terminal_InitTerminal()
		{
			if (!InitializedTerminal)
			{
				AddSkill(Terminal.commands["raiseskill"]);
				AddSkill(Terminal.commands["resetskill"]);
			}
			static void AddSkill(ConsoleCommand command)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Expected O, but got Unknown
				ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher;
				command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)([<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(0)] () =>
				{
					List<string> list = fetcher.Invoke();
					list.AddRange(skills.Values.Select([<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(0)] (Skill skill) => skill.internalSkillName));
					return list;
				});
			}
		}

		[<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(2)]
		private static SkillDef GetSkillDef(SkillType skillType)
		{
			//IL_0005: 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)
			if (!skills.ContainsKey(skillType))
			{
				return null;
			}
			return skills[skillType].skillDef;
		}

		private static byte[] ReadEmbeddedFileBytes(string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static Texture2D loadTexture(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_001f: Expected O, but got Unknown
			Texture2D val = new Texture2D(0, 0);
			ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name));
			return val;
		}

		private static Sprite loadSprite(string name, int width, int height)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero);
		}

		private static ConfigEntry<T> config<[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)] T>(string group, string name, T value, ConfigDescription description)
		{
			ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description);
			configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T))
				.Invoke(configSync, new object[1] { val });
			return val;
		}

		private static ConfigEntry<T> config<[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(2)] T>(string group, string name, T value, string description)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[PublicAPI]
	[<ea3f077c-f75e-4a04-a4c6-181a177d988a>Nullable(0)]
	[<86dc7728-ae1b-4c46-bea9-8c14f6fcb6aa>NullableContext(1)]
	internal static class SkillExtensions
	{
		public static float GetSkillFactor(this Character character, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return character.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static float GetSkillFactor(this Skills skills, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return skills.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static void RaiseSkill(this Character character, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			character.RaiseSkill(Skill.fromName(name), value);
		}

		public static void RaiseSkill(this Skills skill, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			skill.RaiseSkill(Skill.fromName(name), value);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					configSync2.IsSourceOfTruth = __instance.IsDedicated() || __instance.IsServer();
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_ConfigSync);
					if (isServer)
					{
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_InitialConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_InitialConfigSync(ZRpc rpc, ZPackage package)
		{
			RPC_ConfigSync(0L, package);
		}

		private void RPC_ConfigSync(long sender, ZPackage package)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Expected O, but got Unknown
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					bool? obj;
					if ((int)val == 0)
					{
						obj = null;
					}
					else
					{
						ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
						object obj2;
						if (currentRpc == null)
						{
							obj2 = null;
						}
						else
						{
							ISocket socket = currentRpc.GetSocket();
							obj2 = ((socket != null) ? socket.GetHostName() : null);
						}
						obj = val.Contains((string)obj2);
					}
					if (obj == false)
					{
						return;
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return;
					}
					configValueCache.Remove(text);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				if (!isServer)
				{
					if (IsSourceOfTruth)
					{
						lockedConfigChanged += serverLockedSettingChanged;
					}
					IsSourceOfTruth = false;
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				if (!isServer)
				{
					Debug.Log((object)$"Received {parsedConfigs.configValues.Count} configs and {parsedConfigs.customValues.Count} custom values from the server for mod {DisplayName ?? Name}");
					serverLockedSettingChanged();
				}
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			IsSourceOfTruth = true;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			ZPackage package2 = package;
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package2.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package2 = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package2)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[HarmonyPatch]
	[PublicAPI]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			ZRpc rpc2 = rpc;
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		[HarmonyPrefix]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}

BepInEx/plugins/Smoothbrain-Ranching/Ranching.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Guid("E591218A-1FFC-4897-9FAB-722892880928")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("Ranching")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/Ranching")]
[assembly: AssemblyTitle("Ranching")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<95fa6b17-d1ac-470a-b005-f1265d8a817a>Embedded]
	internal sealed class <95fa6b17-d1ac-470a-b005-f1265d8a817a>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<95fa6b17-d1ac-470a-b005-f1265d8a817a>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <bcec0f91-11c7-49dd-b4c5-35f06327cab2>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <bcec0f91-11c7-49dd-b4c5-35f06327cab2>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <bcec0f91-11c7-49dd-b4c5-35f06327cab2>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<95fa6b17-d1ac-470a-b005-f1265d8a817a>Embedded]
	internal sealed class <fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Ranching
{
	[BepInPlugin("org.bepinex.plugins.ranching", "Ranching", "1.1.2")]
	[<bcec0f91-11c7-49dd-b4c5-35f06327cab2>Nullable(0)]
	[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(1)]
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	public class Ranching : BaseUnityPlugin
	{
		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public bool? ShowRangeAsPercent;
		}

		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "Awake")]
		public class PlayerAwake
		{
			[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				((Character)__instance).m_nview.Register<int>("Ranching IncreaseSkill", (Action<long, int>)delegate(long _, int factor)
				{
					((Character)(object)__instance).RaiseSkill("Ranching", factor);
				});
			}
		}

		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "Update")]
		public class PlayerUpdate
		{
			[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					((Character)__instance).m_nview.GetZDO().Set("Ranching Skill", ((Character)__instance).GetSkillFactor(Skill.fromName("Ranching")));
				}
			}
		}

		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		[HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")]
		public class TamedCreatureDied
		{
			[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(1)]
			private static void Postfix(CharacterDrop __instance, [<bcec0f91-11c7-49dd-b4c5-35f06327cab2>Nullable(new byte[] { 1, 0, 1 })] List<KeyValuePair<GameObject, int>> __result)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				if (!__instance.m_character.IsTamed())
				{
					return;
				}
				Player closestPlayer = Player.GetClosestPlayer(((Component)__instance).transform.position, 50f);
				if (closestPlayer != null)
				{
					float num = ((Character)closestPlayer).m_nview.GetZDO().GetFloat("Ranching Skill", 0f) * (ranchingItemFactor.Value - 1f);
					int num2 = ((Random.Range(0f, 1f) < num % 1f) ? 1 : 0) + (int)num;
					for (int i = 0; i < __result.Count; i++)
					{
						__result[i] = new KeyValuePair<GameObject, int>(__result[i].Key, __result[i].Value * (1 + num2));
					}
					((Character)closestPlayer).m_nview.InvokeRPC("Ranching IncreaseSkill", new object[1] { 35 });
				}
			}
		}

		[HarmonyPatch(typeof(Tameable), "DecreaseRemainingTime")]
		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		public class TameFaster
		{
			[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(1)]
			private static void Prefix(Tameable __instance, ref float time)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				Player closestPlayer = Player.GetClosestPlayer(((Component)__instance).transform.position, 10f);
				if (closestPlayer != null)
				{
					time *= 1f + ((Character)closestPlayer).m_nview.GetZDO().GetFloat("Ranching Skill", 0f) * (ranchingTamingFactor.Value - 1f);
					if (Random.Range(0, 10) == 0)
					{
						((Character)closestPlayer).m_nview.InvokeRPC("Ranching IncreaseSkill", new object[1] { 5 });
					}
				}
			}
		}

		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
		public static class SetTamingFlag
		{
			public static bool gettingTamed;

			[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(1)]
			private static void Prefix(MonsterAI __instance)
			{
				Tameable component = ((Component)((BaseAI)__instance).m_character).GetComponent<Tameable>();
				if (component != null && component.GetTameness() > 0)
				{
					gettingTamed = true;
				}
			}

			private static void Finalizer()
			{
				gettingTamed = false;
			}
		}

		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		[HarmonyPatch(typeof(Player), "GetStealthFactor")]
		public static class DoNotAlert
		{
			[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(1)]
			private static bool Prefix(Player __instance, ref float __result)
			{
				if (SetTamingFlag.gettingTamed && ((Character)__instance).m_nview.GetZDO().GetFloat("Ranching Skill", 0f) >= (float)ranchingCalmLevel.Value / 100f && ranchingCalmLevel.Value > 0)
				{
					__result = 0f;
					return false;
				}
				return true;
			}
		}

		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		[HarmonyPatch(typeof(Tameable), "GetStatusString")]
		private static class DisplayInformation
		{
			[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(1)]
			private static void Postfix(Tameable __instance, ref string __result)
			{
				if (!__instance.m_character.IsTamed())
				{
					return;
				}
				Procreation component = ((Component)__instance).GetComponent<Procreation>();
				if (component != null && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Ranching") >= (float)ranchingPregnancyLevel.Value / 100f && ranchingPregnancyLevel.Value > 0)
				{
					if (component.IsPregnant())
					{
						long num = __instance.m_nview.GetZDO().GetLong("pregnant", 0L) + ToTicks(component.m_pregnancyDuration + 1f);
						long num2 = num + (ToTicks(ProcreationTimeOffset(component)) - num) % ToTicks(component.m_updateInterval);
						if (num2 < num)
						{
							num2 += ToTicks(component.m_updateInterval);
						}
						TimeSpan timeSpan = new DateTime(num2) - ZNet.instance.GetTime();
						__result += $", Pregnancy: {timeSpan:hh\\:mm\\:ss}";
					}
					else
					{
						int num3 = Mathf.RoundToInt((float)__instance.m_nview.GetZDO().GetInt("lovePoints", 0) / (float)component.m_requiredLovePoints * 100f);
						__result += $", Pre-Pregnancy: {num3}%";
					}
				}
				if (!__instance.IsHungry() && ((Character)(object)Player.m_localPlayer).GetSkillFactor("Ranching") >= (float)ranchingFoodLevel.Value / 100f && ranchingFoodLevel.Value > 0)
				{
					TimeSpan timeSpan2 = new DateTime(__instance.m_nview.GetZDO().GetLong("TameLastFeeding", 0L)).AddSeconds(__instance.m_fedDuration) - ZNet.instance.GetTime();
					__result += $", Hungry in: {timeSpan2:hh\\:mm\\:ss}";
				}
				static long ToTicks(double seconds)
				{
					return (long)(seconds * 10000000.0);
				}
			}
		}

		[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)]
		[HarmonyPatch(typeof(Procreation), "Awake")]
		private static class StableProcreatingTimes
		{
			[<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(1)]
			private static void Postfix(Procreation __instance)
			{
				((MonoBehaviour)__instance).CancelInvoke("Procreate");
				double timeSeconds = ZNet.instance.GetTimeSeconds();
				((MonoBehaviour)__instance).InvokeRepeating("Procreate", (float)((double)__instance.m_updateInterval - timeSeconds % (double)__instance.m_updateInterval + (double)ProcreationTimeOffset(__instance)) % __instance.m_updateInterval, __instance.m_updateInterval);
			}
		}

		private const string ModName = "Ranching";

		private const string ModVersion = "1.1.2";

		private const string ModGUID = "org.bepinex.plugins.ranching";

		private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.ranching")
		{
			DisplayName = "Ranching",
			CurrentVersion = "1.1.2",
			MinimumRequiredVersion = "1.1.2"
		};

		private static ConfigEntry<Toggle> serverConfigLocked = null;

		private static ConfigEntry<float> ranchingItemFactor = null;

		private static ConfigEntry<float> ranchingTamingFactor = null;

		private static ConfigEntry<int> ranchingFoodLevel = null;

		private static ConfigEntry<int> ranchingCalmLevel = null;

		private static ConfigEntry<int> ranchingPregnancyLevel = null;

		private static ConfigEntry<float> experienceGainedFactor = null;

		private static ConfigEntry<int> experienceLoss = null;

		private static Skill ranching = null;

		private ConfigEntry<T> config<[<bcec0f91-11c7-49dd-b4c5-35f06327cab2>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(val);
			syncedConfigEntry.SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<bcec0f91-11c7-49dd-b4c5-35f06327cab2>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Expected O, but got Unknown
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Expected O, but got Unknown
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Expected O, but got Unknown
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Expected O, but got Unknown
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Expected O, but got Unknown
			ranching = new Skill("Ranching", "ranching.png");
			ranching.Description.English("Reduces the time required to tame animals and increases item yield of tamed animals.");
			ranching.Name.German("Viehhaltung");
			ranching.Description.German("Reduziert die Zeit, die benötigt wird, um ein Tier zu zähmen und erhöht die Ausbeute von gezähmten Tieren.");
			ranching.Configurable = false;
			serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			ranchingItemFactor = config("2 - Ranching", "Item Drop Factor", 2f, new ConfigDescription("Item drop factor for tamed creatures at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			ranchingTamingFactor = config("2 - Ranching", "Taming Factor", 2f, new ConfigDescription("Speed at which creatures get tame at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			ranchingFoodLevel = config("2 - Ranching", "Food Level Requirement", 10, new ConfigDescription("Minimum required skill level to see when tamed creatures will become hungry again. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			ranchingCalmLevel = config("2 - Ranching", "Calming Level Requirement", 20, new ConfigDescription("Minimum required skill level to calm nearby taming creatures. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			ranchingPregnancyLevel = config("2 - Ranching", "Pregnancy Level Requirement", 40, new ConfigDescription("Minimum required skill level to get pregnancy related information of tame creatures. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					ShowRangeAsPercent = false
				}
			}));
			experienceGainedFactor = config("3 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the ranching skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>()));
			experienceGainedFactor.SettingChanged += [<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)] (object _, EventArgs _) =>
			{
				ranching.SkillGainFactor = experienceGainedFactor.Value;
			};
			ranching.SkillGainFactor = experienceGainedFactor.Value;
			experienceLoss = config("3 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the ranching skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			experienceLoss.SettingChanged += [<fbd0af96-10c4-4f43-abd8-8eaba0abdc0a>NullableContext(0)] (object _, EventArgs _) =>
			{
				ranching.SkillLoss = experienceLoss.Value;
			};
			ranching.SkillLoss = experienceLoss.Value;
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			Harmony val = new Harmony("org.bepinex.plugins.ranching");
			val.PatchAll(executingAssembly);
		}

		private static int ProcreationTimeOffset(Procreation procreation)
		{
			//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_003a: Unknown result type (might be due to invalid IL or missing references)
			State state = Random.state;
			try
			{
				Random.InitState(((object)(ZDOID)(ref procreation.m_nview.GetZDO().m_uid)).GetHashCode());
				return (int)(Random.value * procreation.m_updateInterval);
			}
			finally
			{
				Random.state = state;
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<fca817f4-acbd-43b5-a2d0-48abad92bfd0>Embedded]
	internal sealed class <fca817f4-acbd-43b5-a2d0-48abad92bfd0>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<fca817f4-acbd-43b5-a2d0-48abad92bfd0>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <8efac838-edca-431c-bcbd-b561d5b10d86>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <8efac838-edca-431c-bcbd-b561d5b10d86>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <8efac838-edca-431c-bcbd-b561d5b10d86>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<fca817f4-acbd-43b5-a2d0-48abad92bfd0>Embedded]
	internal sealed class <d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[<fca817f4-acbd-43b5-a2d0-48abad92bfd0>Embedded]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
	[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
	internal abstract class OwnConfigEntryBase
	{
		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		public object LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
	[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
	internal class SyncedConfigEntry<[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)] T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(2)]
	[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
	internal abstract class CustomSyncedValueBase
	{
		public object LocalBaseValue;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(1)]
		public readonly string Identifier;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(1)]
		public readonly Type Type;

		private object boxedValue;

		protected bool localIsOwner;

		public object BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action ValueChanged;

		[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
	[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
	internal sealed class CustomSyncedValue<[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)] T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
	[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)]
		private static class SnatchCurrentlyHandlingRPC
		{
			[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
			public static ZRpc currentRpc;

			[HarmonyPrefix]
			[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)]
		private class ParsedConfigs
		{
			[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>();

			[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 1, 1, 2 })]
			public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)]
		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix([<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
			public object value;
		}

		[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)]
		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		public string DisplayName;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		public string CurrentVersion;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		public string MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		private OwnConfigEntryBase lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 1, 0, 1 })]
		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		[method: <d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(2)]
		[field: <8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		public event Action<bool> SourceOfTruthChanged;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		[method: <d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(2)]
		[field: <8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		private event Action lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)] T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += [<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (object _, EventArgs _) =>
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)] T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += [<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (object _, EventArgs _) =>
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(([<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 0, 1 })] KeyValuePair<long, string> kv) =>
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out var value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		[return: <8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		private static OwnConfigEntryBase configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		[return: <8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 2, 1 })]
		public static SyncedConfigEntry<T> ConfigData<[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)] T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)] T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage([<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 2, 1 })] IEnumerable<ConfigEntryBase> configs = null, [<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 2, 1 })] IEnumerable<CustomSyncedValueBase> customValues = null, [<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 2, 1 })] IEnumerable<PackageEntry> packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, [<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)] object value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[HarmonyPatch]
	[<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(1)]
	[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(0)]
	[PublicAPI]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		private string displayName;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		private string currentVersion;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		private string minimumRequiredVersion;

		public bool ModRequired = true;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		private string ReceivedCurrentVersion;

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		private string ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		[<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)]
		private ConfigSync ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error([<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(2)] ZRpc rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, [<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(new byte[] { 2, 1, 1 })] Action<ZRpc, ZPackage> original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (ZRpc rpc, [<8efac838-edca-431c-bcbd-b561d5b10d86>Nullable(1)] ZPackage pkg) =>
				{
					CheckVersion(rpc, pkg, action);
				}));
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy([<d5650929-494f-4f38-a9ca-9c92bd7c330a>NullableContext(0)] (KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace SkillManager
{
	[PublicAPI]
	internal class Skill
	{
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				Localization __instance2 = __instance;
				string key = localizations.FirstOrDefault<KeyValuePair<string, Localization>>((KeyValuePair<string, Localization> l) => l.Value == __instance2).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance2);
				}
			}

			public static Localization ForLanguage(string? language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out Localization value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[PublicAPI]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", key);
			}

			public LocalizeKey Portuguese_Brazilian(string key)
			{
				return addForLang("Portuguese_Brazilian", key);
			}

			public LocalizeKey Chinese(string key)
			{
				return addForLang("Chinese", key);
			}

			public LocalizeKey Japanese(string key)
			{
				return addForLang("Japanese", key);
			}

			public LocalizeKey Korean(string key)
			{
				return addForLang("Korean", key);
			}

			public LocalizeKey Hindi(string key)
			{
				return addForLang("Hindi", key);
			}

			public LocalizeKey Thai(string key)
			{
				return addForLang("Thai", key);
			}

			public LocalizeKey Abenaki(string key)
			{
				return addForLang("Abenaki", key);
			}

			public LocalizeKey Croatian(string key)
			{
				return addForLang("Croatian", key);
			}

			public LocalizeKey Georgian(string key)
			{
				return addForLang("Georgian", key);
			}

			public LocalizeKey Greek(string key)
			{
				return addForLang("Greek", key);
			}

			public LocalizeKey Serbian(string key)
			{
				return addForLang("Serbian", key);
			}

			public LocalizeKey Ukrainian(string key)
			{
				return addForLang("Ukrainian", key);
			}

			private LocalizeKey addForLang(string lang, string value)
			{
				Localizations[lang] = value;
				if (Localization.instance.GetSelectedLanguage() == lang)
				{
					Localization.instance.AddWord(Key, value);
				}
				else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
				{
					Localization.instance.AddWord(Key, value);
				}
				return this;
			}

			[HarmonyPriority(300)]
			internal static void AddLocalizedKeys(Localization __instance, string language)
			{
				foreach (LocalizeKey key in keys)
				{
					string value2;
					if (key.Localizations.TryGetValue(language, out string value) || key.Localizations.TryGetValue("English", out value))
					{
						__instance.AddWord(key.Key, value);
					}
					else if (key.Localizations.TryGetValue("alias", out value2))
					{
						Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
					}
				}
			}
		}

		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public string? Category;
		}

		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		private static class Patch_Skills_IsSkillValid
		{
			private static void Postfix(SkillType type, ref bool __result)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (!__result && skills.ContainsKey(type))
				{
					__result = true;
				}
			}
		}

		private static readonly Dictionary<SkillType, Skill> skills;

		internal static readonly Dictionary<string, Skill> skillByName;

		private readonly string skillName;

		private readonly string internalSkillName;

		private readonly SkillDef skillDef;

		public readonly LocalizeKey Name;

		public readonly LocalizeKey Description;

		private float skillEffectFactor = 1f;

		private int skillLoss = 5;

		public bool Configurable;

		private static bool InitializedTerminal;

		private static Localization? _english;

		private static BaseUnityPlugin? _plugin;

		private static bool hasConfigSync;

		private static object? _configSync;

		public float SkillGainFactor
		{
			get
			{
				return skillDef.m_increseStep;
			}
			set
			{
				skillDef.m_increseStep = value;
				this.SkillGainFactorChanged?.Invoke(value);
			}
		}

		public float SkillEffectFactor
		{
			get
			{
				return skillEffectFactor;
			}
			set
			{
				skillEffectFactor = value;
				this.SkillEffectFactorChanged?.Invoke(value);
			}
		}

		public int SkillLoss
		{
			get
			{
				return skillLoss;
			}
			set
			{
				skillLoss = value;
				this.SkillLossChanged?.Invoke(value);
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				object obj = _plugin;
				if (obj == null)
				{
					BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
					_plugin = val;
					obj = (object)val;
				}
				return (BaseUnityPlugin)obj;
			}
		}

		private static object? configSync
		{
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		public event Action<float>? SkillGainFactorChanged;

		public event Action<float>? SkillEffectFactorChanged;

		public event Action<float>? SkillLossChanged;

		public Skill(string englishName, string icon)
			: this(englishName, loadSprite(icon, 64, 64))
		{
		}

		public Skill(string englishName, Sprite icon)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			SkillType val = fromName(englishName);
			string text = new Regex("[^a-zA-Z]").Replace(englishName, "_");
			skills[val] = this;
			skillByName[englishName] = this;
			skillDef = new SkillDef
			{
				m_description = "$skilldesc_" + text,
				m_icon = icon,
				m_increseStep = 1f,
				m_skill = val
			};
			internalSkillName = text;
			skillName = englishName;
			Name = new LocalizeKey("skill_" + ((object)(SkillType)(ref val)).ToString()).English(englishName);
			Description = new LocalizeKey("skilldesc_" + text);
		}

		public static SkillType fromName(string englishName)
		{
			return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName));
		}

		static Skill()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			skills = new Dictionary<SkillType, Skill>();
			skillByName = new Dictionary<string, Skill>();
			InitializedTerminal = false;
			hasConfigSync = true;
			Harmony val = new Harmony("org.bepinex.helpers.skillmanager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null);
		}

		private static void Patch_FejdStartup()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			foreach (Skill skill in skills.Values)
			{
				if (skill.Configurable)
				{
					string key = skill.Name.Key;
					string group = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim();
					string category = Localization.instance.Localize(key).Trim();
					ConfigEntry<float> skillGain = config(group, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillGainFactor = skillGain.Value;
					skillGain.SettingChanged += delegate
					{
						skill.SkillGainFactor = skillGain.Value;
					};
					ConfigEntry<float> skillEffect = config(group, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillEffectFactor = skillEffect.Value;
					skillEffect.SettingChanged += delegate
					{
						skill.SkillEffectFactor = skillEffect.Value;
					};
					ConfigEntry<int> skillLoss = config(group, "Skill loss", skill.skillLoss, new ConfigDescription("How much experience to lose on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.skillLoss = skillLoss.Value;
					skillLoss.SettingChanged += delegate
					{
						skill.skillLoss = skillLoss.Value;
					};
				}
			}
		}

		private static void Patch_Skills_GetSkillDef(ref SkillDef? __result, List<SkillDef> ___m_skills, SkillType type)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (__result == null)
			{
				SkillDef val = GetSkillDef(type);
				if (val != null)
				{
					___m_skills.Add(val);
					__result = val;
				}
			}
		}

		private static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				SkillType current = key;
				Skill skill = skills[current];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					Skill skill2 = __instance.GetSkill(current);
					skill2.m_level += value;
					skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f);
					((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(SkillType)(ref current)).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon);
					Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level);
					return false;
				}
			}
			return true;
		}

		private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				Skill skill = skills[key];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					__instance.ResetSkill(key);
					Console.instance.Print("Skill " + skill.internalSkillName + " reset");
					return false;
				}
			}
			return true;
		}

		private static void Patch_Skills_OnDeath_Prefix(Skills __instance, ref Dictionary<SkillType, Skill>? __state)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				__state = new Dictionary<SkillType, Skill>();
			}
			foreach (KeyValuePair<SkillType, Skill> skill in skills)
			{
				if (__instance.m_skillData.TryGetValue(skill.Key, out var value))
				{
					__state[skill.Key] = value;
					if (skill.Value.skillLoss > 0)
					{
						Skill obj = value;
						obj.m_level -= value.m_level * (float)skill.Value.SkillLoss / 100f;
						value.m_accumulator = 0f;
					}
					__instance.m_skillData.Remove(skill.Key);
				}
			}
		}

		private static void Patch_Skills_OnDeath_Finalizer(Skills __instance, ref Dictionary<SkillType, Skill>? __state)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				return;
			}
			foreach (KeyValuePair<SkillType, Skill> item in __state)
			{
				__instance.m_skillData[item.Key] = item.Value;
			}
			__state = null;
		}

		private static void Patch_Terminal_InitTerminal_Prefix()
		{
			InitializedTerminal = Terminal.m_terminalInitialized;
		}

		private static void Patch_Terminal_InitTerminal()
		{
			if (!InitializedTerminal)
			{
				AddSkill(Terminal.commands["raiseskill"]);
				AddSkill(Terminal.commands["resetskill"]);
			}
			static void AddSkill(ConsoleCommand command)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Expected O, but got Unknown
				ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher;
				command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)delegate
				{
					List<string> list = fetcher.Invoke();
					list.AddRange(skills.Values.Select((Skill skill) => skill.internalSkillName));
					return list;
				};
			}
		}

		private static SkillDef? GetSkillDef(SkillType skillType)
		{
			//IL_0005: 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)
			if (!skills.ContainsKey(skillType))
			{
				return null;
			}
			return skills[skillType].skillDef;
		}

		private static byte[] ReadEmbeddedFileBytes(string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static Texture2D loadTexture(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_001f: Expected O, but got Unknown
			Texture2D val = new Texture2D(0, 0);
			ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name));
			return val;
		}

		private static Sprite loadSprite(string name, int width, int height)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero);
		}

		private static ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description)
		{
			ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description);
			configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T))
				.Invoke(configSync, new object[1] { val });
			return val;
		}

		private static ConfigEntry<T> config<T>(string group, string name, T value, string description)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[PublicAPI]
	internal static class SkillExtensions
	{
		public static float GetSkillFactor(this Character character, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return character.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static float GetSkillFactor(this Skills skills, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return skills.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static void RaiseSkill(this Character character, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			character.RaiseSkill(Skill.fromName(name), value);
		}

		public static void RaiseSkill(this Skills skill, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			skill.RaiseSkill(Skill.fromName(name), value);
		}

		public static void LowerSkill(this Character character, string name, float factor = 1f)
		{
			character.GetSkills().LowerSkill(name, factor);
		}

		public static void LowerSkill(this Skills skills, string name, float factor)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (factor > 0f && skills.m_skillData.TryGetValue(Skill.fromName(name), out var value))
			{
				Skill obj = value;
				obj.m_level -= value.m_level * factor;
				value.m_accumulator = 0f;
			}
		}
	}
}

BepInEx/plugins/Smoothbrain-Sailing/Sailing.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: Guid("F7B25B5A-5CFB-43CA-934A-440CDB9CB1A9")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyProduct("Sailing")]
[assembly: AssemblyCompany("")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/Sailing")]
[assembly: AssemblyTitle("Sailing")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<32097ee9-7afe-4ac7-96cb-b02b56d79cbf>Embedded]
	internal sealed class <32097ee9-7afe-4ac7-96cb-b02b56d79cbf>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<32097ee9-7afe-4ac7-96cb-b02b56d79cbf>Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <b737b9e9-2eeb-49ad-8009-21ded1d2e095>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <b737b9e9-2eeb-49ad-8009-21ded1d2e095>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <b737b9e9-2eeb-49ad-8009-21ded1d2e095>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<32097ee9-7afe-4ac7-96cb-b02b56d79cbf>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <358225d2-09f4-482e-85e0-c41edd8462c8>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <358225d2-09f4-482e-85e0-c41edd8462c8>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Sailing
{
	[BepInPlugin("org.bepinex.plugins.sailing", "Sailing", "1.1.6")]
	[<b737b9e9-2eeb-49ad-8009-21ded1d2e095>Nullable(0)]
	[BepInIncompatibility("org.bepinex.plugins.valheim_plus")]
	[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
	public class Sailing : BaseUnityPlugin
	{
		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		private enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(2)]
		[<b737b9e9-2eeb-49ad-8009-21ded1d2e095>Nullable(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public bool? ShowRangeAsPercent;

			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public string Description;

			[UsedImplicitly]
			public string DispName;
		}

		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		[HarmonyPatch(typeof(WearNTear), "OnPlaced")]
		private class AddZDO
		{
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			[UsedImplicitly]
			private static void Postfix(WearNTear __instance)
			{
				if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<Ship>()))
				{
					((Component)__instance).GetComponent<ZNetView>().GetZDO().Set("Sailing Skill Level", ((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing"));
					__instance.m_health *= 1f + ((Component)__instance).GetComponent<ZNetView>().GetZDO().GetFloat("Sailing Skill Level", 0f) * shipHealthIncrease.Value;
					((Character)(object)Player.m_localPlayer).RaiseSkill("Sailing", 35f);
				}
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		private class FetchShipPiecesObjectDB
		{
			[HarmonyPriority(0)]
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			private static void Postfix(ObjectDB __instance)
			{
				GameObject itemPrefab = __instance.GetItemPrefab("Hammer");
				PieceTable val = ((itemPrefab == null) ? null : itemPrefab.GetComponent<ItemDrop>()?.m_itemData.m_shared.m_buildPieces);
				if (val != null)
				{
					FetchShipPieces(val.m_pieces);
				}
			}
		}

		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private class FetchShipPiecesZNetScene
		{
			[HarmonyPriority(0)]
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			private static void Postfix(ZNetScene __instance)
			{
				FetchShipPieces(__instance.m_prefabs);
			}
		}

		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		[HarmonyPatch(typeof(Ladder), "Interact")]
		private static class NudgeShip
		{
			private static DateTime lastNudge = DateTime.UtcNow;

			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			private static bool Prefix(Ladder __instance)
			{
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: Unknown result type (might be due to invalid IL or missing references)
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
				//IL_0106: Unknown result type (might be due to invalid IL or missing references)
				if (allowShipNudge.Value == Toggle.Off || ((Character)Player.m_localPlayer).IsSwimming())
				{
					return true;
				}
				KeyboardShortcut value = shipNudgeModifierkey.Value;
				if (Input.GetKey(((KeyboardShortcut)(ref value)).MainKey))
				{
					value = shipNudgeModifierkey.Value;
					if (((KeyboardShortcut)(ref value)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey))
					{
						if ((DateTime.UtcNow - lastNudge).TotalSeconds < 1.0)
						{
							return false;
						}
						lastNudge = DateTime.UtcNow;
						Rigidbody componentInParent = ((Component)__instance).GetComponentInParent<Rigidbody>();
						if (Math.Abs(Vector3.SignedAngle(((Component)componentInParent).transform.position - ((Component)Player.m_localPlayer).transform.position, ((Component)Player.m_localPlayer).transform.forward, ((Component)Player.m_localPlayer).transform.up)) < 90f)
						{
							componentInParent.AddForce(((Component)Player.m_localPlayer).transform.forward * componentInParent.mass * nudgeForce.Value, (ForceMode)1);
						}
						else
						{
							((Character)Player.m_localPlayer).Message((MessageType)2, "Please don't nudge your ship with your butt.", 0, (Sprite)null);
						}
						return false;
					}
				}
				return true;
			}
		}

		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		[HarmonyPatch(typeof(Ladder), "GetHoverText")]
		private class OverrideHoverText
		{
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			public static void Postfix(ref string __result)
			{
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				if (allowShipNudge.Value != 0)
				{
					__result += Localization.instance.Localize($"\n[<b><color=yellow>{shipNudgeModifierkey.Value}</color> + <color=yellow>$KEY_Use</color></b>] Push ship");
				}
			}
		}

		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		[HarmonyPatch(typeof(WearNTear), "Awake")]
		private class IncreaseHealth
		{
			[UsedImplicitly]
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			private static void Prefix(WearNTear __instance)
			{
				float health = __instance.m_health;
				ZDO zDO = ((Component)__instance).GetComponent<ZNetView>().GetZDO();
				__instance.m_health = health * (1f + ((zDO != null) ? zDO.GetFloat("Sailing Skill Level", 0f) : (Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<Ship>()) ? ((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing") : 1f)) * shipHealthIncrease.Value);
			}
		}

		[HarmonyPatch(typeof(Minimap), "Explore", new Type[]
		{
			typeof(Vector3),
			typeof(float)
		})]
		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		private class IncreaseExplorationRadius
		{
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			[UsedImplicitly]
			private static void Prefix(Minimap __instance, ref float radius)
			{
				Player localPlayer = Player.m_localPlayer;
				if (localPlayer != null && localPlayer.m_attached && localPlayer.m_attachedToShip)
				{
					radius *= 1f + ((Character)(object)localPlayer).GetSkillFactor("Sailing") * explorationRadiusIncrease.Value;
				}
			}
		}

		[HarmonyPatch(typeof(Ship), "GetSailForce")]
		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		private class ChangeShipSpeed
		{
			[UsedImplicitly]
			private class Timer
			{
				public float UpdateDelta;

				public float lastUpdate = Time.fixedTime;
			}

			[<b737b9e9-2eeb-49ad-8009-21ded1d2e095>Nullable(1)]
			private static readonly ConditionalWeakTable<Ship, Timer> timers = new ConditionalWeakTable<Ship, Timer>();

			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			private static void Postfix(Ship __instance, ref Vector3 __result)
			{
				//IL_0097: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0087: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				Timer orCreateValue = timers.GetOrCreateValue(__instance);
				Player val = ((IEnumerable<Player>)Player.s_players).FirstOrDefault((Func<Player, bool>)((Player p) => p.GetPlayerID() == __instance.m_shipControlls.GetUser()));
				if (val != null)
				{
					if (shipSpeedIncrease.TryGetValue(((Component)__instance).GetComponent<Piece>().m_name, out var value))
					{
						__result *= 1f + ((Character)val).m_nview.GetZDO().GetFloat("Sailing Skill", 0f) * value.Value;
					}
					if ((int)__instance.m_speed != 0)
					{
						orCreateValue.UpdateDelta += Time.fixedTime - orCreateValue.lastUpdate;
						if (orCreateValue.UpdateDelta > 1f)
						{
							((Character)val).m_nview.InvokeRPC("Sailing Skill Increase", new object[1] { 0.5f });
							orCreateValue.UpdateDelta -= 1f;
						}
					}
				}
				orCreateValue.lastUpdate = Time.fixedTime;
			}
		}

		[HarmonyPatch(typeof(Ship), "Forward")]
		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		private class PreventShipSpeeds
		{
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			private static bool Prefix(Ship __instance)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Invalid comparison between Unknown and I4
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_005f: Invalid comparison between Unknown and I4
				if ((int)__instance.m_speed == 2 && shipHalfRequirement.TryGetValue(((Component)__instance).GetComponent<Piece>().m_name, out var value) && value.Value > Mathf.RoundToInt(((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing") * 100f))
				{
					((Character)Player.m_localPlayer).Message((MessageType)2, "Your sailing skill is too low to sail this ship with reduced sail.", 0, (Sprite)null);
					return false;
				}
				if ((int)__instance.m_speed == 3 && shipFullRequirement.TryGetValue(((Component)__instance).GetComponent<Piece>().m_name, out var value2) && value2.Value > Mathf.RoundToInt(((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing") * 100f))
				{
					((Character)Player.m_localPlayer).Message((MessageType)2, "Your sailing skill is too low to sail this ship with full sail.", 0, (Sprite)null);
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(ShipControlls), "Interact")]
		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		private class BlockSailing
		{
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			private static bool Prefix(ShipControlls __instance)
			{
				if (!shipPaddleRequirement.TryGetValue(((Component)__instance.m_ship).GetComponent<Piece>().m_name, out var value) || value.Value <= Mathf.RoundToInt(((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing") * 100f))
				{
					return true;
				}
				((Character)Player.m_localPlayer).Message((MessageType)2, "Your sailing skill is too low to command this ship.", 0, (Sprite)null);
				return false;
			}
		}

		[HarmonyPatch(typeof(Player), "Awake")]
		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		private class ExposeSailingSkill
		{
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				((Character)__instance).m_nview.Register<float>("Sailing Skill Increase", (Action<long, float>)delegate(long _, float amount)
				{
					((Character)(object)__instance).RaiseSkill("Sailing", amount);
				});
			}
		}

		[HarmonyPatch(typeof(Player), "Update")]
		[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)]
		public class PlayerUpdate
		{
			[<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(1)]
			private static void Postfix(Player __instance)
			{
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					((Character)__instance).m_nview.GetZDO().Set("Sailing Skill", ((Character)(object)__instance).GetSkillFactor("Sailing"));
				}
			}
		}

		private const string ModName = "Sailing";

		private const string ModVersion = "1.1.6";

		private const string ModGUID = "org.bepinex.plugins.sailing";

		private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.sailing")
		{
			DisplayName = "Sailing",
			CurrentVersion = "1.1.6",
			MinimumRequiredVersion = "1.1.6"
		};

		private static ConfigEntry<Toggle> serverConfigLocked = null;

		private static ConfigEntry<float> explorationRadiusIncrease = null;

		private static ConfigEntry<float> shipHealthIncrease = null;

		private static ConfigEntry<float> experienceGainedFactor = null;

		private static ConfigEntry<int> experienceLoss = null;

		private static ConfigEntry<KeyboardShortcut> shipNudgeModifierkey = null;

		private static ConfigEntry<Toggle> allowShipNudge = null;

		private static ConfigEntry<float> nudgeForce = null;

		private static readonly Dictionary<string, ConfigEntry<float>> shipSpeedIncrease = new Dictionary<string, ConfigEntry<float>>();

		private static readonly Dictionary<string, ConfigEntry<int>> shipPaddleRequirement = new Dictionary<string, ConfigEntry<int>>();

		private static readonly Dictionary<string, ConfigEntry<int>> shipHalfRequirement = new Dictionary<string, ConfigEntry<int>>();

		private static readonly Dictionary<string, ConfigEntry<int>> shipFullRequirement = new Dictionary<string, ConfigEntry<int>>();

		private static Skill sailing = null;

		private static Sailing mod = null;

		private ConfigEntry<T> config<[<b737b9e9-2eeb-49ad-8009-21ded1d2e095>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
			configSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> config<[<b737b9e9-2eeb-49ad-8009-21ded1d2e095>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public void Awake()
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Expected O, but got Unknown
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Expected O, but got Unknown
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Expected O, but got Unknown
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Expected O, but got Unknown
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			sailing = new Skill("Sailing", "sailing.png");
			sailing.Description.English("Increases the health of ships built by you, sailing speed of ships commanded by you and your exploration radius while on a ship.");
			sailing.Name.German("Segeln");
			sailing.Description.German("Erhöht die Lebenspunkte von dir gebauter Schiffe, erhöht die Geschwindigkeiten von Schiffen, die du steuerst und erhöht deinen Erkundungsradius, wenn du dich auf einem Schiff befindest.");
			sailing.Configurable = false;
			serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked);
			shipNudgeModifierkey = config<KeyboardShortcut>("1 - General", "Ship Nudge Modifier Key", new KeyboardShortcut((KeyCode)304, Array.Empty<KeyCode>()), new ConfigDescription("Modifier key to hold, to nudge your ship. Clear value to disable this.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false);
			explorationRadiusIncrease = config("3 - Other", "Exploration Radius Factor", 5f, new ConfigDescription("Exploration radius factor while on ships at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			shipHealthIncrease = config("3 - Other", "Ship Health Factor", 2f, new ConfigDescription("Health factor for ships at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>()));
			experienceGainedFactor = config("3 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the sailing skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>()));
			experienceGainedFactor.SettingChanged += [<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)] (object _, EventArgs _) =>
			{
				sailing.SkillGainFactor = experienceGainedFactor.Value;
			};
			sailing.SkillGainFactor = experienceGainedFactor.Value;
			experienceLoss = config("3 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the sailing skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			experienceLoss.SettingChanged += [<358225d2-09f4-482e-85e0-c41edd8462c8>NullableContext(0)] (object _, EventArgs _) =>
			{
				sailing.SkillLoss = experienceLoss.Value;
			};
			sailing.SkillLoss = experienceLoss.Value;
			allowShipNudge = config("3 - Other", "Allow Ship Nudge", Toggle.On, new ConfigDescription("If on, players can press a hotkey, to give their ship a nudge, if it is stuck.", (AcceptableValueBase)null, Array.Empty<object>()));
			nudgeForce = config("3 - Other", "Ship Nudge Force", 10f, new ConfigDescription("Impulse force for ship nudge.", (AcceptableValueBase)null, Array.Empty<object>()));
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			new Harmony("org.bepinex.plugins.sailing").PatchAll(executingAssembly);
			mod = this;
		}

		private static void FetchShipPieces(IEnumerable<GameObject> prefabs)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Expected O, but got Unknown
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Expected O, but got Unknown
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_034a: Expected O, but got Unknown
			//IL_0406: Unknown result type (might be due to invalid IL or missing references)
			//IL_0411: Expected O, but got Unknown
			Localization val = new Localization();
			val.SetupLanguage("English");
			Regex regex = new Regex("['[\"\\]]");
			List<string> shipOrder = new List<string> { "$ship_longship", "$ship_karve", "$ship_raft" };
			foreach (Ship item in from p in prefabs
				select p.GetComponent<Ship>() into s
				where (Object)(object)((s != null) ? ((Component)s).GetComponent<Piece>() : null) != (Object)null
				orderby shipOrder.IndexOf(((Component)s).GetComponent<Piece>().m_name) descending
				select s)
			{
				int num = -shipSpeedIncrease.Count * 4;
				string name = ((Component)item).GetComponent<Piece>().m_name;
				if (!shipSpeedIncrease.ContainsKey(name))
				{
					shipSpeedIncrease[name] = mod.config("2 - Ship Speed", regex.Replace(val.Localize(name), "") + " Speed Factor", 1.5f, new ConfigDescription("Speed factor for " + val.Localize(name) + " at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 3f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Order = (num -= 1),
							DispName = Localization.instance.Localize(name) + " Speed Factor",
							Description = "Speed factor for " + Localization.instance.Localize(name) + " at skill level 100."
						}
					}));
					shipPaddleRequirement[name] = mod.config("2 - Ship Speed", regex.Replace(val.Localize(name), "") + " Paddle Requirement", 0, new ConfigDescription("Required sailing skill level to be able to paddle a " + val.Localize(name) + ".", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Order = (num -= 1),
							ShowRangeAsPercent = false,
							DispName = Localization.instance.Localize(name) + " Paddle Requirement",
							Description = "Required sailing skill level to be able to paddle a " + Localization.instance.Localize(name) + "."
						}
					}));
					shipHalfRequirement[name] = mod.config("2 - Ship Speed", regex.Replace(val.Localize(name), "") + " Half Requirement", 0, new ConfigDescription("Required sailing skill level to be able to sail a " + val.Localize(name) + " with reduced sail.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Order = (num -= 1),
							ShowRangeAsPercent = false,
							DispName = Localization.instance.Localize(name) + " Half Requirement",
							Description = "Required sailing skill level to be able to sail a " + Localization.instance.Localize(name) + " with reduced sail."
						}
					}));
					shipFullRequirement[name] = mod.config("2 - Ship Speed", regex.Replace(val.Localize(name), "") + " Full Requirement", 0, new ConfigDescription("Required sailing skill level to be able to sail a " + val.Localize(name) + " with full sail.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Order = (num -= 1),
							ShowRangeAsPercent = false,
							DispName = Localization.instance.Localize(name) + " Full Requirement",
							Description = "Required sailing skill level to be able to sail a " + Localization.instance.Localize(name) + " with full sail."
						}
					}));
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<5710190d-e3c8-4d73-a609-74605c8bca61>Embedded]
	internal sealed class <5710190d-e3c8-4d73-a609-74605c8bca61>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[<5710190d-e3c8-4d73-a609-74605c8bca61>Embedded]
	[CompilerGenerated]
	internal sealed class <166311ff-1ad9-4588-8420-be72982ae87c>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <166311ff-1ad9-4588-8420-be72982ae87c>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <166311ff-1ad9-4588-8420-be72982ae87c>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[<5710190d-e3c8-4d73-a609-74605c8bca61>Embedded]
	[CompilerGenerated]
	internal sealed class <524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace SkillManager
{
	[PublicAPI]
	[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(0)]
	[<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(1)]
	internal class Skill
	{
		[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(0)]
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				string key = localizations.FirstOrDefault([<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance);
				}
			}

			public static Localization ForLanguage([<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)] string language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(0)]
		[PublicAPI]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", key);
			}

			public LocalizeKey Portuguese_Brazilian(string key)
			{
				return addForLang("Portuguese_Brazilian", key);
			}

			public LocalizeKey Chinese(string key)
			{
				return addForLang("Chinese", key);
			}

			public LocalizeKey Japanese(string key)
			{
				return addForLang("Japanese", key);
			}

			public LocalizeKey Korean(string key)
			{
				return addForLang("Korean", key);
			}

			public LocalizeKey Hindi(string key)
			{
				return addForLang("Hindi", key);
			}

			public LocalizeKey Thai(string key)
			{
				return addForLang("Thai", key);
			}

			public LocalizeKey Abenaki(string key)
			{
				return addForLang("Abenaki", key);
			}

			public LocalizeKey Croatian(string key)
			{
				return addForLang("Croatian", key);
			}

			public LocalizeKey Georgian(string key)
			{
				return addForLang("Georgian", key);
			}

			public LocalizeKey Greek(string key)
			{
				return addForLang("Greek", key);
			}

			public LocalizeKey Serbian(string key)
			{
				return addForLang("Serbian", key);
			}

			public LocalizeKey Ukrainian(string key)
			{
				return addForLang("Ukrainian", key);
			}

			private LocalizeKey addForLang(string lang, string value)
			{
				Localizations[lang] = value;
				if (Localization.instance.GetSelectedLanguage() == lang)
				{
					Localization.instance.AddWord(Key, value);
				}
				else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
				{
					Localization.instance.AddWord(Key, value);
				}
				return this;
			}

			[HarmonyPriority(300)]
			internal static void AddLocalizedKeys(Localization __instance, string language)
			{
				foreach (LocalizeKey key in keys)
				{
					string value2;
					if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value))
					{
						__instance.AddWord(key.Key, value);
					}
					else if (key.Localizations.TryGetValue("alias", out value2))
					{
						Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
					}
				}
			}
		}

		[<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
			public string Category;
		}

		[<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(0)]
		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		private static class Patch_Skills_IsSkillValid
		{
			private static void Postfix(SkillType type, ref bool __result)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (!__result && skills.ContainsKey(type))
				{
					__result = true;
				}
			}
		}

		private static readonly Dictionary<SkillType, Skill> skills;

		internal static readonly Dictionary<string, Skill> skillByName;

		private readonly string skillName;

		private readonly string internalSkillName;

		private readonly SkillDef skillDef;

		public readonly LocalizeKey Name;

		public readonly LocalizeKey Description;

		private float skillEffectFactor = 1f;

		private int skillLoss = 5;

		public bool Configurable;

		private static bool InitializedTerminal;

		[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		private static Localization _english;

		[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static bool hasConfigSync;

		[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		private static object _configSync;

		public float SkillGainFactor
		{
			get
			{
				return skillDef.m_increseStep;
			}
			set
			{
				skillDef.m_increseStep = value;
				this.SkillGainFactorChanged?.Invoke(value);
			}
		}

		public float SkillEffectFactor
		{
			get
			{
				return skillEffectFactor;
			}
			set
			{
				skillEffectFactor = value;
				this.SkillEffectFactorChanged?.Invoke(value);
			}
		}

		public int SkillLoss
		{
			get
			{
				return skillLoss;
			}
			set
			{
				skillLoss = value;
				this.SkillLossChanged?.Invoke(value);
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				object obj = _plugin;
				if (obj == null)
				{
					BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First([<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
					_plugin = val;
					obj = (object)val;
				}
				return (BaseUnityPlugin)obj;
			}
		}

		[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		private static object configSync
		{
			[<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(2)]
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		[method: <524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(2)]
		[field: <166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		public event Action<float> SkillGainFactorChanged;

		[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		[method: <524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(2)]
		[field: <166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		public event Action<float> SkillEffectFactorChanged;

		[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		[method: <524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(2)]
		[field: <166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)]
		public event Action<float> SkillLossChanged;

		public Skill(string englishName, string icon)
			: this(englishName, loadSprite(icon, 64, 64))
		{
		}

		public Skill(string englishName, Sprite icon)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			SkillType val = fromName(englishName);
			string text = new Regex("[^a-zA-Z]").Replace(englishName, "_");
			skills[val] = this;
			skillByName[englishName] = this;
			skillDef = new SkillDef
			{
				m_description = "$skilldesc_" + text,
				m_icon = icon,
				m_increseStep = 1f,
				m_skill = val
			};
			internalSkillName = text;
			skillName = englishName;
			Name = new LocalizeKey("skill_" + ((object)(SkillType)(ref val)).ToString()).English(englishName);
			Description = new LocalizeKey("skilldesc_" + text);
		}

		public static SkillType fromName(string englishName)
		{
			return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName));
		}

		static Skill()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			skills = new Dictionary<SkillType, Skill>();
			skillByName = new Dictionary<string, Skill>();
			InitializedTerminal = false;
			hasConfigSync = true;
			Harmony val = new Harmony("org.bepinex.helpers.skillmanager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null);
		}

		private static void Patch_FejdStartup()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			foreach (Skill skill in skills.Values)
			{
				if (skill.Configurable)
				{
					string key = skill.Name.Key;
					string group = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim();
					string category = Localization.instance.Localize(key).Trim();
					ConfigEntry<float> skillGain = config(group, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillGainFactor = skillGain.Value;
					skillGain.SettingChanged += [<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillGainFactor = skillGain.Value;
					};
					ConfigEntry<float> skillEffect = config(group, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillEffectFactor = skillEffect.Value;
					skillEffect.SettingChanged += [<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillEffectFactor = skillEffect.Value;
					};
					ConfigEntry<int> skillLoss = config(group, "Skill loss", skill.skillLoss, new ConfigDescription("How much experience to lose on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.skillLoss = skillLoss.Value;
					skillLoss.SettingChanged += [<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.skillLoss = skillLoss.Value;
					};
				}
			}
		}

		private static void Patch_Skills_GetSkillDef([<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)] ref SkillDef __result, List<SkillDef> ___m_skills, SkillType type)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (__result == null)
			{
				SkillDef val = GetSkillDef(type);
				if (val != null)
				{
					___m_skills.Add(val);
					__result = val;
				}
			}
		}

		private static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				SkillType current = key;
				Skill skill = skills[current];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					Skill skill2 = __instance.GetSkill(current);
					skill2.m_level += value;
					skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f);
					((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(SkillType)(ref current)).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon);
					Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level);
					return false;
				}
			}
			return true;
		}

		private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				Skill skill = skills[key];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					__instance.ResetSkill(key);
					Console.instance.Print("Skill " + skill.internalSkillName + " reset");
					return false;
				}
			}
			return true;
		}

		private static void Patch_Skills_OnDeath_Prefix(Skills __instance, [<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(new byte[] { 2, 1 })] ref Dictionary<SkillType, Skill> __state)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				__state = new Dictionary<SkillType, Skill>();
			}
			foreach (KeyValuePair<SkillType, Skill> skill in skills)
			{
				if (__instance.m_skillData.TryGetValue(skill.Key, out var value))
				{
					__state[skill.Key] = value;
					if (skill.Value.skillLoss > 0)
					{
						Skill obj = value;
						obj.m_level -= value.m_level * (float)skill.Value.SkillLoss / 100f;
						value.m_accumulator = 0f;
					}
					__instance.m_skillData.Remove(skill.Key);
				}
			}
		}

		private static void Patch_Skills_OnDeath_Finalizer(Skills __instance, [<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(new byte[] { 2, 1 })] ref Dictionary<SkillType, Skill> __state)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (__state == null)
			{
				return;
			}
			foreach (KeyValuePair<SkillType, Skill> item in __state)
			{
				__instance.m_skillData[item.Key] = item.Value;
			}
			__state = null;
		}

		private static void Patch_Terminal_InitTerminal_Prefix()
		{
			InitializedTerminal = Terminal.m_terminalInitialized;
		}

		private static void Patch_Terminal_InitTerminal()
		{
			if (!InitializedTerminal)
			{
				AddSkill(Terminal.commands["raiseskill"]);
				AddSkill(Terminal.commands["resetskill"]);
			}
			static void AddSkill(ConsoleCommand command)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Expected O, but got Unknown
				ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher;
				command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)([<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(0)] () =>
				{
					List<string> list = fetcher.Invoke();
					list.AddRange(skills.Values.Select([<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(0)] (Skill skill) => skill.internalSkillName));
					return list;
				});
			}
		}

		[<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(2)]
		private static SkillDef GetSkillDef(SkillType skillType)
		{
			//IL_0005: 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)
			if (!skills.ContainsKey(skillType))
			{
				return null;
			}
			return skills[skillType].skillDef;
		}

		private static byte[] ReadEmbeddedFileBytes(string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static Texture2D loadTexture(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_001f: Expected O, but got Unknown
			Texture2D val = new Texture2D(0, 0);
			ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name));
			return val;
		}

		private static Sprite loadSprite(string name, int width, int height)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero);
		}

		private static ConfigEntry<T> config<[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)] T>(string group, string name, T value, ConfigDescription description)
		{
			ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description);
			configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T))
				.Invoke(configSync, new object[1] { val });
			return val;
		}

		private static ConfigEntry<T> config<[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(2)] T>(string group, string name, T value, string description)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[PublicAPI]
	[<166311ff-1ad9-4588-8420-be72982ae87c>Nullable(0)]
	[<524ae538-514f-4b8e-9fcc-15590855d3cf>NullableContext(1)]
	internal static class SkillExtensions
	{
		public static float GetSkillFactor(this Character character, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return character.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static float GetSkillFactor(this Skills skills, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return skills.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static void RaiseSkill(this Character character, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			character.RaiseSkill(Skill.fromName(name), value);
		}

		public static void RaiseSkill(this Skills skill, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			skill.RaiseSkill(Skill.fromName(name), value);
		}

		public static void LowerSkill(this Character character, string name, float factor = 1f)
		{
			character.GetSkills().LowerSkill(name, factor);
		}

		public static void LowerSkill(this Skills skills, string name, float factor)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (factor > 0f && skills.m_skillData.TryGetValue(Skill.fromName(name), out var value))
			{
				Skill obj = value;
				obj.m_level -= value.m_level * factor;
				value.m_accumulator = 0f;
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	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;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;


		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			ZPackage package2 = package;
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package2.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package2 = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package2)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[PublicAPI]
	[HarmonyPatch]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			ZRpc rpc2 = rpc;
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		[HarmonyPrefix]
		private static void RemoveDisconnected(Z

BepInEx/plugins/Smoothbrain-Tenacity/Tenacity.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using SkillManager;
using UnityEngine;
using UnityEngine.UI;

[assembly: Guid("B1CC958B-840C-4AAF-9AE7-7EF8DA315688")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyProduct("Tenacity")]
[assembly: AssemblyCompany("")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyDescription("https://valheim.thunderstore.io/package/Smoothbrain/Tenacity")]
[assembly: AssemblyTitle("Tenacity")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<4dc5b996-73d2-4595-bce5-efd46b72e432>Embedded]
	internal sealed class <4dc5b996-73d2-4595-bce5-efd46b72e432>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<4dc5b996-73d2-4595-bce5-efd46b72e432>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <0a2e865e-28aa-4a4f-a5dc-dd02c964bb72>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <0a2e865e-28aa-4a4f-a5dc-dd02c964bb72>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <0a2e865e-28aa-4a4f-a5dc-dd02c964bb72>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<4dc5b996-73d2-4595-bce5-efd46b72e432>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <7c4baed4-2cf9-4da4-a9f2-6097dcd5c7dd>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <7c4baed4-2cf9-4da4-a9f2-6097dcd5c7dd>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace Tenacity
{
	[<7c4baed4-2cf9-4da4-a9f2-6097dcd5c7dd>NullableContext(1)]
	[<0a2e865e-28aa-4a4f-a5dc-dd02c964bb72>Nullable(0)]
	[BepInPlugin("org.bepinex.plugins.tenacity", "Tenacity", "1.0.2")]
	public class Tenacity : BaseUnityPlugin
	{
		[<7c4baed4-2cf9-4da4-a9f2-6097dcd5c7dd>NullableContext(0)]
		[HarmonyPatch(typeof(Character), "RPC_Damage")]
		private class ReduceDamageTaken
		{
			[<7c4baed4-2cf9-4da4-a9f2-6097dcd5c7dd>NullableContext(1)]
			[UsedImplicitly]
			private static void Prefix(Character __instance, HitData hit)
			{
				Player val = (Player)(object)((__instance is Player) ? __instance : null);
				if (val != null)
				{
					((Character)(object)val).RaiseSkill("Tenacity", (float)Math.Sqrt(hit.GetTotalDamage()));
					hit.ApplyModifier(1f - ((Character)(object)val).GetSkillFactor("Tenacity") * 0.2f);
				}
			}
		}

		private const string ModName = "Tenacity";

		private const string ModVersion = "1.0.2";

		private const string ModGUID = "org.bepinex.plugins.tenacity";

		public void Awake()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			Skill skill = new Skill("Tenacity", "tenacity-icon.png");
			skill.Description.English("Reduces damage taken slightly.");
			skill.Name.German("Hartnäckigkeit");
			skill.Description.German("Reduziert den erlittenen Schaden.");
			skill.Configurable = true;
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			Harmony val = new Harmony("org.bepinex.plugins.tenacity");
			val.PatchAll(executingAssembly);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<bfe59b6f-c8eb-4bae-8ac7-f967ab4801b3>Embedded]
	internal sealed class <bfe59b6f-c8eb-4bae-8ac7-f967ab4801b3>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<bfe59b6f-c8eb-4bae-8ac7-f967ab4801b3>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <69d703b8-61c8-493a-a73c-93cabd5986a0>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <69d703b8-61c8-493a-a73c-93cabd5986a0>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <69d703b8-61c8-493a-a73c-93cabd5986a0>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	[<bfe59b6f-c8eb-4bae-8ac7-f967ab4801b3>Embedded]
	internal sealed class <eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace SkillManager
{
	[<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(1)]
	[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(0)]
	[PublicAPI]
	internal class Skill
	{
		[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(0)]
		public static class LocalizationCache
		{
			private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>();

			internal static void LocalizationPostfix(Localization __instance, string language)
			{
				string key = localizations.FirstOrDefault([<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key;
				if (key != null)
				{
					localizations.Remove(key);
				}
				if (!localizations.ContainsKey(language))
				{
					localizations.Add(language, __instance);
				}
			}

			public static Localization ForLanguage([<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)] string language = null)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Expected O, but got Unknown
				if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value))
				{
					return value;
				}
				value = new Localization();
				if (language != null)
				{
					value.SetupLanguage(language);
				}
				return value;
			}
		}

		[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(0)]
		[PublicAPI]
		public class LocalizeKey
		{
			private static readonly List<LocalizeKey> keys = new List<LocalizeKey>();

			public readonly string Key;

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

			public LocalizeKey(string key)
			{
				Key = key.Replace("$", "");
			}

			public void Alias(string alias)
			{
				Localizations.Clear();
				if (!alias.Contains("$"))
				{
					alias = "$" + alias;
				}
				Localizations["alias"] = alias;
				Localization.instance.AddWord(Key, Localization.instance.Localize(alias));
			}

			public LocalizeKey English(string key)
			{
				return addForLang("English", key);
			}

			public LocalizeKey Swedish(string key)
			{
				return addForLang("Swedish", key);
			}

			public LocalizeKey French(string key)
			{
				return addForLang("French", key);
			}

			public LocalizeKey Italian(string key)
			{
				return addForLang("Italian", key);
			}

			public LocalizeKey German(string key)
			{
				return addForLang("German", key);
			}

			public LocalizeKey Spanish(string key)
			{
				return addForLang("Spanish", key);
			}

			public LocalizeKey Russian(string key)
			{
				return addForLang("Russian", key);
			}

			public LocalizeKey Romanian(string key)
			{
				return addForLang("Romanian", key);
			}

			public LocalizeKey Bulgarian(string key)
			{
				return addForLang("Bulgarian", key);
			}

			public LocalizeKey Macedonian(string key)
			{
				return addForLang("Macedonian", key);
			}

			public LocalizeKey Finnish(string key)
			{
				return addForLang("Finnish", key);
			}

			public LocalizeKey Danish(string key)
			{
				return addForLang("Danish", key);
			}

			public LocalizeKey Norwegian(string key)
			{
				return addForLang("Norwegian", key);
			}

			public LocalizeKey Icelandic(string key)
			{
				return addForLang("Icelandic", key);
			}

			public LocalizeKey Turkish(string key)
			{
				return addForLang("Turkish", key);
			}

			public LocalizeKey Lithuanian(string key)
			{
				return addForLang("Lithuanian", key);
			}

			public LocalizeKey Czech(string key)
			{
				return addForLang("Czech", key);
			}

			public LocalizeKey Hungarian(string key)
			{
				return addForLang("Hungarian", key);
			}

			public LocalizeKey Slovak(string key)
			{
				return addForLang("Slovak", key);
			}

			public LocalizeKey Polish(string key)
			{
				return addForLang("Polish", key);
			}

			public LocalizeKey Dutch(string key)
			{
				return addForLang("Dutch", key);
			}

			public LocalizeKey Portuguese_European(string key)
			{
				return addForLang("Portuguese_European", key);
			}

			public LocalizeKey Portuguese_Brazilian(string key)
			{
				return addForLang("Portuguese_Brazilian", key);
			}

			public LocalizeKey Chinese(string key)
			{
				return addForLang("Chinese", key);
			}

			public LocalizeKey Japanese(string key)
			{
				return addForLang("Japanese", key);
			}

			public LocalizeKey Korean(string key)
			{
				return addForLang("Korean", key);
			}

			public LocalizeKey Hindi(string key)
			{
				return addForLang("Hindi", key);
			}

			public LocalizeKey Thai(string key)
			{
				return addForLang("Thai", key);
			}

			public LocalizeKey Abenaki(string key)
			{
				return addForLang("Abenaki", key);
			}

			public LocalizeKey Croatian(string key)
			{
				return addForLang("Croatian", key);
			}

			public LocalizeKey Georgian(string key)
			{
				return addForLang("Georgian", key);
			}

			public LocalizeKey Greek(string key)
			{
				return addForLang("Greek", key);
			}

			public LocalizeKey Serbian(string key)
			{
				return addForLang("Serbian", key);
			}

			public LocalizeKey Ukrainian(string key)
			{
				return addForLang("Ukrainian", key);
			}

			private LocalizeKey addForLang(string lang, string value)
			{
				Localizations[lang] = value;
				if (Localization.instance.GetSelectedLanguage() == lang)
				{
					Localization.instance.AddWord(Key, value);
				}
				else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key))
				{
					Localization.instance.AddWord(Key, value);
				}
				return this;
			}

			[HarmonyPriority(300)]
			internal static void AddLocalizedKeys(Localization __instance, string language)
			{
				foreach (LocalizeKey key in keys)
				{
					string value2;
					if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value))
					{
						__instance.AddWord(key.Key, value);
					}
					else if (key.Localizations.TryGetValue("alias", out value2))
					{
						Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2));
					}
				}
			}
		}

		[<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)]
			[UsedImplicitly]
			public string Category;
		}

		[<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(0)]
		[HarmonyPatch(typeof(Skills), "IsSkillValid")]
		private static class Patch_Skills_IsSkillValid
		{
			private static void Postfix(SkillType type, ref bool __result)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				if (!__result && skills.ContainsKey(type))
				{
					__result = true;
				}
			}
		}

		private static readonly Dictionary<SkillType, Skill> skills;

		internal static readonly Dictionary<string, Skill> skillByName;

		private readonly string skillName;

		private readonly string internalSkillName;

		private readonly SkillDef skillDef;

		public readonly LocalizeKey Name;

		public readonly LocalizeKey Description;

		private float skillEffectFactor = 1f;

		public bool Configurable;

		private static bool InitializedTerminal;

		[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)]
		private static Localization _english;

		[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)]
		private static BaseUnityPlugin _plugin;

		private static bool hasConfigSync;

		[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)]
		private static object _configSync;

		public float SkillGainFactor
		{
			get
			{
				return skillDef.m_increseStep;
			}
			set
			{
				skillDef.m_increseStep = value;
				this.SkillGainFactorChanged?.Invoke(value);
			}
		}

		public float SkillEffectFactor
		{
			get
			{
				return skillEffectFactor;
			}
			set
			{
				skillEffectFactor = value;
				this.SkillEffectFactorChanged?.Invoke(value);
			}
		}

		private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English"));

		private static BaseUnityPlugin plugin
		{
			get
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Expected O, but got Unknown
				object obj = _plugin;
				if (obj == null)
				{
					BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First([<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
					_plugin = val;
					obj = (object)val;
				}
				return (BaseUnityPlugin)obj;
			}
		}

		[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)]
		private static object configSync
		{
			[<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(2)]
			get
			{
				if (_configSync == null && hasConfigSync)
				{
					Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync");
					if ((object)type != null)
					{
						_configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager");
						type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString());
						type.GetProperty("IsLocked").SetValue(_configSync, true);
					}
					else
					{
						hasConfigSync = false;
					}
				}
				return _configSync;
			}
		}

		[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)]
		[method: <eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(2)]
		[field: <69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)]
		public event Action<float> SkillGainFactorChanged;

		[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)]
		[method: <eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(2)]
		[field: <69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)]
		public event Action<float> SkillEffectFactorChanged;

		public Skill(string englishName, string icon)
			: this(englishName, loadSprite(icon, 64, 64))
		{
		}

		public Skill(string englishName, Sprite icon)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			SkillType val = fromName(englishName);
			string text = new Regex("[^a-zA-Z]").Replace(englishName, "_");
			skills[val] = this;
			skillByName[englishName] = this;
			skillDef = new SkillDef
			{
				m_description = "$skilldesc_" + text,
				m_icon = icon,
				m_increseStep = 1f,
				m_skill = val
			};
			internalSkillName = text;
			skillName = englishName;
			Name = new LocalizeKey("skill_" + ((object)(SkillType)(ref val)).ToString()).English(englishName);
			Description = new LocalizeKey("skilldesc_" + text);
		}

		public static SkillType fromName(string englishName)
		{
			return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName));
		}

		static Skill()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Expected O, but got Unknown
			skills = new Dictionary<SkillType, Skill>();
			skillByName = new Dictionary<string, Skill>();
			InitializedTerminal = false;
			hasConfigSync = true;
			Harmony val = new Harmony("org.bepinex.helpers.skillmanager");
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void Patch_FejdStartup()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			foreach (Skill skill in skills.Values)
			{
				if (skill.Configurable)
				{
					string key = skill.Name.Key;
					string group = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim();
					string category = Localization.instance.Localize(key).Trim();
					ConfigEntry<float> skillGain = config(group, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillGainFactor = skillGain.Value;
					skillGain.SettingChanged += [<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillGainFactor = skillGain.Value;
					};
					ConfigEntry<float> skillEffect = config(group, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1]
					{
						new ConfigurationManagerAttributes
						{
							Category = category
						}
					}));
					skill.SkillEffectFactor = skillEffect.Value;
					skillEffect.SettingChanged += [<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(0)] (object _, EventArgs _) =>
					{
						skill.SkillEffectFactor = skillEffect.Value;
					};
				}
			}
		}

		private static void Patch_Skills_GetSkillDef([<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)] ref SkillDef __result, List<SkillDef> ___m_skills, SkillType type)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (__result == null)
			{
				SkillDef val = GetSkillDef(type);
				if (val != null)
				{
					___m_skills.Add(val);
					__result = val;
				}
			}
		}

		private static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				SkillType current = key;
				Skill skill = skills[current];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					Skill skill2 = __instance.GetSkill(current);
					skill2.m_level += value;
					skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f);
					((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(SkillType)(ref current)).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon);
					Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level);
					return false;
				}
			}
			return true;
		}

		private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			foreach (SkillType key in skills.Keys)
			{
				Skill skill = skills[key];
				if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase))
				{
					__instance.ResetSkill(key);
					Console.instance.Print("Skill " + skill.internalSkillName + " reset");
					return false;
				}
			}
			return true;
		}

		private static void Patch_Terminal_InitTerminal_Prefix()
		{
			InitializedTerminal = Terminal.m_terminalInitialized;
		}

		private static void Patch_Terminal_InitTerminal()
		{
			if (!InitializedTerminal)
			{
				AddSkill(Terminal.commands["raiseskill"]);
				AddSkill(Terminal.commands["resetskill"]);
			}
			static void AddSkill(ConsoleCommand command)
			{
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Expected O, but got Unknown
				ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher;
				command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)([<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(0)] () =>
				{
					List<string> list = fetcher.Invoke();
					list.AddRange(skills.Values.Select([<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(0)] (Skill skill) => skill.internalSkillName));
					return list;
				});
			}
		}

		[<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(2)]
		private static SkillDef GetSkillDef(SkillType skillType)
		{
			//IL_0005: 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)
			if (!skills.ContainsKey(skillType))
			{
				return null;
			}
			return skills[skillType].skillDef;
		}

		private static byte[] ReadEmbeddedFileBytes(string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static Texture2D loadTexture(string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_001f: Expected O, but got Unknown
			Texture2D val = new Texture2D(0, 0);
			ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name));
			return val;
		}

		private static Sprite loadSprite(string name, int width, int height)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero);
		}

		private static ConfigEntry<T> config<[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)] T>(string group, string name, T value, ConfigDescription description)
		{
			ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description);
			configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T))
				.Invoke(configSync, new object[1] { val });
			return val;
		}

		private static ConfigEntry<T> config<[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(2)] T>(string group, string name, T value, string description)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[<eb9a33bc-e95e-4a74-917e-aa2dd1533290>NullableContext(1)]
	[<69d703b8-61c8-493a-a73c-93cabd5986a0>Nullable(0)]
	[PublicAPI]
	internal static class SkillExtensions
	{
		public static float GetSkillFactor(this Character character, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return character.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static float GetSkillFactor(this Skills skills, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return skills.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor;
		}

		public static void RaiseSkill(this Character character, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			character.RaiseSkill(Skill.fromName(name), value);
		}

		public static void RaiseSkill(this Skills skill, string name, float value = 1f)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			skill.RaiseSkill(Skill.fromName(name), value);
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					configSync2.IsSourceOfTruth = __instance.IsDedicated() || __instance.IsServer();
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_ConfigSync);
					if (isServer)
					{
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_InitialConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_InitialConfigSync(ZRpc rpc, ZPackage package)
		{
			RPC_ConfigSync(0L, package);
		}

		private void RPC_ConfigSync(long sender, ZPackage package)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Expected O, but got Unknown
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					bool? obj;
					if ((int)val == 0)
					{
						obj = null;
					}
					else
					{
						ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
						object obj2;
						if (currentRpc == null)
						{
							obj2 = null;
						}
						else
						{
							ISocket socket = currentRpc.GetSocket();
							obj2 = ((socket != null) ? socket.GetHostName() : null);
						}
						obj = val.Contains((string)obj2);
					}
					if (obj == false)
					{
						return;
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return;
					}
					configValueCache.Remove(text);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				if (!isServer)
				{
					if (IsSourceOfTruth)
					{
						lockedConfigChanged += serverLockedSettingChanged;
					}
					IsSourceOfTruth = false;
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				if (!isServer)
				{
					Debug.Log((object)$"Received {parsedConfigs.configValues.Count} configs and {parsedConfigs.customValues.Count} custom values from the server for mod {DisplayName ?? Name}");
					serverLockedSettingChanged();
				}
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			IsSourceOfTruth = true;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			ZPackage package2 = package;
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package2.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package2 = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package2)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[HarmonyPatch]
	[PublicAPI]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			ZRpc rpc2 = rpc;
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}

BepInEx/plugins/TastyChickenLegs-AutomaticFuel/AutomaticFuel.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using UnityEngine;
using UnityEngine.UI;

[assembly: AssemblyFileVersion("1.3.8")]
[assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyProduct("AutomaticFuel")]
[assembly: AssemblyCompany("TastyChickenLegs")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyTitle("AutomaticFuel")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.3.8.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<f0da9226-4d6d-47ec-aab7-40fd37e1628d>Embedded]
	internal sealed class <f0da9226-4d6d-47ec-aab7-40fd37e1628d>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[<f0da9226-4d6d-47ec-aab7-40fd37e1628d>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class <2fdb0271-2074-4d19-b012-27fac8ff016f>NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public <2fdb0271-2074-4d19-b012-27fac8ff016f>NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public <2fdb0271-2074-4d19-b012-27fac8ff016f>NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[<f0da9226-4d6d-47ec-aab7-40fd37e1628d>Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class <3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public <3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
[<2fdb0271-2074-4d19-b012-27fac8ff016f>Nullable(0)]
internal sealed class ConfigurationManagerAttributes
{
	public bool? ShowRangeAsPercent;

	public Action<ConfigEntryBase> CustomDrawer;

	public bool? Browsable;

	public string Category;

	public object DefaultValue;

	public bool? HideDefaultButton;

	public bool? HideSettingName;

	public string Description;

	public string DispName;

	public int? Order;

	public bool? ReadOnly;

	public bool? IsAdvanced;

	public Func<object, string> ObjToStr;

	public Func<string, object> StrToObj;
}
namespace AutomaticFuel
{
	[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
	[<2fdb0271-2074-4d19-b012-27fac8ff016f>Nullable(0)]
	[BepInPlugin("TastyChickenLegs.AutomaticFuel", "AutomaticFuel", "1.3.8")]
	public class AutomaticFuelPlugin : BaseUnityPlugin
	{
		[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(0)]
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(0)]
		private class ConfigurationManagerAttributes
		{
			public bool? Browsable = false;
		}

		[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(0)]
		[HarmonyPatch(typeof(Container), "Awake")]
		private static class ContainerAwakePatch
		{
			[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
			private static void Postfix(Container __instance, ZNetView ___m_nview)
			{
				TastyUtils.AddContainer(__instance, ___m_nview);
			}
		}

		[HarmonyPatch(typeof(Container), "OnDestroyed")]
		[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(0)]
		private static class ContainerOnDestroyedPatch
		{
			[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
			private static void Prefix(Container __instance)
			{
				ContainerList.Remove(__instance);
			}
		}

		internal const string ModName = "AutomaticFuel";

		internal const string ModVersion = "1.3.8";

		internal const string Author = "TastyChickenLegs";

		private const string ModGUID = "TastyChickenLegs.AutomaticFuel";

		private static string ConfigFileName = "TastyChickenLegs.AutomaticFuel.cfg";

		private static string ConfigFileFullPath;

		private static readonly bool isDebug;

		public static ConfigEntry<float> dropRange;

		public static ConfigEntry<float> containerRange;

		public static ConfigEntry<float> fireplaceRange;

		public static ConfigEntry<float> smelterOreRange;

		public static ConfigEntry<float> smelterFuelRange;

		public static ConfigEntry<string> fuelDisallowTypes;

		public static ConfigEntry<string> oreDisallowTypes;

		public static ConfigEntry<KeyCode> toggleKeythree;

		public static string toggleString;

		public static ConfigEntry<bool> refuelStandingTorches;

		public static ConfigEntry<bool> refuelWallTorches;

		public static ConfigEntry<bool> refuelFirePits;

		public static ConfigEntry<bool> blastFurnaceFix;

		public static ConfigEntry<bool> restrictKilnOutput;

		public static ConfigEntry<int> restrictKilnOutputAmount;

		public static ConfigEntry<bool> leaveLastItem;

		public static ConfigEntry<bool> isOn;

		public static ConfigEntry<bool> modEnabled;

		public static ConfigEntry<bool> distributedFilling;

		public static ConfigEntry<bool> configStackSmelters;

		public static ConfigEntry<bool> configBlastFurnaceTakesAll;

		internal static readonly List<Container> ContainerList;

		public static ConfigEntry<float> mRange;

		public static ConfigEntry<bool> refuelBraziers;

		public static ConfigEntry<bool> turnOffKiln;

		public static ConfigEntry<bool> refuelHearth;

		public static ConfigEntry<bool> refuelHotTub;

		public static ConfigEntry<bool> turnOffWindmills;

		public static ConfigEntry<bool> turnOffSpinningWheel;

		internal static string ConnectionError;

		public static float lastFuel;

		public static int fuelCount;

		private readonly Harmony _harmony = new Harmony("TastyChickenLegs.AutomaticFuel");

		public static readonly ManualLogSource AutomaticFuelLogger;

		private static readonly ConfigSync ConfigSync;

		private static ConfigEntry<Toggle> _serverConfigLocked;

		public void Awake()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Expected O, but got Unknown
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Expected O, but got Unknown
			_serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only.");
			ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked);
			dropRange = config("General", "DropRange", 15f, new ConfigDescription("The maximum range to pull dropped fuel", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			fireplaceRange = config("Fireplace", "FireplaceRange", 5f, new ConfigDescription("The maximum range to pull fuel from containers for fireplaces", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			smelterOreRange = config("Smelters", "SmelterOreRange", 15f, new ConfigDescription("The maximum range to pull ore from containers for smelters", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			smelterFuelRange = config("Smelters", "SmelterFuelRange", 15f, new ConfigDescription("The maximum range to pull fuel from containers for smelters", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f), Array.Empty<object>()));
			restrictKilnOutputAmount = config("Smelters", "RestrictKilnOutputAmount", 50, new ConfigDescription("Amount of coal to shut off kiln fueling max 1000", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000), Array.Empty<object>()));
			configStackSmelters = config("Smelters", "AllowStackSmelters", value: false, "Allows smelters, kiln to be stacked.  Takes away the smoke and smoke blocked check");
			fuelDisallowTypes = config("Fireplace", "FuelDisallowTypes", "RoundLog,FineWood", "Types of item to disallow as fuel (i.e. anything that is consumed), comma-separated.");
			oreDisallowTypes = config("Smelters", "OreDisallowTypes", "RoundLog,FineWood", "Types of item to disallow as ore (i.e. anything that is transformed), comma-separated).");
			configBlastFurnaceTakesAll = config("Smelters", "BlastFurnaceTakesAll", value: true, "Allows the Blast Furnace to take all ore");
			toggleKeythree = config<KeyCode>("General", "ToggleKey", (KeyCode)291, "Key to toggle behaviour. Leave blank to disable the toggle key. Use https://docs.unity3d.com/Manual/ConventionalGameInput.html");
			turnOffWindmills = config("Smelters", "Turn Off Windmills", value: false, "Turn off the Windmills");
			turnOffSpinningWheel = config("Smelters", "Turn Off SpinningWheel", value: false, "Turn off the Spinnng Wheel");
			turnOffKiln = config("Smelters", "Turn Off Kiln", value: false, "Turn off the Kiln");
			refuelStandingTorches = config("Fireplace", "RefuelStandingTorches", value: true, "Refuel standing torches");
			refuelBraziers = config("Fireplace", "RefuelBraziers", value: true, "Refuel Braziers");
			refuelHotTub = config("Fireplace", "RefuelHotTub", value: true, "Refuel HotTub");
			refuelWallTorches = config("Fireplace", "RefuelWallTorches", value: true, "Refuel wall torches");
			refuelFirePits = config("Fireplace", "RefuelFirePits", value: true, "Refuel fire pits");
			refuelHearth = config("Fireplace", "RefuelHearth", value: true, "Refuel Hearth");
			restrictKilnOutput = config("Smelters", "RestrictKilnOutput", value: false, "Restrict kiln output");
			isOn = config("", "IsOn", value: true, "Behaviour is currently on or not");
			distributedFilling = config("Smelters", "DistributedFueling", value: true, "If true, refilling will occur one piece of fuel or ore at a time, making filling take longer but be better distributed between objects.");
			leaveLastItem = config("Smelters", "LeaveLastItem", value: false, "Don't use last of item in chest");
			modEnabled = config("", "Enabled", value: true, "Enable this mod");
			if (modEnabled.Value)
			{
				Assembly executingAssembly = Assembly.GetExecutingAssembly();
				_harmony.PatchAll(executingAssembly);
				SetupWatcher();
			}
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		private void SetupWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			fileSystemWatcher.Changed += ReadConfigValues;
			fileSystemWatcher.Created += ReadConfigValues;
			fileSystemWatcher.Renamed += ReadConfigValues;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(ConfigFileFullPath))
			{
				return;
			}
			try
			{
				AutomaticFuelLogger.LogDebug((object)"ReadConfigValues called");
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch
			{
				AutomaticFuelLogger.LogError((object)("There was an issue loading your " + ConfigFileName));
				AutomaticFuelLogger.LogError((object)"Please check your config entries for spelling and format!");
			}
		}

		private ConfigEntry<T> config<[<2fdb0271-2074-4d19-b012-27fac8ff016f>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags);
			ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val);
			ConfigSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting;
			return val2;
		}

		private ConfigEntry<T> config<[<2fdb0271-2074-4d19-b012-27fac8ff016f>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		public static void Dbgl(string str = "", bool pref = true)
		{
			if (isDebug)
			{
				Debug.Log((object)((pref ? (typeof(AutomaticFuelPlugin).Namespace + " ") : "") + str));
			}
		}

		private void Update()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			if (Input.GetKeyDown(toggleKeythree.Value) && !TastyUtils.IgnoreKeyPresses(extra: true))
			{
				isOn.Value = !isOn.Value;
				((BaseUnityPlugin)this).Config.Save();
				((Character)Player.m_localPlayer).Message((MessageType)2, string.Format(toggleString, isOn.Value), 0, (Sprite)null);
			}
		}

		static AutomaticFuelPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			isDebug = false;
			toggleString = "Auto Fuel: {0}";
			ContainerList = new List<Container>();
			ConnectionError = "";
			AutomaticFuelLogger = Logger.CreateLogSource("AutomaticFuel");
			ConfigSync = new ConfigSync("TastyChickenLegs.AutomaticFuel")
			{
				DisplayName = "AutomaticFuel",
				CurrentVersion = "1.3.8",
				MinimumRequiredVersion = "1.3.8"
			};
			_serverConfigLocked = null;
		}
	}
	[<2fdb0271-2074-4d19-b012-27fac8ff016f>Nullable(0)]
	[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
	public class TastyUtils
	{
		public static bool IgnoreKeyPresses(bool extra = false)
		{
			if (!extra)
			{
				if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !Minimap.IsOpen() && !Console.IsVisible() && !TextInput.IsVisible() && !ZNet.instance.InPasswordDialog())
				{
					Chat instance = Chat.instance;
					if (instance == null)
					{
						return false;
					}
					return instance.HasFocus();
				}
				return true;
			}
			if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && !Minimap.IsOpen() && !Console.IsVisible() && !TextInput.IsVisible() && !ZNet.instance.InPasswordDialog())
			{
				Chat instance2 = Chat.instance;
				if ((instance2 == null || !instance2.HasFocus()) && !StoreGui.IsVisible() && !InventoryGui.IsVisible() && !Menu.IsVisible())
				{
					TextViewer instance3 = TextViewer.instance;
					if (instance3 == null)
					{
						return false;
					}
					return instance3.IsVisible();
				}
			}
			return true;
		}

		public static bool CheckKeyDown(string value)
		{
			try
			{
				return Input.GetKeyDown(value.ToLower());
			}
			catch
			{
				return false;
			}
		}

		public static bool CheckKeyHeld(string value, bool req = true)
		{
			try
			{
				return Input.GetKey(value.ToLower());
			}
			catch
			{
				return !req;
			}
		}

		public static string GetPrefabName(string name)
		{
			char[] anyOf = new char[2] { '(', ' ' };
			int num = name.IndexOfAny(anyOf);
			if (num >= 0)
			{
				return name.Substring(0, num);
			}
			return name;
		}

		public static void AddContainer(Container container, ZNetView nview)
		{
			try
			{
				ManualLogSource automaticFuelLogger = AutomaticFuelPlugin.AutomaticFuelLogger;
				object[] obj = new object[4]
				{
					((Object)container).name,
					(Object)(object)nview != (Object)null,
					((nview != null) ? nview.GetZDO() : null) != null,
					null
				};
				long? obj2;
				if (nview == null)
				{
					obj2 = null;
				}
				else
				{
					ZDO zDO = nview.GetZDO();
					obj2 = ((zDO != null) ? new long?(zDO.GetLong(StringExtensionMethods.GetStableHashCode("creator"), 0L)) : null);
				}
				obj[3] = obj2;
				automaticFuelLogger.LogDebug((object)string.Format("Checking {0} {1} {2} {3}", obj));
				if (container.GetInventory() != null && ((nview != null) ? nview.GetZDO() : null) != null && (((Object)container).name.StartsWith("piece_", StringComparison.Ordinal) || ((Object)container).name.StartsWith("Container", StringComparison.Ordinal) || nview.GetZDO().GetLong(StringExtensionMethods.GetStableHashCode("creator"), 0L) != 0L))
				{
					AutomaticFuelPlugin.AutomaticFuelLogger.LogDebug((object)("Adding " + ((Object)container).name));
					AutomaticFuelPlugin.ContainerList.Add(container);
				}
			}
			catch
			{
			}
		}

		public static List<Container> GetNearbyContainers(Vector3 center, float range)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			List<Container> list = new List<Container>();
			foreach (Container item in AutomaticFuelPlugin.ContainerList.Where([<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(0)] (Container container) => (Object)(object)container != (Object)null && (Object)(object)((Component)container).GetComponentInParent<Piece>() != (Object)null && (Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)((container != null) ? ((Component)container).transform : null) != (Object)null && container.GetInventory() != null && (range <= 0f || Vector3.Distance(center, ((Component)container).transform.position) < range) && container.CheckAccess(Player.m_localPlayer.GetPlayerID()) && !container.IsInUse()))
			{
				if (PrivateArea.CheckAccess(((Component)item).transform.position, 0f, false, false))
				{
					if (!PrivateArea.InsideFactionArea(((Component)item).transform.position, (Faction)0))
					{
						item.Load();
						list.Add(item);
					}
					else
					{
						item.Load();
						list.Add(item);
					}
				}
			}
			return list;
		}
	}
}
namespace AutomaticFuel.GameClasses
{
	internal class Fireplace_Patches
	{
		[HarmonyPatch(typeof(Fireplace), "UpdateFireplace")]
		private static class Fireplace_UpdateFireplace_Patch
		{
			[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
			private static void Postfix(Fireplace __instance, ZNetView ___m_nview)
			{
				if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && AutomaticFuelPlugin.isOn.Value && ___m_nview.IsOwner() && (!((Object)__instance).name.Contains("groundtorch") || AutomaticFuelPlugin.refuelStandingTorches.Value) && (!((Object)__instance).name.Contains("walltorch") || AutomaticFuelPlugin.refuelWallTorches.Value) && (!((Object)__instance).name.Contains("fire_pit") || AutomaticFuelPlugin.refuelFirePits.Value) && (!((Object)__instance).name.Contains("brazier") || AutomaticFuelPlugin.refuelBraziers.Value) && (!((Object)__instance).name.Contains("hearth") || AutomaticFuelPlugin.refuelHearth.Value) && (!((Object)__instance).name.Contains("bathtub") || AutomaticFuelPlugin.refuelHotTub.Value))
				{
					if ((double)(Time.time - AutomaticFuelPlugin.lastFuel) < 0.1)
					{
						AutomaticFuelPlugin.fuelCount++;
						RefuelTorch(__instance, ___m_nview, AutomaticFuelPlugin.fuelCount * 33);
					}
					else
					{
						AutomaticFuelPlugin.fuelCount = 0;
						AutomaticFuelPlugin.lastFuel = Time.time;
						RefuelTorch(__instance, ___m_nview, 0);
					}
				}
			}
		}

		[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
		public static async void RefuelTorch(Fireplace fireplace, ZNetView znview, int delay)
		{
			try
			{
				await Task.Delay(delay);
				if (!Object.op_Implicit((Object)(object)fireplace) || !Object.op_Implicit((Object)(object)znview) || !znview.IsValid() || !AutomaticFuelPlugin.modEnabled.Value)
				{
					return;
				}
				int num = (int)(fireplace.m_maxFuel - Mathf.Ceil(znview.GetZDO().GetFloat("fuel", 0f)));
				List<Container> nearbyContainers = TastyUtils.GetNearbyContainers(((Component)fireplace).transform.position, AutomaticFuelPlugin.fireplaceRange.Value);
				Collider[] array = Physics.OverlapSphere(((Component)fireplace).transform.position + Vector3.up, AutomaticFuelPlugin.dropRange.Value, LayerMask.GetMask(new string[1] { "item" }));
				foreach (Collider val in array)
				{
					if (!Object.op_Implicit((Object)(object)((val != null) ? val.attachedRigidbody : null)))
					{
						continue;
					}
					ItemDrop component = ((Component)val.attachedRigidbody).GetComponent<ItemDrop>();
					int num2;
					if (component == null)
					{
						num2 = 1;
					}
					else
					{
						ZNetView component2 = ((Component)component).GetComponent<ZNetView>();
						num2 = ((((component2 != null) ? new bool?(component2.IsValid()) : null) != true) ? 1 : 0);
					}
					if (num2 != 0)
					{
						continue;
					}
					string prefabName = TastyUtils.GetPrefabName(((Object)((Component)component).gameObject).name);
					if (!(component.m_itemData.m_shared.m_name == fireplace.m_fuelItem.m_itemData.m_shared.m_name) || num <= 0 || AutomaticFuelPlugin.fuelDisallowTypes.Value.Split(new char[1] { ',' }).Contains(prefabName))
					{
						continue;
					}
					AutomaticFuelPlugin.Dbgl("auto adding fuel " + prefabName + " from ground");
					int num3 = Mathf.Min(component.m_itemData.m_stack, num);
					num -= num3;
					for (int j = 0; j < num3; j++)
					{
						if (component.m_itemData.m_stack <= 1)
						{
							if (znview.GetZDO() == null)
							{
								Object.Destroy((Object)(object)((Component)component).gameObject);
							}
							else
							{
								ZNetScene.instance.Destroy(((Component)component).gameObject);
							}
							znview.InvokeRPC("AddFuel", new object[0]);
							if (!AutomaticFuelPlugin.distributedFilling.Value)
							{
								break;
							}
							return;
						}
						ItemData itemData = component.m_itemData;
						itemData.m_stack--;
						znview.InvokeRPC("AddFuel", new object[0]);
						Traverse.Create((object)component).Method("Save", Array.Empty<object>()).GetValue();
						if (AutomaticFuelPlugin.distributedFilling.Value)
						{
							return;
						}
					}
				}
				foreach (Container item in nearbyContainers)
				{
					if (!Object.op_Implicit((Object)(object)fireplace.m_fuelItem) || num <= 0)
					{
						continue;
					}
					List<ItemData> list = new List<ItemData>();
					item.GetInventory().GetAllItems(fireplace.m_fuelItem.m_itemData.m_shared.m_name, list);
					foreach (ItemData item2 in list)
					{
						if (item2 != null && (!AutomaticFuelPlugin.leaveLastItem.Value || item2.m_stack > 1) && !AutomaticFuelPlugin.fuelDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item2.m_dropPrefab).name))
						{
							num--;
							AutomaticFuelPlugin.Dbgl($"container at {((Component)item).transform.position} has {item2.m_stack} {((Object)item2.m_dropPrefab).name}, taking one");
							znview.InvokeRPC("AddFuel", new object[0]);
							item.GetInventory().RemoveItem(fireplace.m_fuelItem.m_itemData.m_shared.m_name, 1, -1, true);
							typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item, new object[0]);
							typeof(Inventory).GetMethod("Changed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item.GetInventory(), new object[0]);
							if (AutomaticFuelPlugin.distributedFilling.Value)
							{
								return;
							}
						}
					}
				}
			}
			catch
			{
			}
		}
	}
	internal class Smelters
	{
		[HarmonyPatch(typeof(Smelter), "Awake")]
		public class BlastFurnacePatch
		{
			[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
			private static void Prefix(ref Smelter __instance)
			{
				//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00db: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_010a: Expected O, but got Unknown
				//IL_010b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0110: Unknown result type (might be due to invalid IL or missing references)
				//IL_0125: Unknown result type (might be due to invalid IL or missing references)
				//IL_013f: Expected O, but got Unknown
				//IL_0140: Unknown result type (might be due to invalid IL or missing references)
				//IL_0145: Unknown result type (might be due to invalid IL or missing references)
				//IL_015a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0174: Expected O, but got Unknown
				//IL_0175: Unknown result type (might be due to invalid IL or missing references)
				//IL_017a: Unknown result type (might be due to invalid IL or missing references)
				//IL_018f: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a9: Expected O, but got Unknown
				//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_01af: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_01de: Expected O, but got Unknown
				if (!AutomaticFuelPlugin.configBlastFurnaceTakesAll.Value)
				{
					return;
				}
				if (__instance.m_name != "$piece_blastfurnace")
				{
					Debug.Log((object)"Ignored non-blast furnace smelter.");
					return;
				}
				Debug.Log((object)"Found a blast furnace! Applying fix.");
				foreach (ItemDrop allItem in ObjectDB.instance.GetAllItems((ItemType)1, ""))
				{
					if (metals.Keys.Contains(allItem.m_itemData.m_shared.m_name))
					{
						Debug.Log((object)("Adding " + allItem.m_itemData.m_shared.m_name + " to list of materials."));
						metals[allItem.m_itemData.m_shared.m_name] = allItem;
					}
				}
				foreach (ItemConversion item in new List<ItemConversion>
				{
					new ItemConversion
					{
						m_from = metals["$item_copperore"],
						m_to = metals["$item_copper"]
					},
					new ItemConversion
					{
						m_from = metals["$item_tinore"],
						m_to = metals["$item_tin"]
					},
					new ItemConversion
					{
						m_from = metals["$item_ironscrap"],
						m_to = metals["$item_iron"]
					},
					new ItemConversion
					{
						m_from = metals["$item_silverore"],
						m_to = metals["$item_silver"]
					},
					new ItemConversion
					{
						m_from = metals["$item_copperscrap"],
						m_to = metals["$item_copper"]
					}
				})
				{
					__instance.m_conversion.Add(item);
				}
			}
		}

		[HarmonyPatch(typeof(Smelter), "UpdateSmoke")]
		private class SmelterUpdateSmoke_Patch
		{
			[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
			private static void Postfix(Smelter __instance)
			{
				if ((Object)(object)__instance.m_smokeSpawner != (Object)null && AutomaticFuelPlugin.configStackSmelters.Value)
				{
					((Behaviour)__instance.m_smokeSpawner).enabled = false;
					__instance.m_blockedSmoke = false;
				}
			}
		}

		[HarmonyPatch(typeof(Smelter), "UpdateSmelter")]
		private static class Smelter_FixedUpdate_Patch
		{
			[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
			private static void Postfix(Smelter __instance, ZNetView ___m_nview)
			{
				if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && AutomaticFuelPlugin.isOn.Value && !((Object)(object)___m_nview == (Object)null) && ___m_nview.IsOwner() && (!((Object)__instance).name.Contains("charcoal_kiln") || !AutomaticFuelPlugin.turnOffKiln.Value) && (!((Object)__instance).name.Contains("piece_spinningwheel") || !AutomaticFuelPlugin.turnOffSpinningWheel.Value) && (!((Object)__instance).name.Contains("windmill") || !AutomaticFuelPlugin.turnOffWindmills.Value))
				{
					if ((double)(Time.time - AutomaticFuelPlugin.lastFuel) < 0.1)
					{
						AutomaticFuelPlugin.fuelCount++;
						RefuelSmelter(__instance, ___m_nview, AutomaticFuelPlugin.fuelCount * 33);
					}
					else
					{
						AutomaticFuelPlugin.fuelCount = 0;
						AutomaticFuelPlugin.lastFuel = Time.time;
						RefuelSmelter(__instance, ___m_nview, 0);
					}
				}
			}
		}

		[<2fdb0271-2074-4d19-b012-27fac8ff016f>Nullable(1)]
		private static Dictionary<string, ItemDrop> metals = new Dictionary<string, ItemDrop>
		{
			{ "$item_copperore", null },
			{ "$item_copper", null },
			{ "$item_ironscrap", null },
			{ "$item_iron", null },
			{ "$item_tinore", null },
			{ "$item_tin", null },
			{ "$item_silverore", null },
			{ "$item_silver", null },
			{ "$item_copperscrap", null }
		};

		[<3bce1325-ce87-4e1a-bd8c-18816089810d>NullableContext(1)]
		public static async void RefuelSmelter(Smelter __instance, ZNetView ___m_nview, int delay)
		{
			await Task.Delay(delay);
			if (!Object.op_Implicit((Object)(object)__instance) || !Object.op_Implicit((Object)(object)___m_nview) || !___m_nview.IsValid() || !AutomaticFuelPlugin.modEnabled.Value)
			{
				return;
			}
			int num = __instance.m_maxOre - Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>();
			int num2 = __instance.m_maxFuel - Mathf.CeilToInt(___m_nview.GetZDO().GetFloat("fuel", 0f));
			List<Container> nearbyContainers = TastyUtils.GetNearbyContainers(((Component)__instance).transform.position, AutomaticFuelPlugin.smelterOreRange.Value);
			List<Container> nearbyContainers2 = TastyUtils.GetNearbyContainers(((Component)__instance).transform.position, AutomaticFuelPlugin.smelterFuelRange.Value);
			if (((Object)__instance).name.Contains("charcoal_kiln") && AutomaticFuelPlugin.restrictKilnOutput.Value)
			{
				string name = __instance.m_conversion[0].m_to.m_itemData.m_shared.m_name;
				int num3 = AutomaticFuelPlugin.restrictKilnOutputAmount.Value - Traverse.Create((object)__instance).Method("GetQueueSize", Array.Empty<object>()).GetValue<int>();
				foreach (Container item in nearbyContainers)
				{
					List<ItemData> list = new List<ItemData>();
					item.GetInventory().GetAllItems(name, list);
					foreach (ItemData item2 in list)
					{
						if (item2 != null)
						{
							num3 -= item2.m_stack;
						}
					}
				}
				if (num3 < 0)
				{
					num3 = 0;
				}
				if (num > num3)
				{
					num = num3;
				}
			}
			bool flag = false;
			bool flag2 = false;
			Collider[] array = Physics.OverlapSphere(((Component)__instance).transform.position + Vector3.up, AutomaticFuelPlugin.dropRange.Value, LayerMask.GetMask(new string[1] { "item" }));
			foreach (Collider val in array)
			{
				if (!Object.op_Implicit((Object)(object)((val != null) ? val.attachedRigidbody : null)))
				{
					continue;
				}
				ItemDrop component = ((Component)val.attachedRigidbody).GetComponent<ItemDrop>();
				int num4;
				if (component == null)
				{
					num4 = 1;
				}
				else
				{
					ZNetView component2 = ((Component)component).GetComponent<ZNetView>();
					num4 = ((((component2 != null) ? new bool?(component2.IsValid()) : null) != true) ? 1 : 0);
				}
				if (num4 != 0)
				{
					continue;
				}
				string prefabName = TastyUtils.GetPrefabName(((Object)((Component)component).gameObject).name);
				foreach (ItemConversion item3 in __instance.m_conversion)
				{
					if (flag2)
					{
						break;
					}
					if (!(component.m_itemData.m_shared.m_name == item3.m_from.m_itemData.m_shared.m_name) || num <= 0 || AutomaticFuelPlugin.oreDisallowTypes.Value.Split(new char[1] { ',' }).Contains(prefabName))
					{
						continue;
					}
					AutomaticFuelPlugin.Dbgl("auto adding ore " + prefabName + " from ground");
					int num5 = Mathf.Min(component.m_itemData.m_stack, num);
					num -= num5;
					for (int j = 0; j < num5; j++)
					{
						if (component.m_itemData.m_stack <= 1)
						{
							if (___m_nview.GetZDO() == null)
							{
								Object.Destroy((Object)(object)((Component)component).gameObject);
							}
							else
							{
								ZNetScene.instance.Destroy(((Component)component).gameObject);
							}
							___m_nview.InvokeRPC("AddOre", new object[1] { prefabName });
							if (AutomaticFuelPlugin.distributedFilling.Value)
							{
								flag2 = true;
							}
							break;
						}
						ItemData itemData = component.m_itemData;
						itemData.m_stack--;
						___m_nview.InvokeRPC("AddOre", new object[1] { prefabName });
						Traverse.Create((object)component).Method("Save", Array.Empty<object>()).GetValue();
						if (AutomaticFuelPlugin.distributedFilling.Value)
						{
							flag2 = true;
						}
					}
				}
				if (!Object.op_Implicit((Object)(object)__instance.m_fuelItem) || !(component.m_itemData.m_shared.m_name == __instance.m_fuelItem.m_itemData.m_shared.m_name) || num2 <= 0 || flag || AutomaticFuelPlugin.fuelDisallowTypes.Value.Split(new char[1] { ',' }).Contains(prefabName))
				{
					continue;
				}
				AutomaticFuelPlugin.Dbgl("auto adding fuel " + prefabName + " from ground");
				int num6 = Mathf.Min(component.m_itemData.m_stack, num2);
				num2 -= num6;
				for (int k = 0; k < num6; k++)
				{
					if (component.m_itemData.m_stack <= 1)
					{
						if (___m_nview.GetZDO() == null)
						{
							Object.Destroy((Object)(object)((Component)component).gameObject);
						}
						else
						{
							ZNetScene.instance.Destroy(((Component)component).gameObject);
						}
						___m_nview.InvokeRPC("AddFuel", new object[0]);
						if (AutomaticFuelPlugin.distributedFilling.Value)
						{
							flag = true;
						}
						break;
					}
					ItemData itemData2 = component.m_itemData;
					itemData2.m_stack--;
					___m_nview.InvokeRPC("AddFuel", new object[0]);
					Traverse.Create((object)component).Method("Save", Array.Empty<object>()).GetValue();
					if (AutomaticFuelPlugin.distributedFilling.Value)
					{
						flag = true;
						break;
					}
				}
			}
			foreach (Container item4 in nearbyContainers)
			{
				foreach (ItemConversion item5 in __instance.m_conversion)
				{
					if (flag2)
					{
						break;
					}
					List<ItemData> list2 = new List<ItemData>();
					item4.GetInventory().GetAllItems(item5.m_from.m_itemData.m_shared.m_name, list2);
					foreach (ItemData item6 in list2)
					{
						if (item6 != null && num > 0 && (!AutomaticFuelPlugin.leaveLastItem.Value || item6.m_stack > 1) && !AutomaticFuelPlugin.oreDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item6.m_dropPrefab).name))
						{
							num--;
							AutomaticFuelPlugin.Dbgl($"container at {((Component)item4).transform.position} has {item6.m_stack} {((Object)item6.m_dropPrefab).name}, taking one");
							object[] array2 = new object[1];
							GameObject dropPrefab = item6.m_dropPrefab;
							array2[0] = ((dropPrefab != null) ? ((Object)dropPrefab).name : null);
							___m_nview.InvokeRPC("AddOre", array2);
							item4.GetInventory().RemoveItem(item5.m_from.m_itemData.m_shared.m_name, 1, -1, true);
							typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item4, new object[0]);
							typeof(Inventory).GetMethod("Changed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item4.GetInventory(), new object[0]);
							if (AutomaticFuelPlugin.distributedFilling.Value)
							{
								flag2 = true;
								break;
							}
						}
					}
				}
			}
			foreach (Container item7 in nearbyContainers2)
			{
				if (!Object.op_Implicit((Object)(object)__instance.m_fuelItem) || num2 <= 0 || flag)
				{
					break;
				}
				List<ItemData> list3 = new List<ItemData>();
				item7.GetInventory().GetAllItems(__instance.m_fuelItem.m_itemData.m_shared.m_name, list3);
				foreach (ItemData item8 in list3)
				{
					if (item8 == null || (AutomaticFuelPlugin.leaveLastItem.Value && item8.m_stack <= 1))
					{
						continue;
					}
					num2--;
					if (!AutomaticFuelPlugin.fuelDisallowTypes.Value.Split(new char[1] { ',' }).Contains(((Object)item8.m_dropPrefab).name))
					{
						AutomaticFuelPlugin.Dbgl($"container at {((Component)item7).transform.position} has {item8.m_stack} {((Object)item8.m_dropPrefab).name}, taking one");
						___m_nview.InvokeRPC("AddFuel", new object[0]);
						item7.GetInventory().RemoveItem(__instance.m_fuelItem.m_itemData.m_shared.m_name, 1, -1, true);
						typeof(Container).GetMethod("Save", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item7, new object[0]);
						typeof(Inventory).GetMethod("Changed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(item7.GetInventory(), new object[0]);
						if (AutomaticFuelPlugin.distributedFilling.Value)
						{
							flag = true;
							break;
						}
					}
				}
			}
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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;
		}
	}
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	internal abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	internal class SyncedConfigEntry<T> : OwnConfigEntryBase
	{
		public readonly ConfigEntry<T> SourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public SyncedConfigEntry(ConfigEntry<T> sourceConfig)
		{
			SourceConfig = sourceConfig;
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type)
		{
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	internal sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T))
			: base(configSync, identifier, typeof(T))
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	internal class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					configSync2.IsSourceOfTruth = __instance.IsDedicated() || __instance.IsServer();
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_ConfigSync);
					if (isServer)
					{
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers()
								where adminList.Contains(p.m_rpc.GetSocket().GetHostName())
								select p).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_InitialConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPrefix]
			[HarmonyPriority(800)]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (__instance.IsServer())
				{
					BufferingSocket value = new BufferingSocket(rpc.GetSocket());
					AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value);
					object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (val != null && (int)ZNet.m_onlineBackend > 0)
					{
						AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value);
					}
					if (__state == null)
					{
						__state = new Dictionary<Assembly, BufferingSocket>();
					}
					__state[Assembly.GetExecutingAssembly()] = value;
				}
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZRpc rpc2 = rpc;
				ZNet __instance2 = __instance;
				Dictionary<Assembly, BufferingSocket> __state2 = __state;
				ZNetPeer peer;
				if (__instance2.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance2).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc2.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc2.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag.GetValueOrDefault();
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
				IL_0052:
				result = 0;
				goto IL_0053;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			ConfigEntry<T> configEntry2 = configEntry;
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry2);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry2.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			CustomSyncedValueBase customValue2 = customValue;
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue2);
			customValue2.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(ZRoutedRpc.Everybody, customValue2);
				}
			};
		}

		private void RPC_InitialConfigSync(ZRpc rpc, ZPackage package)
		{
			RPC_ConfigSync(0L, package);
		}

		private void RPC_ConfigSync(long sender, ZPackage package)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Expected O, but got Unknown
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					bool? obj;
					if ((int)val == 0)
					{
						obj = null;
					}
					else
					{
						ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
						object obj2;
						if (currentRpc == null)
						{
							obj2 = null;
						}
						else
						{
							ISocket socket = currentRpc.GetSocket();
							obj2 = ((socket != null) ? socket.GetHostName() : null);
						}
						obj = val.Contains((string)obj2);
					}
					if (obj == false)
					{
						return;
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2u) != 0)
				{
					long num = package.ReadLong();
					string text = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return;
					}
					configValueCache.Remove(text);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4u) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				if (!isServer)
				{
					if (IsSourceOfTruth)
					{
						lockedConfigChanged += serverLockedSettingChanged;
					}
					IsSourceOfTruth = false;
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				if (!isServer)
				{
					Debug.Log((object)$"Received {parsedConfigs.configValues.Count} configs and {parsedConfigs.customValues.Count} custom values from the server for mod {DisplayName ?? Name}");
					serverLockedSettingChanged();
				}
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			OwnConfigEntryBase config2 = config;
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			IsSourceOfTruth = true;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZNetPeer peer2 = peer;
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer2.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer2.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer2.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout");
						peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer2);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != ZRoutedRpc.Everybody)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			ZPackage package2 = package;
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package2.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package2 = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from peer in peers
				where peer.IsReady()
				select peer into p
				select distributeConfigToPeers(p, package2)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition()))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[HarmonyPatch]
	[PublicAPI]
	internal class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return "Mod " + DisplayName + " must not be installed.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			ZRpc rpc2 = rpc;
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout();
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")";
				}
			}
		}
	}
}

BepInEx/plugins/Tekla-AutoRepair/AutoRepair.dll

Decompiled 8 months ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AutoRepair")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AutoRepair")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9c03d122-ca5f-446a-aeff-1d08d6698593")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace AutoRepair
{
	[BepInPlugin("Tekla_AutoRepair", "AutoRepair", "5.4.1600")]
	public class Main : BaseUnityPlugin
	{
		public const string NAME = "AutoRepair";

		public const string AUTHOR = "Tekla";

		public const string GUID = "Tekla_AutoRepair";

		public const string VERSION = "5.4.1600";

		internal readonly ManualLogSource log;

		internal readonly Harmony harmony;

		internal readonly Assembly assembly;

		public readonly string modFolder;

		internal static ManualLogSource Log;

		public Main()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			Log = new ManualLogSource("AutoRepair");
			harmony = new Harmony("Tekla_AutoRepair");
			assembly = Assembly.GetExecutingAssembly();
			modFolder = Path.GetDirectoryName(assembly.Location);
		}

		public void Start()
		{
			Logger.Sources.Add((ILogSource)(object)Log);
			harmony.PatchAll(assembly);
		}
	}
}
namespace AutoRepair.Patches
{
	[HarmonyPatch]
	public static class Patches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(CraftingStation), "Interact")]
		public static void CraftingStation_Interact(CraftingStation __instance, Humanoid user, bool repeat, bool alt)
		{
			int num = 0;
			InventoryGui instance = InventoryGui.instance;
			while (instance.HaveRepairableItems())
			{
				num++;
				instance.RepairOneItem();
			}
			if (num > 0)
			{
				((Character)Player.m_localPlayer).Message((MessageType)2, " ", 0, (Sprite)null);
				Main.Log.LogInfo((object)$"[AutoRepair] Repaired {num} objects!\n");
			}
		}
	}
}

BepInEx/plugins/Valheim.DisplayBepInExInfo.dll

Decompiled 8 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
namespace Valheim.DisplayBepInExInfo;

[BepInPlugin("org.bepinex.valheim.displayinfo", "Display BepInEx Info In-Game", "2.0.1")]
public class DisplayInfoPlugin : BaseUnityPlugin
{
	internal static ConfigEntry<LogLevel> LogLevels;

	internal static ConfigEntry<bool> DisplayLogsInConsole;

	internal static string BepInExVersion => typeof(BaseUnityPlugin).Assembly.GetName().Version.ToString();

	private void Awake()
	{
		LogLevels = ((BaseUnityPlugin)this).Config.Bind<LogLevel>("Console", "LogLevels", (LogLevel)30, "Log levels to log to Valheim console.");
		DisplayLogsInConsole = ((BaseUnityPlugin)this).Config.Bind<bool>("Console", "DisplayBepInExLogs", true, "If true, will display BepInEx logs in Valheim console.");
		if (DisplayLogsInConsole.Value)
		{
			Logger.Listeners.Add((ILogListener)(object)new ValheimConsoleListener());
		}
		Harmony.CreateAndPatchAll(typeof(DisplayInfoPlugin), (string)null);
		Traverse.Create<Game>().Field<bool>("isModded").Value = true;
	}

	[HarmonyPatch(typeof(FejdStartup), "Start")]
	[HarmonyPostfix]
	private static void OnFejdStartup(FejdStartup __instance)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
		GameObject gameObject = ((Component)((Component)__instance.m_versionLabel).transform.parent).gameObject;
		GameObject val = new GameObject("BepInEx Version");
		val.transform.parent = gameObject.transform;
		val.AddComponent<CanvasRenderer>();
		val.transform.localPosition = Vector3.zero;
		RectTransform obj = val.AddComponent<RectTransform>();
		obj.anchorMin = new Vector2(0.03f, 0.95f);
		obj.anchorMax = new Vector2(0.3f, 0.95f);
		Text val2 = val.AddComponent<Text>();
		val2.font = Font.CreateDynamicFontFromOSFont("Arial", 20);
		val2.text = $"Running BepInEx {BepInExVersion}\n{Chainloader.PluginInfos.Count} plugins loaded";
		if (Console.instance.IsConsoleEnabled())
		{
			val2.text += "\nPress F5 to open console";
		}
		((Graphic)val2).color = Color.white;
		val2.fontSize = 20;
	}

	[HarmonyPatch(typeof(ZNet), "SetServer")]
	[HarmonyPostfix]
	private static void OnServerStart(string serverName)
	{
		Type type = typeof(BaseUnityPlugin).Assembly.GetType("BepInEx.ConsoleManager", throwOnError: false);
		if (!(type == null))
		{
			AccessTools.MethodDelegate<Action<string>>(AccessTools.Method(type, "SetConsoleTitle", (Type[])null, (Type[])null), (object)null, true)("BepInEx " + BepInExVersion + " - Valheim Server - " + serverName);
		}
	}

	[HarmonyPatch(typeof(Terminal), "Awake")]
	[HarmonyPostfix]
	private static void FixConsoleMesh()
	{
		if (Object.op_Implicit((Object)(object)Console.instance) && Object.op_Implicit((Object)(object)((Component)((Terminal)Console.instance).m_chatWindow).gameObject))
		{
			Outline[] componentsInChildren = ((Component)((Terminal)Console.instance).m_chatWindow).gameObject.GetComponentsInChildren<Outline>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				((Behaviour)componentsInChildren[i]).enabled = false;
			}
		}
	}

	[HarmonyPatch(typeof(Terminal), "UpdateChat")]
	[HarmonyPostfix]
	private static void FixConsoleMesh2()
	{
		if (((TMP_Text)((Terminal)Console.instance).m_output).text.Length > 6000)
		{
			((Terminal)Console.instance).m_chatBuffer.Clear();
		}
	}
}
internal class ValheimConsoleListener : ILogListener, IDisposable
{
	public void Dispose()
	{
	}

	public void LogEvent(object sender, LogEventArgs eventArgs)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		if ((eventArgs.Level & DisplayInfoPlugin.LogLevels.Value) != 0 && Object.op_Implicit((Object)(object)Console.instance))
		{
			Console.instance.Print(((object)eventArgs).ToString());
		}
	}
}

BepInEx/plugins/ValheimModding-Jotunn/Jotunn.dll

Decompiled 8 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn;
using Jotunn.Configs;
using Jotunn.ConsoleCommands;
using Jotunn.Entities;
using Jotunn.GUI;
using Jotunn.Managers;
using Jotunn.Managers.MockSystem;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using SimpleJson;
using SimpleJson.Reflection;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.U2D;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("JotunnTests")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("Valheim-Modding team")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Jötunn (/ˈjɔːtʊn/, \"giant\") is a modding library for Valheim, with the goal of making the lives of mod developers easier.")]
[assembly: AssemblyFileVersion("2.12.7.0")]
[assembly: AssemblyInformationalVersion("2.12.7")]
[assembly: AssemblyProduct("JotunnLib")]
[assembly: AssemblyTitle("Jotunn")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Valheim-Modding/Jotunn")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.12.7.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
}
internal class CompatibilityWindow : MonoBehaviour
{
	public ScrollRect scrollRect;

	public Text failedConnection;

	public Text localVersion;

	public Text remoteVersion;

	public Text errorMessages;

	public Button continueButton;

	public Button logFileButton;

	public Button troubleshootingButton;

	public void UpdateTextPositions()
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: 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_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Expected O, but got Unknown
		float preferredHeight = failedConnection.preferredHeight;
		float preferredHeight2 = localVersion.preferredHeight;
		float preferredHeight3 = remoteVersion.preferredHeight;
		float preferredHeight4 = errorMessages.preferredHeight;
		Vector2 anchoredPosition = ((Graphic)localVersion).rectTransform.anchoredPosition;
		Vector2 anchoredPosition2 = ((Graphic)remoteVersion).rectTransform.anchoredPosition;
		float num = preferredHeight + 32f;
		((Graphic)localVersion).rectTransform.anchoredPosition = new Vector2(anchoredPosition.x, 0f - num);
		((Graphic)remoteVersion).rectTransform.anchoredPosition = new Vector2(anchoredPosition2.x, 0f - num);
		Vector2 anchoredPosition3 = ((Graphic)errorMessages).rectTransform.anchoredPosition;
		float num2 = num + Mathf.Max(preferredHeight2, preferredHeight3) + 32f;
		((Graphic)errorMessages).rectTransform.anchoredPosition = new Vector2(anchoredPosition3.x, 0f - num2);
		RectTransform val = (RectTransform)((Component)scrollRect.content).transform;
		val.SetSizeWithCurrentAnchors((Axis)1, num2 + preferredHeight4);
	}
}
public sealed class ConfigurationManagerAttributes
{
	public bool? ShowRangeAsPercent;

	public Action<ConfigEntryBase> CustomDrawer;

	public bool? Browsable;

	public string Category;

	public object DefaultValue;

	public bool? HideDefaultButton;

	public bool? HideSettingName;

	public string Description;

	public string DispName;

	public int? Order;

	public bool? ReadOnly;

	public bool? IsAdvanced;

	public Func<object, string> ObjToStr;

	public Func<string, object> StrToObj;

	private bool isAdminOnly;

	private bool isUnlocked;

	private static readonly PropertyInfo[] _myProperties = typeof(ConfigurationManagerAttributes).GetProperties(BindingFlags.Instance | BindingFlags.Public);

	private static readonly FieldInfo[] _myFields = typeof(ConfigurationManagerAttributes).GetFields(BindingFlags.Instance | BindingFlags.Public);

	public bool IsAdminOnly
	{
		get
		{
			return isAdminOnly;
		}
		set
		{
			isAdminOnly = value;
			IsUnlocked = !value;
		}
	}

	public Color EntryColor { get; set; }

	public Color DescriptionColor { get; set; }

	public bool IsUnlocked
	{
		get
		{
			return isUnlocked;
		}
		internal set
		{
			ReadOnly = !value;
			HideDefaultButton = !value;
			isUnlocked = value;
		}
	}

	public ConfigurationManagerAttributes()
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		EntryColor = new Color(1f, 0.631f, 0.235f, 1f);
		DescriptionColor = Color.white;
	}

	public void SetFromAttributes(object[] attribs)
	{
		if (attribs == null || attribs.Length == 0)
		{
			return;
		}
		foreach (object obj in attribs)
		{
			if (obj == null)
			{
				continue;
			}
			if (!(obj is DisplayNameAttribute displayNameAttribute))
			{
				if (!(obj is CategoryAttribute categoryAttribute))
				{
					if (!(obj is DescriptionAttribute descriptionAttribute))
					{
						if (!(obj is DefaultValueAttribute defaultValueAttribute))
						{
							if (!(obj is ReadOnlyAttribute readOnlyAttribute))
							{
								if (!(obj is BrowsableAttribute browsableAttribute))
								{
									if (obj is string text)
									{
										switch (text)
										{
										case "ReadOnly":
											ReadOnly = true;
											break;
										case "Browsable":
											Browsable = true;
											break;
										case "Unbrowsable":
										case "Hidden":
											Browsable = false;
											break;
										case "Advanced":
											IsAdvanced = true;
											break;
										}
										continue;
									}
									Type type = obj.GetType();
									if (!(type.Name == "ConfigurationManagerAttributes"))
									{
										break;
									}
									FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
									foreach (var item in from my in _myProperties
										join other in fields on my.Name equals other.Name
										select new { my, other })
									{
										try
										{
											object obj2 = item.other.GetValue(obj);
											if (obj2 != null)
											{
												if (item.my.PropertyType != item.other.FieldType && typeof(Delegate).IsAssignableFrom(item.my.PropertyType))
												{
													obj2 = Delegate.CreateDelegate(item.my.PropertyType, ((Delegate)obj2).Target, ((Delegate)obj2).Method);
												}
												item.my.SetValue(this, obj2, null);
											}
										}
										catch (Exception ex)
										{
											Logger.LogWarning("Failed to copy value " + item.my.Name + " from provided tag object " + type.FullName + " - " + ex.Message);
										}
									}
									foreach (var item2 in from my in _myFields
										join other in fields on my.Name equals other.Name
										select new { my, other })
									{
										try
										{
											object obj3 = item2.other.GetValue(obj);
											if (obj3 != null)
											{
												if (item2.my.FieldType != item2.other.FieldType && typeof(Delegate).IsAssignableFrom(item2.my.FieldType))
												{
													obj3 = Delegate.CreateDelegate(item2.my.FieldType, ((Delegate)obj3).Target, ((Delegate)obj3).Method);
												}
												item2.my.SetValue(this, obj3);
											}
										}
										catch (Exception ex2)
										{
											Logger.LogWarning("Failed to copy value " + item2.my.Name + " from provided tag object " + type.FullName + " - " + ex2.Message);
										}
									}
								}
								else
								{
									Browsable = browsableAttribute.Browsable;
								}
							}
							else
							{
								ReadOnly = readOnlyAttribute.IsReadOnly;
							}
						}
						else
						{
							DefaultValue = defaultValueAttribute.Value;
						}
					}
					else
					{
						Description = descriptionAttribute.Description;
					}
				}
				else
				{
					Category = categoryAttribute.Category;
				}
			}
			else
			{
				DispName = displayNameAttribute.DisplayName;
			}
		}
	}
}
public static class ObjImporter
{
	private struct meshStruct
	{
		public Vector3[] vertices;

		public Vector3[] normals;

		public Vector2[] uv;

		public Vector2[] uv1;

		public Vector2[] uv2;

		public int[] triangles;

		public int[] faceVerts;

		public int[] faceUVs;

		public Vector3[] faceData;

		public string name;

		public string fileName;
	}

	public static Mesh ImportFile(string filePath)
	{
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: 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_006e: 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_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Expected O, but got Unknown
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		meshStruct mesh = CreateMeshStruct(filePath);
		PopulateMeshStruct(ref mesh);
		Vector3[] array = (Vector3[])(object)new Vector3[mesh.faceData.Length];
		Vector2[] array2 = (Vector2[])(object)new Vector2[mesh.faceData.Length];
		Vector3[] array3 = (Vector3[])(object)new Vector3[mesh.faceData.Length];
		int num = 0;
		Vector3[] faceData = mesh.faceData;
		foreach (Vector3 val in faceData)
		{
			array[num] = mesh.vertices[(int)val.x - 1];
			if (val.y >= 1f)
			{
				array2[num] = mesh.uv[(int)val.y - 1];
			}
			if (val.z >= 1f)
			{
				array3[num] = mesh.normals[(int)val.z - 1];
			}
			num++;
		}
		Mesh val2 = new Mesh();
		val2.vertices = array;
		val2.uv = array2;
		val2.normals = array3;
		val2.triangles = mesh.triangles;
		val2.RecalculateBounds();
		val2.Optimize();
		return val2;
	}

	private static meshStruct CreateMeshStruct(string filename)
	{
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		int num5 = 0;
		meshStruct result = default(meshStruct);
		result.fileName = filename;
		StreamReader streamReader = File.OpenText(filename);
		string s = streamReader.ReadToEnd();
		streamReader.Close();
		using (StringReader stringReader = new StringReader(s))
		{
			string text = stringReader.ReadLine();
			char[] separator = new char[1] { ' ' };
			while (text != null)
			{
				if (!text.StartsWith("f ") && !text.StartsWith("v ") && !text.StartsWith("vt ") && !text.StartsWith("vn "))
				{
					text = stringReader.ReadLine();
					if (text != null)
					{
						text = text.Replace("  ", " ");
					}
					continue;
				}
				text = text.Trim();
				string[] array = text.Split(separator, 50);
				switch (array[0])
				{
				case "v":
					num2++;
					break;
				case "vt":
					num3++;
					break;
				case "vn":
					num4++;
					break;
				case "f":
					num5 = num5 + array.Length - 1;
					num += 3 * (array.Length - 2);
					break;
				}
				text = stringReader.ReadLine();
				if (text != null)
				{
					text = text.Replace("  ", " ");
				}
			}
		}
		result.triangles = new int[num];
		result.vertices = (Vector3[])(object)new Vector3[num2];
		result.uv = (Vector2[])(object)new Vector2[num3];
		result.normals = (Vector3[])(object)new Vector3[num4];
		result.faceData = (Vector3[])(object)new Vector3[num5];
		return result;
	}

	private static void PopulateMeshStruct(ref meshStruct mesh)
	{
		//IL_0329: Unknown result type (might be due to invalid IL or missing references)
		//IL_032e: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0390: Unknown result type (might be due to invalid IL or missing references)
		//IL_0395: Unknown result type (might be due to invalid IL or missing references)
		//IL_0358: Unknown result type (might be due to invalid IL or missing references)
		//IL_035d: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0423: Unknown result type (might be due to invalid IL or missing references)
		//IL_0425: Unknown result type (might be due to invalid IL or missing references)
		StreamReader streamReader = File.OpenText(mesh.fileName);
		string s = streamReader.ReadToEnd();
		streamReader.Close();
		using StringReader stringReader = new StringReader(s);
		string text = stringReader.ReadLine();
		char[] separator = new char[1] { ' ' };
		char[] separator2 = new char[1] { '/' };
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		int num5 = 0;
		int num6 = 0;
		int num7 = 0;
		while (text != null)
		{
			if (!text.StartsWith("f ") && !text.StartsWith("v ") && !text.StartsWith("vt ") && !text.StartsWith("vn ") && !text.StartsWith("g ") && !text.StartsWith("usemtl ") && !text.StartsWith("mtllib ") && !text.StartsWith("vt1 ") && !text.StartsWith("vt2 ") && !text.StartsWith("vc ") && !text.StartsWith("usemap "))
			{
				text = stringReader.ReadLine();
				if (text != null)
				{
					text = text.Replace("  ", " ");
				}
				continue;
			}
			text = text.Trim();
			string[] array = text.Split(separator, 50);
			switch (array[0])
			{
			case "v":
				mesh.vertices[num3] = new Vector3(Convert.ToSingle(array[1]), Convert.ToSingle(array[2]), Convert.ToSingle(array[3]));
				num3++;
				break;
			case "vt":
				mesh.uv[num5] = new Vector2(Convert.ToSingle(array[1]), Convert.ToSingle(array[2]));
				num5++;
				break;
			case "vt1":
				mesh.uv[num6] = new Vector2(Convert.ToSingle(array[1]), Convert.ToSingle(array[2]));
				num6++;
				break;
			case "vt2":
				mesh.uv[num7] = new Vector2(Convert.ToSingle(array[1]), Convert.ToSingle(array[2]));
				num7++;
				break;
			case "vn":
				mesh.normals[num4] = new Vector3(Convert.ToSingle(array[1]), Convert.ToSingle(array[2]), Convert.ToSingle(array[3]));
				num4++;
				break;
			case "f":
			{
				int num8 = 1;
				List<int> list = new List<int>();
				while (num8 < array.Length && (array[num8] ?? "").Length > 0)
				{
					Vector3 val = default(Vector3);
					string[] array2 = array[num8].Split(separator2, 3);
					val.x = Convert.ToInt32(array2[0]);
					if (array2.Length > 1)
					{
						if (array2[1] != "")
						{
							val.y = Convert.ToInt32(array2[1]);
						}
						val.z = Convert.ToInt32(array2[2]);
					}
					num8++;
					mesh.faceData[num2] = val;
					list.Add(num2);
					num2++;
				}
				for (num8 = 1; num8 + 2 < array.Length; num8++)
				{
					mesh.triangles[num] = list[0];
					num++;
					mesh.triangles[num] = list[num8];
					num++;
					mesh.triangles[num] = list[num8 + 1];
					num++;
				}
				break;
			}
			}
			text = stringReader.ReadLine();
			if (text != null)
			{
				text = text.Replace("  ", " ");
			}
		}
	}
}
namespace SimpleJson
{
	[GeneratedCode("simple-json", "1.0.0")]
	[EditorBrowsable(EditorBrowsableState.Never)]
	public class JsonArray : List<object>
	{
		public JsonArray()
		{
		}

		public JsonArray(int capacity)
			: base(capacity)
		{
		}

		public override string ToString()
		{
			return SimpleJson.SerializeObject(this) ?? string.Empty;
		}
	}
	[GeneratedCode("simple-json", "1.0.0")]
	[EditorBrowsable(EditorBrowsableState.Never)]
	public class JsonObject : IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable
	{
		private readonly Dictionary<string, object> _members;

		public object this[int index] => GetAtIndex(_members, index);

		public ICollection<string> Keys => _members.Keys;

		public ICollection<object> Values => _members.Values;

		public object this[string key]
		{
			get
			{
				return _members[key];
			}
			set
			{
				_members[key] = value;
			}
		}

		public int Count => _members.Count;

		public bool IsReadOnly => false;

		public JsonObject()
		{
			_members = new Dictionary<string, object>();
		}

		public JsonObject(IEqualityComparer<string> comparer)
		{
			_members = new Dictionary<string, object>(comparer);
		}

		internal static object GetAtIndex(IDictionary<string, object> obj, int index)
		{
			if (obj == null)
			{
				throw new ArgumentNullException("obj");
			}
			if (index >= obj.Count)
			{
				throw new ArgumentOutOfRangeException("index");
			}
			int num = 0;
			foreach (KeyValuePair<string, object> item in obj)
			{
				if (num++ == index)
				{
					return item.Value;
				}
			}
			return null;
		}

		public void Add(string key, object value)
		{
			_members.Add(key, value);
		}

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

		public bool Remove(string key)
		{
			return _members.Remove(key);
		}

		public bool TryGetValue(string key, out object value)
		{
			return _members.TryGetValue(key, out value);
		}

		public void Add(KeyValuePair<string, object> item)
		{
			_members.Add(item.Key, item.Value);
		}

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

		public bool Contains(KeyValuePair<string, object> item)
		{
			if (_members.ContainsKey(item.Key))
			{
				return _members[item.Key] == item.Value;
			}
			return false;
		}

		public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			int num = Count;
			using IEnumerator<KeyValuePair<string, object>> enumerator = GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValuePair<string, object> current = enumerator.Current;
				array[arrayIndex++] = current;
				if (--num <= 0)
				{
					break;
				}
			}
		}

		public bool Remove(KeyValuePair<string, object> item)
		{
			return _members.Remove(item.Key);
		}

		public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
		{
			return _members.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _members.GetEnumerator();
		}

		public override string ToString()
		{
			return SimpleJson.SerializeObject(this);
		}
	}
	[GeneratedCode("simple-json", "1.0.0")]
	public static class SimpleJson
	{
		private const int TOKEN_NONE = 0;

		private const int TOKEN_CURLY_OPEN = 1;

		private const int TOKEN_CURLY_CLOSE = 2;

		private const int TOKEN_SQUARED_OPEN = 3;

		private const int TOKEN_SQUARED_CLOSE = 4;

		private const int TOKEN_COLON = 5;

		private const int TOKEN_COMMA = 6;

		private const int TOKEN_STRING = 7;

		private const int TOKEN_NUMBER = 8;

		private const int TOKEN_TRUE = 9;

		private const int TOKEN_FALSE = 10;

		private const int TOKEN_NULL = 11;

		private const int BUILDER_CAPACITY = 2000;

		private static readonly char[] EscapeTable;

		private static readonly char[] EscapeCharacters;

		private static readonly string EscapeCharactersString;

		private static IJsonSerializerStrategy _currentJsonSerializerStrategy;

		private static PocoJsonSerializerStrategy _pocoJsonSerializerStrategy;

		public static IJsonSerializerStrategy CurrentJsonSerializerStrategy
		{
			get
			{
				return _currentJsonSerializerStrategy ?? (_currentJsonSerializerStrategy = PocoJsonSerializerStrategy);
			}
			set
			{
				_currentJsonSerializerStrategy = value;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy => _pocoJsonSerializerStrategy ?? (_pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy());

		static SimpleJson()
		{
			EscapeCharacters = new char[7] { '"', '\\', '\b', '\f', '\n', '\r', '\t' };
			EscapeCharactersString = new string(EscapeCharacters);
			EscapeTable = new char[93];
			EscapeTable[34] = '"';
			EscapeTable[92] = '\\';
			EscapeTable[8] = 'b';
			EscapeTable[12] = 'f';
			EscapeTable[10] = 'n';
			EscapeTable[13] = 'r';
			EscapeTable[9] = 't';
		}

		public static object DeserializeObject(string json)
		{
			if (TryDeserializeObject(json, out var obj))
			{
				return obj;
			}
			throw new SerializationException("Invalid JSON string");
		}

		public static bool TryDeserializeObject(string json, out object obj)
		{
			bool success = true;
			if (json != null)
			{
				char[] json2 = json.ToCharArray();
				int index = 0;
				obj = ParseValue(json2, ref index, ref success);
			}
			else
			{
				obj = null;
			}
			return success;
		}

		public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy)
		{
			object obj = DeserializeObject(json);
			if (!(type == null) && (obj == null || !ReflectionUtils.IsAssignableFrom(obj.GetType(), type)))
			{
				return (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(obj, type);
			}
			return obj;
		}

		public static object DeserializeObject(string json, Type type)
		{
			return DeserializeObject(json, type, null);
		}

		public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy)
		{
			return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy);
		}

		public static T DeserializeObject<T>(string json)
		{
			return (T)DeserializeObject(json, typeof(T), null);
		}

		public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy)
		{
			StringBuilder stringBuilder = new StringBuilder(2000);
			if (!SerializeValue(jsonSerializerStrategy, json, stringBuilder))
			{
				return null;
			}
			return stringBuilder.ToString();
		}

		public static string SerializeObject(object json)
		{
			return SerializeObject(json, CurrentJsonSerializerStrategy);
		}

		public static string EscapeToJavascriptString(string jsonString)
		{
			if (string.IsNullOrEmpty(jsonString))
			{
				return jsonString;
			}
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			while (num < jsonString.Length)
			{
				char c = jsonString[num++];
				if (c == '\\')
				{
					int num2 = jsonString.Length - num;
					if (num2 >= 2)
					{
						switch (jsonString[num])
						{
						case '\\':
							stringBuilder.Append('\\');
							num++;
							break;
						case '"':
							stringBuilder.Append("\"");
							num++;
							break;
						case 't':
							stringBuilder.Append('\t');
							num++;
							break;
						case 'b':
							stringBuilder.Append('\b');
							num++;
							break;
						case 'n':
							stringBuilder.Append('\n');
							num++;
							break;
						case 'r':
							stringBuilder.Append('\r');
							num++;
							break;
						}
					}
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}

		private static IDictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)
		{
			IDictionary<string, object> dictionary = new JsonObject();
			NextToken(json, ref index);
			bool flag = false;
			while (!flag)
			{
				switch (LookAhead(json, index))
				{
				case 0:
					success = false;
					return null;
				case 6:
					NextToken(json, ref index);
					continue;
				case 2:
					NextToken(json, ref index);
					return dictionary;
				}
				string key = ParseString(json, ref index, ref success);
				if (!success)
				{
					success = false;
					return null;
				}
				int num = NextToken(json, ref index);
				if (num != 5)
				{
					success = false;
					return null;
				}
				object value = ParseValue(json, ref index, ref success);
				if (!success)
				{
					success = false;
					return null;
				}
				dictionary[key] = value;
			}
			return dictionary;
		}

		private static JsonArray ParseArray(char[] json, ref int index, ref bool success)
		{
			JsonArray jsonArray = new JsonArray();
			NextToken(json, ref index);
			bool flag = false;
			while (!flag)
			{
				switch (LookAhead(json, index))
				{
				case 0:
					success = false;
					return null;
				case 6:
					NextToken(json, ref index);
					continue;
				case 4:
					break;
				default:
				{
					object item = ParseValue(json, ref index, ref success);
					if (!success)
					{
						return null;
					}
					jsonArray.Add(item);
					continue;
				}
				}
				NextToken(json, ref index);
				break;
			}
			return jsonArray;
		}

		private static object ParseValue(char[] json, ref int index, ref bool success)
		{
			switch (LookAhead(json, index))
			{
			case 7:
				return ParseString(json, ref index, ref success);
			case 8:
				return ParseNumber(json, ref index, ref success);
			case 1:
				return ParseObject(json, ref index, ref success);
			case 3:
				return ParseArray(json, ref index, ref success);
			case 9:
				NextToken(json, ref index);
				return true;
			case 10:
				NextToken(json, ref index);
				return false;
			case 11:
				NextToken(json, ref index);
				return null;
			default:
				success = false;
				return null;
			}
		}

		private static string ParseString(char[] json, ref int index, ref bool success)
		{
			StringBuilder stringBuilder = new StringBuilder(2000);
			EatWhitespace(json, ref index);
			char c = json[index++];
			bool flag = false;
			while (!flag && index != json.Length)
			{
				c = json[index++];
				switch (c)
				{
				case '"':
					flag = true;
					break;
				case '\\':
				{
					if (index == json.Length)
					{
						break;
					}
					switch (json[index++])
					{
					case '"':
						stringBuilder.Append('"');
						continue;
					case '\\':
						stringBuilder.Append('\\');
						continue;
					case '/':
						stringBuilder.Append('/');
						continue;
					case 'b':
						stringBuilder.Append('\b');
						continue;
					case 'f':
						stringBuilder.Append('\f');
						continue;
					case 'n':
						stringBuilder.Append('\n');
						continue;
					case 'r':
						stringBuilder.Append('\r');
						continue;
					case 't':
						stringBuilder.Append('\t');
						continue;
					case 'u':
						break;
					default:
						continue;
					}
					int num = json.Length - index;
					if (num < 4)
					{
						break;
					}
					if (!(success = uint.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var result)))
					{
						return "";
					}
					if (55296 <= result && result <= 56319)
					{
						index += 4;
						num = json.Length - index;
						if (num < 6 || !(new string(json, index, 2) == "\\u") || !uint.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var result2) || 56320 > result2 || result2 > 57343)
						{
							success = false;
							return "";
						}
						stringBuilder.Append((char)result);
						stringBuilder.Append((char)result2);
						index += 6;
					}
					else
					{
						stringBuilder.Append(ConvertFromUtf32((int)result));
						index += 4;
					}
					continue;
				}
				default:
					stringBuilder.Append(c);
					continue;
				}
				break;
			}
			if (!flag)
			{
				success = false;
				return null;
			}
			return stringBuilder.ToString();
		}

		private static string ConvertFromUtf32(int utf32)
		{
			if (utf32 < 0 || utf32 > 1114111)
			{
				throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
			}
			if (55296 <= utf32 && utf32 <= 57343)
			{
				throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range.");
			}
			if (utf32 < 65536)
			{
				return new string((char)utf32, 1);
			}
			utf32 -= 65536;
			return new string(new char[2]
			{
				(char)((utf32 >> 10) + 55296),
				(char)(utf32 % 1024 + 56320)
			});
		}

		private static object ParseNumber(char[] json, ref int index, ref bool success)
		{
			EatWhitespace(json, ref index);
			int lastIndexOfNumber = GetLastIndexOfNumber(json, index);
			int length = lastIndexOfNumber - index + 1;
			string text = new string(json, index, length);
			object result2;
			if (text.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || text.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
			{
				success = double.TryParse(new string(json, index, length), NumberStyles.Any, CultureInfo.InvariantCulture, out var result);
				result2 = result;
			}
			else
			{
				success = long.TryParse(new string(json, index, length), NumberStyles.Any, CultureInfo.InvariantCulture, out var result3);
				result2 = result3;
			}
			index = lastIndexOfNumber + 1;
			return result2;
		}

		private static int GetLastIndexOfNumber(char[] json, int index)
		{
			int i;
			for (i = index; i < json.Length && "0123456789+-.eE".IndexOf(json[i]) != -1; i++)
			{
			}
			return i - 1;
		}

		private static void EatWhitespace(char[] json, ref int index)
		{
			while (index < json.Length && " \t\n\r\b\f".IndexOf(json[index]) != -1)
			{
				index++;
			}
		}

		private static int LookAhead(char[] json, int index)
		{
			int index2 = index;
			return NextToken(json, ref index2);
		}

		private static int NextToken(char[] json, ref int index)
		{
			EatWhitespace(json, ref index);
			if (index == json.Length)
			{
				return 0;
			}
			char c = json[index];
			index++;
			switch (c)
			{
			case '{':
				return 1;
			case '}':
				return 2;
			case '[':
				return 3;
			case ']':
				return 4;
			case ',':
				return 6;
			case '"':
				return 7;
			case '-':
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				return 8;
			case ':':
				return 5;
			default:
			{
				index--;
				int num = json.Length - index;
				if (num >= 5 && json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')
				{
					index += 5;
					return 10;
				}
				if (num >= 4 && json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')
				{
					index += 4;
					return 9;
				}
				if (num >= 4 && json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')
				{
					index += 4;
					return 11;
				}
				return 0;
			}
			}
		}

		private static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder)
		{
			bool flag = true;
			if (value is string aString)
			{
				flag = SerializeString(aString, builder);
			}
			else if (value is IDictionary<string, object> dictionary)
			{
				flag = SerializeObject(jsonSerializerStrategy, dictionary.Keys, dictionary.Values, builder);
			}
			else if (value is IDictionary<string, string> dictionary2)
			{
				flag = SerializeObject(jsonSerializerStrategy, dictionary2.Keys, dictionary2.Values, builder);
			}
			else if (value is IEnumerable anArray)
			{
				flag = SerializeArray(jsonSerializerStrategy, anArray, builder);
			}
			else if (IsNumeric(value))
			{
				flag = SerializeNumber(value, builder);
			}
			else if (value is bool)
			{
				builder.Append(((bool)value) ? "true" : "false");
			}
			else if (value == null)
			{
				builder.Append("null");
			}
			else
			{
				flag = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out var output);
				if (flag)
				{
					SerializeValue(jsonSerializerStrategy, output, builder);
				}
			}
			return flag;
		}

		private static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder)
		{
			builder.Append("{");
			IEnumerator enumerator = keys.GetEnumerator();
			IEnumerator enumerator2 = values.GetEnumerator();
			bool flag = true;
			while (enumerator.MoveNext() && enumerator2.MoveNext())
			{
				object current = enumerator.Current;
				object current2 = enumerator2.Current;
				if (!flag)
				{
					builder.Append(",");
				}
				if (current is string aString)
				{
					SerializeString(aString, builder);
				}
				else if (!SerializeValue(jsonSerializerStrategy, current2, builder))
				{
					return false;
				}
				builder.Append(":");
				if (!SerializeValue(jsonSerializerStrategy, current2, builder))
				{
					return false;
				}
				flag = false;
			}
			builder.Append("}");
			return true;
		}

		private static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder)
		{
			builder.Append("[");
			bool flag = true;
			foreach (object item in anArray)
			{
				if (!flag)
				{
					builder.Append(",");
				}
				if (!SerializeValue(jsonSerializerStrategy, item, builder))
				{
					return false;
				}
				flag = false;
			}
			builder.Append("]");
			return true;
		}

		private static bool SerializeString(string aString, StringBuilder builder)
		{
			if (aString.IndexOfAny(EscapeCharacters) == -1)
			{
				builder.Append('"');
				builder.Append(aString);
				builder.Append('"');
				return true;
			}
			builder.Append('"');
			int num = 0;
			char[] array = aString.ToCharArray();
			for (int i = 0; i < array.Length; i++)
			{
				char c = array[i];
				if (c >= EscapeTable.Length || EscapeTable[(uint)c] == '\0')
				{
					num++;
					continue;
				}
				if (num > 0)
				{
					builder.Append(array, i - num, num);
					num = 0;
				}
				builder.Append('\\');
				builder.Append(EscapeTable[(uint)c]);
			}
			if (num > 0)
			{
				builder.Append(array, array.Length - num, num);
			}
			builder.Append('"');
			return true;
		}

		private static bool SerializeNumber(object number, StringBuilder builder)
		{
			if (number is long)
			{
				builder.Append(((long)number).ToString(CultureInfo.InvariantCulture));
			}
			else if (number is ulong)
			{
				builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture));
			}
			else if (number is int)
			{
				builder.Append(((int)number).ToString(CultureInfo.InvariantCulture));
			}
			else if (number is uint)
			{
				builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture));
			}
			else if (number is decimal)
			{
				builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture));
			}
			else if (number is float)
			{
				builder.Append(((float)number).ToString(CultureInfo.InvariantCulture));
			}
			else
			{
				builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture));
			}
			return true;
		}

		private static bool IsNumeric(object value)
		{
			if (value is sbyte)
			{
				return true;
			}
			if (value is byte)
			{
				return true;
			}
			if (value is short)
			{
				return true;
			}
			if (value is ushort)
			{
				return true;
			}
			if (value is int)
			{
				return true;
			}
			if (value is uint)
			{
				return true;
			}
			if (value is long)
			{
				return true;
			}
			if (value is ulong)
			{
				return true;
			}
			if (value is float)
			{
				return true;
			}
			if (value is double)
			{
				return true;
			}
			if (value is decimal)
			{
				return true;
			}
			return false;
		}
	}
	[GeneratedCode("simple-json", "1.0.0")]
	public interface IJsonSerializerStrategy
	{
		bool TrySerializeNonPrimitiveObject(object input, out object output);

		object DeserializeObject(object value, Type type);
	}
	[GeneratedCode("simple-json", "1.0.0")]
	public class PocoJsonSerializerStrategy : IJsonSerializerStrategy
	{
		internal IDictionary<Type, ReflectionUtils.ConstructorDelegate> ConstructorCache;

		internal IDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>> GetCache;

		internal IDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>> SetCache;

		internal static readonly Type[] EmptyTypes = new Type[0];

		internal static readonly Type[] ArrayConstructorParameterTypes = new Type[1] { typeof(int) };

		private static readonly string[] Iso8601Format = new string[3] { "yyyy-MM-dd\\THH:mm:ss.FFFFFFF\\Z", "yyyy-MM-dd\\THH:mm:ss\\Z", "yyyy-MM-dd\\THH:mm:ssK" };

		public PocoJsonSerializerStrategy()
		{
			ConstructorCache = new ReflectionUtils.ThreadSafeDictionary<Type, ReflectionUtils.ConstructorDelegate>(ContructorDelegateFactory);
			GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);
			SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);
		}

		protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName)
		{
			return clrPropertyName;
		}

		internal virtual ReflectionUtils.ConstructorDelegate ContructorDelegateFactory(Type key)
		{
			return ReflectionUtils.GetContructor(key, key.IsArray ? ArrayConstructorParameterTypes : EmptyTypes);
		}

		internal virtual IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
		{
			IDictionary<string, ReflectionUtils.GetDelegate> dictionary = new Dictionary<string, ReflectionUtils.GetDelegate>();
			foreach (PropertyInfo property in ReflectionUtils.GetProperties(type))
			{
				if (property.CanRead)
				{
					MethodInfo getterMethodInfo = ReflectionUtils.GetGetterMethodInfo(property);
					if (!getterMethodInfo.IsStatic && getterMethodInfo.IsPublic)
					{
						dictionary[MapClrMemberNameToJsonFieldName(property.Name)] = ReflectionUtils.GetGetMethod(property);
					}
				}
			}
			foreach (FieldInfo field in ReflectionUtils.GetFields(type))
			{
				if (!field.IsStatic && field.IsPublic)
				{
					dictionary[MapClrMemberNameToJsonFieldName(field.Name)] = ReflectionUtils.GetGetMethod(field);
				}
			}
			return dictionary;
		}

		internal virtual IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
		{
			IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> dictionary = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();
			foreach (PropertyInfo property in ReflectionUtils.GetProperties(type))
			{
				if (property.CanWrite)
				{
					MethodInfo setterMethodInfo = ReflectionUtils.GetSetterMethodInfo(property);
					if (!setterMethodInfo.IsStatic && setterMethodInfo.IsPublic)
					{
						dictionary[MapClrMemberNameToJsonFieldName(property.Name)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(property.PropertyType, ReflectionUtils.GetSetMethod(property));
					}
				}
			}
			foreach (FieldInfo field in ReflectionUtils.GetFields(type))
			{
				if (!field.IsInitOnly && !field.IsStatic && field.IsPublic)
				{
					dictionary[MapClrMemberNameToJsonFieldName(field.Name)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(field.FieldType, ReflectionUtils.GetSetMethod(field));
				}
			}
			return dictionary;
		}

		public virtual bool TrySerializeNonPrimitiveObject(object input, out object output)
		{
			if (!TrySerializeKnownTypes(input, out output))
			{
				return TrySerializeUnknownTypes(input, out output);
			}
			return true;
		}

		public virtual object DeserializeObject(object value, Type type)
		{
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			string text = value as string;
			if (type == typeof(Guid) && string.IsNullOrEmpty(text))
			{
				return default(Guid);
			}
			if (value == null)
			{
				return null;
			}
			object obj = null;
			if (text != null)
			{
				if (text.Length != 0)
				{
					if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)))
					{
						return DateTime.ParseExact(text, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
					}
					if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset)))
					{
						return DateTimeOffset.ParseExact(text, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
					}
					if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)))
					{
						return new Guid(text);
					}
					if (type == typeof(Uri))
					{
						if (Uri.IsWellFormedUriString(text, UriKind.RelativeOrAbsolute) && Uri.TryCreate(text, UriKind.RelativeOrAbsolute, out Uri result))
						{
							return result;
						}
						return null;
					}
					if (type == typeof(string))
					{
						return text;
					}
					return Convert.ChangeType(text, type, CultureInfo.InvariantCulture);
				}
				obj = ((type == typeof(Guid)) ? ((object)default(Guid)) : ((!ReflectionUtils.IsNullableType(type) || !(Nullable.GetUnderlyingType(type) == typeof(Guid))) ? text : null));
				if (!ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))
				{
					return text;
				}
			}
			else if (value is bool)
			{
				return value;
			}
			bool flag = value is long;
			bool flag2 = value is double;
			if ((flag && type == typeof(long)) || (flag2 && type == typeof(double)))
			{
				return value;
			}
			if ((flag2 && type != typeof(double)) || (flag && type != typeof(long)))
			{
				obj = ((type == typeof(int) || type == typeof(long) || type == typeof(double) || type == typeof(float) || type == typeof(bool) || type == typeof(decimal) || type == typeof(byte) || type == typeof(short)) ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture) : value);
				if (ReflectionUtils.IsNullableType(type))
				{
					return ReflectionUtils.ToNullableType(obj, type);
				}
				return obj;
			}
			if (value is IDictionary<string, object> dictionary)
			{
				IDictionary<string, object> dictionary2 = dictionary;
				if (ReflectionUtils.IsTypeDictionary(type))
				{
					Type[] genericTypeArguments = ReflectionUtils.GetGenericTypeArguments(type);
					Type type2 = genericTypeArguments[0];
					Type type3 = genericTypeArguments[1];
					Type key = typeof(Dictionary<, >).MakeGenericType(type2, type3);
					IDictionary dictionary3 = (IDictionary)ConstructorCache[key]();
					foreach (KeyValuePair<string, object> item in dictionary2)
					{
						dictionary3.Add(item.Key, DeserializeObject(item.Value, type3));
					}
					obj = dictionary3;
				}
				else if (type == typeof(object))
				{
					obj = value;
				}
				else
				{
					obj = ConstructorCache[type]();
					foreach (KeyValuePair<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> item2 in SetCache[type])
					{
						if (dictionary2.TryGetValue(item2.Key, out var value2))
						{
							value2 = DeserializeObject(value2, item2.Value.Key);
							item2.Value.Value(obj, value2);
						}
					}
				}
			}
			else if (value is IList<object> list)
			{
				IList<object> list2 = list;
				IList list3 = null;
				if (type.IsArray)
				{
					list3 = (IList)ConstructorCache[type](list2.Count);
					int num = 0;
					foreach (object item3 in list2)
					{
						list3[num++] = DeserializeObject(item3, type.GetElementType());
					}
				}
				else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || ReflectionUtils.IsAssignableFrom(typeof(IList), type))
				{
					Type genericListElementType = ReflectionUtils.GetGenericListElementType(type);
					list3 = (IList)(ConstructorCache[type] ?? ConstructorCache[typeof(List<>).MakeGenericType(genericListElementType)])(list2.Count);
					foreach (object item4 in list2)
					{
						list3.Add(DeserializeObject(item4, genericListElementType));
					}
				}
				obj = list3;
			}
			return obj;
		}

		protected virtual object SerializeEnum(Enum p)
		{
			return Convert.ToDouble(p, CultureInfo.InvariantCulture);
		}

		protected virtual bool TrySerializeKnownTypes(object input, out object output)
		{
			bool result = true;
			if (input is DateTime)
			{
				output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
			}
			else if (input is DateTimeOffset)
			{
				output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
			}
			else if (input is Guid)
			{
				output = ((Guid)input).ToString("D");
			}
			else if (input is Uri)
			{
				output = input.ToString();
			}
			else if (input is Enum p)
			{
				output = SerializeEnum(p);
			}
			else
			{
				result = false;
				output = null;
			}
			return result;
		}

		protected virtual bool TrySerializeUnknownTypes(object input, out object output)
		{
			if (input == null)
			{
				throw new ArgumentNullException("input");
			}
			output = null;
			Type type = input.GetType();
			if (type.FullName == null)
			{
				return false;
			}
			IDictionary<string, object> dictionary = new JsonObject();
			IDictionary<string, ReflectionUtils.GetDelegate> dictionary2 = GetCache[type];
			foreach (KeyValuePair<string, ReflectionUtils.GetDelegate> item in dictionary2)
			{
				if (item.Value != null)
				{
					dictionary.Add(MapClrMemberNameToJsonFieldName(item.Key), item.Value(input));
				}
			}
			output = dictionary;
			return true;
		}
	}
}
namespace SimpleJson.Reflection
{
	[GeneratedCode("reflection-utils", "1.0.0")]
	internal class ReflectionUtils
	{
		public delegate object GetDelegate(object source);

		public delegate void SetDelegate(object source, object value);

		public delegate object ConstructorDelegate(params object[] args);

		public delegate TValue ThreadSafeDictionaryValueFactory<TKey, TValue>(TKey key);

		private static class Assigner<T>
		{
			public static T Assign(ref T left, T right)
			{
				return left = right;
			}
		}

		public sealed class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
		{
			private readonly object _lock = new object();

			private readonly ThreadSafeDictionaryValueFactory<TKey, TValue> _valueFactory;

			private Dictionary<TKey, TValue> _dictionary;

			public ICollection<TKey> Keys => _dictionary.Keys;

			public ICollection<TValue> Values => _dictionary.Values;

			public TValue this[TKey key]
			{
				get
				{
					return Get(key);
				}
				set
				{
					throw new NotImplementedException();
				}
			}

			public int Count => _dictionary.Count;

			public bool IsReadOnly
			{
				get
				{
					throw new NotImplementedException();
				}
			}

			public ThreadSafeDictionary(ThreadSafeDictionaryValueFactory<TKey, TValue> valueFactory)
			{
				_valueFactory = valueFactory;
			}

			private TValue Get(TKey key)
			{
				if (_dictionary == null)
				{
					return AddValue(key);
				}
				if (!_dictionary.TryGetValue(key, out var value))
				{
					return AddValue(key);
				}
				return value;
			}

			private TValue AddValue(TKey key)
			{
				TValue val = _valueFactory(key);
				lock (_lock)
				{
					if (_dictionary == null)
					{
						_dictionary = new Dictionary<TKey, TValue>();
						_dictionary[key] = val;
					}
					else
					{
						if (_dictionary.TryGetValue(key, out var value))
						{
							return value;
						}
						Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(_dictionary);
						dictionary[key] = val;
						_dictionary = dictionary;
					}
				}
				return val;
			}

			public void Add(TKey key, TValue value)
			{
				throw new NotImplementedException();
			}

			public bool ContainsKey(TKey key)
			{
				return _dictionary.ContainsKey(key);
			}

			public bool Remove(TKey key)
			{
				throw new NotImplementedException();
			}

			public bool TryGetValue(TKey key, out TValue value)
			{
				value = this[key];
				return true;
			}

			public void Add(KeyValuePair<TKey, TValue> item)
			{
				throw new NotImplementedException();
			}

			public void Clear()
			{
				throw new NotImplementedException();
			}

			public bool Contains(KeyValuePair<TKey, TValue> item)
			{
				throw new NotImplementedException();
			}

			public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
			{
				throw new NotImplementedException();
			}

			public bool Remove(KeyValuePair<TKey, TValue> item)
			{
				throw new NotImplementedException();
			}

			public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
			{
				return _dictionary.GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return _dictionary.GetEnumerator();
			}
		}

		private static readonly object[] EmptyObjects = new object[0];

		public static Type GetTypeInfo(Type type)
		{
			return type;
		}

		public static Attribute GetAttribute(MemberInfo info, Type type)
		{
			if (info == null || type == null || !Attribute.IsDefined(info, type))
			{
				return null;
			}
			return Attribute.GetCustomAttribute(info, type);
		}

		public static Type GetGenericListElementType(Type type)
		{
			IEnumerable<Type> interfaces = type.GetInterfaces();
			foreach (Type item in interfaces)
			{
				if (IsTypeGeneric(item) && item.GetGenericTypeDefinition() == typeof(IList<>))
				{
					return GetGenericTypeArguments(item)[0];
				}
			}
			return GetGenericTypeArguments(type)[0];
		}

		public static Attribute GetAttribute(Type objectType, Type attributeType)
		{
			if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType))
			{
				return null;
			}
			return Attribute.GetCustomAttribute(objectType, attributeType);
		}

		public static Type[] GetGenericTypeArguments(Type type)
		{
			return type.GetGenericArguments();
		}

		public static bool IsTypeGeneric(Type type)
		{
			return GetTypeInfo(type).IsGenericType;
		}

		public static bool IsTypeGenericeCollectionInterface(Type type)
		{
			if (!IsTypeGeneric(type))
			{
				return false;
			}
			Type genericTypeDefinition = type.GetGenericTypeDefinition();
			if (!(genericTypeDefinition == typeof(IList<>)) && !(genericTypeDefinition == typeof(ICollection<>)))
			{
				return genericTypeDefinition == typeof(IEnumerable<>);
			}
			return true;
		}

		public static bool IsAssignableFrom(Type type1, Type type2)
		{
			return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2));
		}

		public static bool IsTypeDictionary(Type type)
		{
			if (typeof(IDictionary).IsAssignableFrom(type))
			{
				return true;
			}
			if (!GetTypeInfo(type).IsGenericType)
			{
				return false;
			}
			Type genericTypeDefinition = type.GetGenericTypeDefinition();
			return genericTypeDefinition == typeof(IDictionary<, >);
		}

		public static bool IsNullableType(Type type)
		{
			if (GetTypeInfo(type).IsGenericType)
			{
				return type.GetGenericTypeDefinition() == typeof(Nullable<>);
			}
			return false;
		}

		public static object ToNullableType(object obj, Type nullableType)
		{
			if (obj != null)
			{
				return Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture);
			}
			return null;
		}

		public static bool IsValueType(Type type)
		{
			return GetTypeInfo(type).IsValueType;
		}

		public static IEnumerable<ConstructorInfo> GetConstructors(Type type)
		{
			return type.GetConstructors();
		}

		public static ConstructorInfo GetConstructorInfo(Type type, params Type[] argsType)
		{
			IEnumerable<ConstructorInfo> constructors = GetConstructors(type);
			foreach (ConstructorInfo item in constructors)
			{
				ParameterInfo[] parameters = item.GetParameters();
				if (argsType.Length != parameters.Length)
				{
					continue;
				}
				int num = 0;
				bool flag = true;
				ParameterInfo[] parameters2 = item.GetParameters();
				foreach (ParameterInfo parameterInfo in parameters2)
				{
					if (parameterInfo.ParameterType != argsType[num])
					{
						flag = false;
						break;
					}
				}
				if (flag)
				{
					return item;
				}
			}
			return null;
		}

		public static IEnumerable<PropertyInfo> GetProperties(Type type)
		{
			return type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		}

		public static IEnumerable<FieldInfo> GetFields(Type type)
		{
			return type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		}

		public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo)
		{
			return propertyInfo.GetGetMethod(nonPublic: true);
		}

		public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo)
		{
			return propertyInfo.GetSetMethod(nonPublic: true);
		}

		public static ConstructorDelegate GetContructor(ConstructorInfo constructorInfo)
		{
			return GetConstructorByExpression(constructorInfo);
		}

		public static ConstructorDelegate GetContructor(Type type, params Type[] argsType)
		{
			return GetConstructorByExpression(type, argsType);
		}

		public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo)
		{
			return (object[] args) => constructorInfo.Invoke(args);
		}

		public static ConstructorDelegate GetConstructorByReflection(Type type, params Type[] argsType)
		{
			ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);
			if (!(constructorInfo == null))
			{
				return GetConstructorByReflection(constructorInfo);
			}
			return null;
		}

		public static ConstructorDelegate GetConstructorByExpression(ConstructorInfo constructorInfo)
		{
			ParameterInfo[] parameters = constructorInfo.GetParameters();
			ParameterExpression parameterExpression = Expression.Parameter(typeof(object[]), "args");
			Expression[] array = new Expression[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				Expression index = Expression.Constant(i);
				Type parameterType = parameters[i].ParameterType;
				Expression expression = Expression.ArrayIndex(parameterExpression, index);
				Expression expression2 = Expression.Convert(expression, parameterType);
				array[i] = expression2;
			}
			NewExpression body = Expression.New(constructorInfo, array);
			Expression<Func<object[], object>> expression3 = Expression.Lambda<Func<object[], object>>(body, new ParameterExpression[1] { parameterExpression });
			Func<object[], object> compiledLambda = expression3.Compile();
			return (object[] args) => compiledLambda(args);
		}

		public static ConstructorDelegate GetConstructorByExpression(Type type, params Type[] argsType)
		{
			ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);
			if (!(constructorInfo == null))
			{
				return GetConstructorByExpression(constructorInfo);
			}
			return null;
		}

		public static GetDelegate GetGetMethod(PropertyInfo propertyInfo)
		{
			return GetGetMethodByExpression(propertyInfo);
		}

		public static GetDelegate GetGetMethod(FieldInfo fieldInfo)
		{
			return GetGetMethodByExpression(fieldInfo);
		}

		public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo)
		{
			MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo);
			return (object source) => methodInfo.Invoke(source, EmptyObjects);
		}

		public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo)
		{
			return (object source) => fieldInfo.GetValue(source);
		}

		public static GetDelegate GetGetMethodByExpression(PropertyInfo propertyInfo)
		{
			MethodInfo getterMethodInfo = GetGetterMethodInfo(propertyInfo);
			ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "instance");
			UnaryExpression instance = ((!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(parameterExpression, propertyInfo.DeclaringType) : Expression.Convert(parameterExpression, propertyInfo.DeclaringType));
			Func<object, object> compiled = Expression.Lambda<Func<object, object>>(Expression.TypeAs(Expression.Call(instance, getterMethodInfo), typeof(object)), new ParameterExpression[1] { parameterExpression }).Compile();
			return (object source) => compiled(source);
		}

		public static GetDelegate GetGetMethodByExpression(FieldInfo fieldInfo)
		{
			ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "instance");
			MemberExpression expression = Expression.Field(Expression.Convert(parameterExpression, fieldInfo.DeclaringType), fieldInfo);
			GetDelegate compiled = Expression.Lambda<GetDelegate>(Expression.Convert(expression, typeof(object)), new ParameterExpression[1] { parameterExpression }).Compile();
			return (object source) => compiled(source);
		}

		public static SetDelegate GetSetMethod(PropertyInfo propertyInfo)
		{
			return GetSetMethodByExpression(propertyInfo);
		}

		public static SetDelegate GetSetMethod(FieldInfo fieldInfo)
		{
			return GetSetMethodByExpression(fieldInfo);
		}

		public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo)
		{
			MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo);
			return delegate(object source, object value)
			{
				methodInfo.Invoke(source, new object[1] { value });
			};
		}

		public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo)
		{
			return delegate(object source, object value)
			{
				fieldInfo.SetValue(source, value);
			};
		}

		public static SetDelegate GetSetMethodByExpression(PropertyInfo propertyInfo)
		{
			MethodInfo setterMethodInfo = GetSetterMethodInfo(propertyInfo);
			ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "instance");
			ParameterExpression parameterExpression2 = Expression.Parameter(typeof(object), "value");
			UnaryExpression instance = ((!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(parameterExpression, propertyInfo.DeclaringType) : Expression.Convert(parameterExpression, propertyInfo.DeclaringType));
			UnaryExpression unaryExpression = ((!IsValueType(propertyInfo.PropertyType)) ? Expression.TypeAs(parameterExpression2, propertyInfo.PropertyType) : Expression.Convert(parameterExpression2, propertyInfo.PropertyType));
			Action<object, object> compiled = Expression.Lambda<Action<object, object>>(Expression.Call(instance, setterMethodInfo, unaryExpression), new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile();
			return delegate(object source, object val)
			{
				compiled(source, val);
			};
		}

		public static SetDelegate GetSetMethodByExpression(FieldInfo fieldInfo)
		{
			ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "instance");
			ParameterExpression parameterExpression2 = Expression.Parameter(typeof(object), "value");
			Action<object, object> compiled = Expression.Lambda<Action<object, object>>(Assign(Expression.Field(Expression.Convert(parameterExpression, fieldInfo.DeclaringType), fieldInfo), Expression.Convert(parameterExpression2, fieldInfo.FieldType)), new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile();
			return delegate(object source, object val)
			{
				compiled(source, val);
			};
		}

		public static BinaryExpression Assign(Expression left, Expression right)
		{
			MethodInfo method = typeof(Assigner<>).MakeGenericType(left.Type).GetMethod("Assign");
			return Expression.Add(left, right, method);
		}
	}
}
namespace Jotunn
{
	public static class ArrayExtensions
	{
		public static T[] Populate<T>(this T[] arr, T value)
		{
			for (int i = 0; i < arr.Length; i++)
			{
				arr[i] = value;
			}
			return arr;
		}
	}
	public static class ConfigEntryBaseExtension
	{
		public static bool IsVisible(this ConfigEntryBase configurationEntry)
		{
			ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes();
			ConfigDescription description = configurationEntry.Description;
			configurationManagerAttributes.SetFromAttributes((description != null) ? description.Tags : null);
			return configurationManagerAttributes.Browsable != false;
		}

		public static bool IsSyncable(this ConfigEntryBase configurationEntry)
		{
			if (configurationEntry.Description.Tags.FirstOrDefault((object x) => x is ConfigurationManagerAttributes) is ConfigurationManagerAttributes configurationManagerAttributes)
			{
				return configurationManagerAttributes.IsAdminOnly;
			}
			return false;
		}

		public static string GetBoundButtonName(this ConfigEntryBase configurationEntry)
		{
			if (configurationEntry == null)
			{
				throw new ArgumentNullException("configurationEntry");
			}
			if (configurationEntry.SettingType != typeof(KeyCode) && configurationEntry.SettingType != typeof(KeyboardShortcut) && configurationEntry.SettingType != typeof(InputManager.GamepadButton))
			{
				return null;
			}
			if (!InputManager.ButtonToConfigDict.TryGetValue(configurationEntry, out var value))
			{
				return null;
			}
			return value.Name;
		}

		public static ButtonConfig GetButtonConfig(this ConfigEntryBase configurationEntry)
		{
			if (configurationEntry == null)
			{
				throw new ArgumentNullException("configurationEntry");
			}
			if (configurationEntry.SettingType != typeof(KeyCode) && configurationEntry.SettingType != typeof(KeyboardShortcut) && configurationEntry.SettingType != typeof(InputManager.GamepadButton))
			{
				return null;
			}
			InputManager.ButtonToConfigDict.TryGetValue(configurationEntry, out var value);
			return value;
		}

		internal static object GetLocalValue(this ConfigEntryBase configurationEntry)
		{
			if (SynchronizationManager.Instance.localValues.TryGetValue(configurationEntry, out var value))
			{
				return value;
			}
			return null;
		}

		internal static void SetLocalValue(this ConfigEntryBase configurationEntry, object value)
		{
			SynchronizationManager.Instance.localValues[configurationEntry] = value;
		}

		internal static ConfigurationManagerAttributes GetConfigurationManagerAttributes(this ConfigEntryBase configEntry)
		{
			return (ConfigurationManagerAttributes)configEntry.Description.Tags.FirstOrDefault((object x) => x is ConfigurationManagerAttributes);
		}
	}
	internal static class EventExtensions
	{
		public static void SafeInvoke(this Action events)
		{
			if (events == null)
			{
				return;
			}
			Delegate[] invocationList = events.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				Action action = (Action)invocationList[i];
				try
				{
					action();
				}
				catch (Exception ex)
				{
					Logger.LogWarning($"Exception thrown at event {new StackFrame(1).GetMethod().Name} in {action.Method.DeclaringType.Name}.{action.Method.Name}:\n{ex}");
				}
			}
		}

		public static void SafeInvoke<TArg1>(this Action<TArg1> events, TArg1 arg1)
		{
			if (events == null)
			{
				return;
			}
			Delegate[] invocationList = events.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				Action<TArg1> action = (Action<TArg1>)invocationList[i];
				try
				{
					action(arg1);
				}
				catch (Exception ex)
				{
					Logger.LogWarning($"Exception thrown at event {new StackFrame(1).GetMethod().Name} in {action.Method.DeclaringType.Name}.{action.Method.Name}:\n{ex}");
				}
			}
		}

		public static void SafeInvoke<TArg1, TArg2>(this Action<TArg1, TArg2> events, TArg1 arg1, TArg2 arg2)
		{
			if (events == null)
			{
				return;
			}
			Delegate[] invocationList = events.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				Action<TArg1, TArg2> action = (Action<TArg1, TArg2>)invocationList[i];
				try
				{
					action(arg1, arg2);
				}
				catch (Exception ex)
				{
					Logger.LogWarning($"Exception thrown at event {new StackFrame(1).GetMethod().Name} in {action.Method.DeclaringType.Name}.{action.Method.Name}:\n{ex}");
				}
			}
		}

		public static void SafeInvoke<TEventArg>(this EventHandler<TEventArg> events, object sender, TEventArg arg1)
		{
			if (events == null)
			{
				return;
			}
			Delegate[] invocationList = events.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				EventHandler<TEventArg> eventHandler = (EventHandler<TEventArg>)invocationList[i];
				try
				{
					eventHandler(sender, arg1);
				}
				catch (Exception ex)
				{
					Logger.LogWarning($"Exception thrown at event {new StackFrame(1).GetMethod().Name} in {eventHandler.Method.DeclaringType.Name}.{eventHandler.Method.Name}:\n{ex}");
				}
			}
		}
	}
	public static class ExposedGameObjectExtension
	{
		public static GameObject OrNull(this GameObject @this)
		{
			if (!Object.op_Implicit((Object)(object)@this))
			{
				return null;
			}
			return @this;
		}

		public static T OrNull<T>(this T @this) where T : Object
		{
			if (!Object.op_Implicit((Object)(object)@this))
			{
				return default(T);
			}
			return @this;
		}

		public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
		{
			return gameObject.GetComponent<T>() ?? gameObject.AddComponent<T>();
		}

		public static Component AddComponentCopy<T>(this GameObject gameObject, T duplicate) where T : Component
		{
			Component val = gameObject.AddComponent(((object)duplicate).GetType());
			PropertyInfo[] properties = ((object)duplicate).GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (!(propertyInfo.Name == "rayTracingMode") && propertyInfo.CanWrite && propertyInfo.GetMethod != null)
				{
					propertyInfo.SetValue(val, propertyInfo.GetValue(duplicate));
				}
			}
			FieldInfo[] fields = ((object)duplicate).GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (!(fieldInfo.Name == "rayTracingMode"))
				{
					fieldInfo.SetValue(val, fieldInfo.GetValue(duplicate));
				}
			}
			return val;
		}
	}
	internal static class GameObjectGUIExtension
	{
		internal static GameObject SetToTextHeight(this GameObject go)
		{
			go.GetComponent<RectTransform>().SetSizeWithCurrentAnchors((Axis)1, go.GetComponentInChildren<Text>().preferredHeight + 3f);
			return go;
		}

		internal static GameObject SetUpperLeft(this GameObject go)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(0f, 1f);
			component.anchorMin = new Vector2(0f, 1f);
			component.pivot = new Vector2(0f, 1f);
			component.anchoredPosition = new Vector2(0f, 0f);
			return go;
		}

		internal static GameObject SetMiddleLeft(this GameObject go)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(0f, 0.5f);
			component.anchorMin = new Vector2(0f, 0.5f);
			component.pivot = new Vector2(0f, 0.5f);
			component.anchoredPosition = new Vector2(0f, 0f);
			return go;
		}

		internal static GameObject SetBottomLeft(this GameObject go)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(0f, 0f);
			component.anchorMin = new Vector2(0f, 0f);
			component.pivot = new Vector2(0f, 0f);
			component.anchoredPosition = new Vector2(0f, 0f);
			return go;
		}

		internal static GameObject SetUpperRight(this GameObject go)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(1f, 1f);
			component.anchorMin = new Vector2(1f, 1f);
			component.pivot = new Vector2(1f, 1f);
			component.anchoredPosition = new Vector2(0f, 0f);
			return go;
		}

		internal static GameObject SetMiddleRight(this GameObject go)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(1f, 0.5f);
			component.anchorMin = new Vector2(1f, 0.5f);
			component.pivot = new Vector2(1f, 0.5f);
			component.anchoredPosition = new Vector2(0f, 0f);
			return go;
		}

		internal static GameObject SetBottomRight(this GameObject go)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(1f, 0f);
			component.anchorMin = new Vector2(1f, 0f);
			component.pivot = new Vector2(1f, 0f);
			component.anchoredPosition = new Vector2(0f, 0f);
			return go;
		}

		internal static GameObject SetUpperCenter(this GameObject go)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(0.5f, 1f);
			component.anchorMin = new Vector2(0.5f, 1f);
			component.pivot = new Vector2(0.5f, 1f);
			component.anchoredPosition = new Vector2(0f, 0f);
			return go;
		}

		internal static GameObject SetMiddleCenter(this GameObject go)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(0.5f, 0.5f);
			component.anchorMin = new Vector2(0.5f, 0.5f);
			component.pivot = new Vector2(0.5f, 0.5f);
			component.anchoredPosition = new Vector2(0f, 0f);
			return go;
		}

		internal static GameObject SetBottomCenter(this GameObject go)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			component.anchorMax = new Vector2(0.5f, 0f);
			component.anchorMin = new Vector2(0.5f, 0f);
			component.pivot = new Vector2(0.5f, 0f);
			component.anchoredPosition = new Vector2(0f, 0f);
			return go;
		}

		internal static GameObject SetSize(this GameObject go, float width, float height)
		{
			RectTransform component = go.GetComponent<RectTransform>();
			component.SetSizeWithCurrentAnchors((Axis)0, width);
			component.SetSizeWithCurrentAnchors((Axis)1, height);
			return go;
		}

		internal static GameObject SetWidth(this GameObject go, float width)
		{
			RectTransform component = go.GetComponent<RectTransform>();
			component.SetSizeWithCurrentAnchors((Axis)0, width);
			return go;
		}

		internal static GameObject SetHeight(this GameObject go, float height)
		{
			RectTransform component = go.GetComponent<RectTransform>();
			component.SetSizeWithCurrentAnchors((Axis)1, height);
			return go;
		}

		internal static float GetWidth(this GameObject go)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			Rect rect = component.rect;
			return ((Rect)(ref rect)).width;
		}

		internal static float GetHeight(this GameObject go)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = go.GetComponent<RectTransform>();
			Rect rect = component.rect;
			return ((Rect)(ref rect)).height;
		}

		internal static float GetTextHeight(this GameObject go)
		{
			return go.GetComponent<Text>().preferredHeight;
		}

		internal static GameObject SetText(this GameObject go, string text)
		{
			go.GetComponent<Text>().text = text;
			return go;
		}
	}
	public static class GameObjectExtension
	{
		public static bool IsValid(this GameObject self)
		{
			try
			{
				string text = ((Object)self).name;
				if (text.IndexOf('(') > 0)
				{
					text = text.Substring(((Object)self).name.IndexOf('(')).Trim();
				}
				if (string.IsNullOrEmpty(text))
				{
					throw new Exception("GameObject must have a name !");
				}
				if (Object.op_Implicit((Object)(object)self.GetComponent<ZNetView>()) && ((Object)self).name.IndexOfAny(new char[2] { ')', ' ' }) > 0)
				{
					throw new Exception("GameObject name must not contain parenthesis or spaces!");
				}
				return true;
			}
			catch (Exception data)
			{
				Logger.LogError(data);
				return false;
			}
		}
	}
	public static class ItemDropExtension
	{
		public static string TokenName(this ItemDrop self)
		{
			return self.m_itemData.m_shared.m_name;
		}
	}
	public static class ItemDataExtension
	{
		public static string TokenName(this ItemData self)
		{
			return self.m_shared.m_name;
		}
	}
	public static class RecipeExtension
	{
		public static bool IsValid(this Recipe self)
		{
			try
			{
				string text = ((Object)self).name;
				if (text.IndexOf('(') > 0)
				{
					text = text.Substring(((Object)self).name.IndexOf('(')).Trim();
				}
				if (string.IsNullOrEmpty(text))
				{
					throw new Exception("Recipe must have a name !");
				}
				return true;
			}
			catch (Exception data)
			{
				Logger.LogError(data);
				return false;
			}
		}
	}
	public static class PieceExtension
	{
		public static string TokenName(this Piece self)
		{
			return self.m_name;
		}
	}
	public static class StatusEffectExtension
	{
		public static string TokenName(this StatusEffect self)
		{
			return self.m_name;
		}

		public static bool IsValid(this StatusEffect self)
		{
			try
			{
				string text = ((Object)self).name;
				if (text.IndexOf('(') > 0)
				{
					text = text.Substring(((Object)self).name.IndexOf('(')).Trim();
				}
				if (string.IsNullOrEmpty(text))
				{
					throw new Exception("StatusEffect must have a name !");
				}
				return true;
			}
			catch (Exception data)
			{
				Logger.LogError(data);
				return false;
			}
		}
	}
	public static class PrefabExtension
	{
		public static void FixReferences(this object objectToFix)
		{
			MockManager.FixReferences(objectToFix, 0);
		}

		public static void FixReferences(this GameObject gameObject)
		{
			gameObject.FixReferences(recursive: false);
		}

		public static void FixReferences(this GameObject gameObject, bool recursive)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			Component[] components = gameObject.GetComponents<Component>();
			foreach (Component val in components)
			{
				if (!(val is Transform))
				{
					MockManager.FixReferences(val, 0);
				}
			}
			if (!recursive)
			{
				return;
			}
			foreach (Transform item in gameObject.transform)
			{
				Transform val2 = item;
				((Component)val2).gameObject.FixReferences(recursive: true);
			}
		}

		public static void CloneFields(this GameObject gameObject, GameObject objectToClone)
		{
			Dictionary<FieldInfo, object> dictionary = new Dictionary<FieldInfo, object>();
			Component[] componentsInChildren = objectToClone.GetComponentsInChildren<Component>();
			Component[] array = componentsInChildren;
			foreach (Component val in array)
			{
				FieldInfo[] fields = ((object)val).GetType().GetFields((BindingFlags)(-1));
				foreach (FieldInfo fieldInfo in fields)
				{
					if (!fieldInfo.IsLiteral && !fieldInfo.IsInitOnly)
					{
						dictionary.Add(fieldInfo, fieldInfo.GetValue(val));
					}
				}
				if (!Object.op_Implicit((Object)(object)gameObject.GetComponent(((object)val).GetType())))
				{
					gameObject.AddComponent(((object)val).GetType());
				}
			}
			Component[] componentsInChildren2 = gameObject.GetComponentsInChildren<Component>();
			Component[] array2 = componentsInChildren2;
			foreach (Component val2 in array2)
			{
				FieldInfo[] fields2 = ((object)val2).GetType().GetFields((BindingFlags)(-1));
				foreach (FieldInfo fieldInfo2 in fields2)
				{
					if (dictionary.TryGetValue(fieldInfo2, out var value))
					{
						fieldInfo2.SetValue(val2, value);
					}
				}
			}
		}
	}
	internal static class ObjectExtension
	{
		public static string GetObjectString(this object obj)
		{
			if (obj == null)
			{
				return "null";
			}
			string text = $"{obj}";
			Type type = obj.GetType();
			IEnumerable<FieldInfo> enumerable = from f in type.GetFields()
				where f.IsPublic
				select f;
			foreach (FieldInfo item in enumerable)
			{
				object value = item.GetValue(obj);
				string text2 = ((value == null) ? "null" : value.ToString());
				text = text + "\n " + item.Name + ": " + text2;
			}
			PropertyInfo[] properties = type.GetProperties();
			PropertyInfo[] array = properties;
			foreach (PropertyInfo propertyInfo in array)
			{
				object value2 = propertyInfo.GetValue(obj, null);
				string text3 = ((value2 == null) ? "null" : value2.ToString());
				text = text + "\n " + propertyInfo.Name + ": " + text3;
			}
			return text;
		}
	}
	public static class RectTransformExtensions
	{
		public static bool Overlaps(this RectTransform a, RectTransform b)
		{
			//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_000a: Unknown result type (might be due to invalid IL or missing references)
			Rect val = a.WorldRect();
			return ((Rect)(ref val)).Overlaps(b.WorldRect());
		}

		public static bool Overlaps(this RectTransform a, RectTransform b, bool allowInverse)
		{
			//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_000a: Unknown result type (might be due to invalid IL or missing references)
			Rect val = a.WorldRect();
			return ((Rect)(ref val)).Overlaps(b.WorldRect(), allowInverse);
		}

		public static Rect WorldRect(this RectTransform rectTransform)
		{
			//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_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			Vector2 sizeDelta = rectTransform.sizeDelta;
			float num = sizeDelta.x * ((Transform)rectTransform).lossyScale.x;
			float num2 = sizeDelta.y * ((Transform)rectTransform).lossyScale.y;
			Vector3 position = ((Transform)rectTransform).position;
			return new Rect(position.x - num / 2f, position.y - num2 / 2f, num, num2);
		}
	}
	public static class ZNetExtension
	{
		public enum ZNetInstanceType
		{
			Local,
			Client,
			Server
		}

		public static bool IsLocalInstance(this ZNet znet)
		{
			if (znet.IsServer())
			{
				return !znet.IsDedicated();
			}
			return false;
		}

		public static bool IsClientInstance(this ZNet znet)
		{
			if (!znet.IsServer())
			{
				return !znet.IsDedicated();
			}
			return false;
		}

		public static bool IsServerInstance(this ZNet znet)
		{
			if (znet.IsServer())
			{
				return znet.IsDedicated();
			}
			return false;
		}

		public static ZNetInstanceType GetInstanceType(this ZNet znet)
		{
			if (znet.IsLocalInstance())
			{
				return ZNetInstanceType.Local;
			}
			if (znet.IsClientInstance())
			{
				return ZNetInstanceType.Client;
			}
			return ZNetInstanceType.Server;
		}

		public static bool IsAdmin(this ZNet znet, long uid)
		{
			if (!Object.op_Implicit((Object)(object)znet))
			{
				Logger.LogWarning("IsAdmin check failed: ZNet is null");
				return false;
			}
			if (znet.m_adminList == null)
			{
				Logger.LogWarning("IsAdmin check failed: admin list is only available on the server");
				return false;
			}
			ZNetPeer peer = znet.GetPeer(uid);
			if (peer == null)
			{
				Logger.LogWarning($"IsAdmin check failed: peer not found with id {uid}");
				return false;
			}
			string hostName = peer.m_socket.GetHostName();
			if (!string.IsNullOrEmpty(hostName))
			{
				return znet.ListContainsId(znet.m_adminList, hostName);
			}
			return false;
		}
	}
	internal interface IManager
	{
		void Init();
	}
	public class Logger
	{
		public static bool ShowDate;

		private static Logger instance;

		private readonly Dictionary<string, ManualLogSource> logger = new Dictionary<string, ManualLogSource>();

		internal static void Init()
		{
			if (instance == null)
			{
				instance = new Logger();
			}
		}

		internal static void Destroy()
		{
			LogDebug("Destroying Logger");
			foreach (KeyValuePair<string, ManualLogSource> item in instance.logger)
			{
				Logger.Sources.Remove((ILogSource)(object)item.Value);
			}
			instance.logger.Clear();
		}

		private ManualLogSource GetLogger()
		{
			Type declaringType = new StackFrame(3).GetMethod().DeclaringType;
			if (!logger.TryGetValue(declaringType.FullName, out var value))
			{
				value = Logger.CreateLogSource(declaringType.FullName);
				logger.Add(declaringType.FullName, value);
			}
			return value;
		}

		private static void Log(LogLevel level, BepInPlugin sourceMod, object data)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			string text = string.Empty;
			if (ShowDate)
			{
				text = text + "[" + DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo) + "] ";
			}
			if (sourceMod != null)
			{
				text = text + "[" + sourceMod.Name + "] ";
			}
			instance.GetLogger().Log(level, (object)$"{text}{data}");
		}

		public static void LogFatal(object data)
		{
			Log((LogLevel)1, null, data);
		}

		public static void LogFatal(BepInPlugin sourceMod, object data)
		{
			Log((LogLevel)1, sourceMod, data);
		}

		public static void LogError(object data)
		{
			Log((LogLevel)2, null, data);
		}

		public static void LogError(BepInPlugin sourceMod, object data)
		{
			Log((LogLevel)2, sourceMod, data);
		}

		public static void LogWarning(object data)
		{
			Log((LogLevel)4, null, data);
		}

		public static void LogWarning(BepInPlugin sourceMod, object data)
		{
			Log((LogLevel)4, sourceMod, data);
		}

		public static void LogMessage(object data)
		{
			Log((LogLevel)8, null, data);
		}

		public static void LogMessage(BepInPlugin sourceMod, object data)
		{
			Log((LogLevel)8, sourceMod, data);
		}

		public static void LogInfo(object data)
		{
			Log((LogLevel)16, null, data);
		}

		public static void LogInfo(BepInPlugin sourceMod, object data)
		{
			Log((LogLevel)16, sourceMod, data);
		}

		public static void LogDebug(object data)
		{
			Log((LogLevel)32, null, data);
		}

		public static void LogDebug(BepInPlugin sourceMod, object data)
		{
			Log((LogLevel)32, sourceMod, data);
		}
	}
	[BepInPlugin("com.jotunn.jotunn", "Jotunn", "2.12.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(CompatibilityLevel.VersionCheckOnly, VersionStrictness.Minor)]
	public class Main : BaseUnityPlugin
	{
		public const string Version = "2.12.7";

		public const string ModName = "Jotunn";

		public const string ModGuid = "com.jotunn.jotunn";

		internal static Main Instance;

		internal static Harmony Harmony;

		internal static GameObject RootObject;

		private List<IManager> Managers;

		private void Awake()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			Instance = this;
			Harmony = new Harmony("com.jotunn.jotunn");
			Harmony.PatchAll(typeof(ModCompatibility));
			Logger.Init();
			RootObject = new GameObject("_JotunnRoot");
			Object.DontDestroyOnLoad((Object)(object)RootObject);
			Managers = new List<IManager>
			{
				LocalizationManager.Instance,
				CommandManager.Instance,
				InputManager.Instance,
				SkillManager.Instance,
				PrefabManager.Instance,
				ItemManager.Instance,
				PieceManager.Instance,
				CreatureManager.Instance,
				ZoneManager.Instance,
				MockManager.Instance,
				KitbashManager.Instance,
				GUIManager.Instance,
				KeyHintManager.Instance,
				NetworkManager.Instance,
				SynchronizationManager.Instance,
				RenderManager.Instance,
				MinimapManager.Instance,
				UndoManager.Instance
			};
			foreach (IManager manager in Managers)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Initializing " + manager.GetType().Name));
				manager.Init();
			}
			ModQuery.Init();
			ModCompatibility.Init();
			Game.isModded = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Jötunn v2.12.7 loaded successfully");
		}

		private void Start()
		{
			InitializePatches();
			LocalizationManager.Instance.LoadingAutomaticLocalizations();
		}

		private void OnApplicationQuit()
		{
			AssetBundle.UnloadAllAssetBundles(false);
		}

		[Obsolete]
		private void InitializePatches()
		{
			List<Tuple<MethodInfo, int>> list = new List<Tuple<MethodInfo, int>>();
			HashSet<Assembly> hashSet = new HashSet<Assembly>();
			foreach (BaseUnityPlugin value in BepInExUtils.GetDependentPlugins().Values)
			{
				try
				{
					Assembly assembly = ((object)value).GetType().Assembly;
					if (hashSet.Contains(assembly))
					{
						continue;
					}
					hashSet.Add(assembly);
					Type[] types = assembly.GetTypes();
					foreach (Type type in types)
					{
						try
						{
							foreach (MethodInfo item in from x in type.GetMethods(BindingFlags.Static | BindingFlags.Public)
								where x.GetCustomAttributes(typeof(PatchInitAttribute), inherit: false).Length == 1
								select x)
							{
								PatchInitAttribute patchInitAttribute = item.GetCustomAttributes(typeof(PatchInitAttribute), inherit: false).FirstOrDefault() as PatchInitAttribute;
								list.Add(new Tuple<MethodInfo, int>(item, patchInitAttribute.Priority));
							}
						}
						catch (Exception)
						{
						}
					}
				}
				catch (Exception)
				{
				}
			}
			foreach (Tuple<MethodInfo, int> item2 in list.OrderBy((Tuple<MethodInfo, int> x) => x.Item2))
			{
				Logger.LogDebug("Applying patches in " + item2.Item1.DeclaringType.Name + "." + item2.Item1.Name);
				item2.Item1.Invoke(null, null);
			}
		}
	}
	internal class ClassMember
	{
		private static readonly Dictionary<Type, ClassMember> CachedClassMembers = new Dictionary<Type, ClassMember>();

		public List<MemberBase> Members { get; private set; } = new List<MemberBase>();


		public Type Type { get; private set; }

		private ClassMember(Type type, IEnumerable<FieldInfo> fieldInfos, IEnumerable<PropertyInfo> propertyInfos)
		{
			Type = type;
			foreach (FieldInfo fieldInfo in fieldInfos)
			{
				AddMember(new FieldMember(fieldInfo));
			}
			foreach (PropertyInfo propertyInfo in propertyInfos)
			{
				AddMember(new PropertyMember(propertyInfo));
			}
		}

		private void AddMember(MemberBase member)
		{
			if (member.IsClass && !(member.MemberType == typeof(string)) && (!(member.EnumeratedType != null) || (member.IsEnumeratedClass && !(member.EnumeratedType == typeof(string)))) && !member.HasCustomAttribute<NonSerializedAttribute>())
			{
				Members.Add(member);
			}
		}

		private static T[] GetMembersFromType<T>(Type type, Func<Type, T[]> getMembers)
		{
			T[] array = getMembers(type);
			Type baseType = type.BaseType;
			while (baseType != null)
			{
				T[] second = getMembers(baseType);
				array = array.Union(second).ToArray();
				baseType = baseType.BaseType;
			}
			return array;
		}

		public static ClassMember GetClassMember(Type type)
		{
			if (CachedClassMembers.TryGetValue(type, out var value))
			{
				return value;
			}
			FieldInfo[] membersFromType = GetMembersFromType(type, (Type t) => t.GetFields(~BindingFlags.Static));
			PropertyInfo[] membersFromType2 = GetMembersFromType(type, (Type t) => t.GetProperties(~BindingFlags.Static));
			value = new ClassMember(type, membersFromType, membersFromType2);
			CachedClassMembers[type] = value;
			return value;
		}
	}
	internal class FieldMember : MemberBase
	{
		private readonly FieldInfo fieldInfo;

		public FieldMember(FieldInfo fieldInfo)
		{
			this.fieldInfo = fieldInfo;
			base.MemberType = fieldInfo.FieldType;
			base.IsUnityObject = base.MemberType.IsSameOrSubclass(typeof(Object));
			base.IsClass = base.MemberType.IsClass;
			base.HasGetMethod = true;
			base.EnumeratedType = base.MemberType.GetEnumeratedType();
			base.IsEnumerableOfUnityObjects = base.EnumeratedType?.IsSameOrSubclass(typeof(Object)) ?? false;
			base.IsEnumeratedClass = base.EnumeratedType?.IsClass ?? false;
		}

		public override object GetValue(object obj)
		{
			try
			{
				return fieldInfo.GetValue(obj);
			}
			catch
			{
				return null;
			}
		}

		public override void SetValue(object obj, object value)
		{
			fieldInfo.SetValue(obj, value);
		}

		public override bool HasCustomAttribute<T>()
		{
			return fieldInfo.GetCustomAttribute<T>() != null;
		}
	}
	internal abstract class MemberBase
	{
		public bool HasGetMethod { get; protected set; }

		public Type MemberType { get; protected set; }

		public Type EnumeratedType { get; protected set; }

		public bool IsUnityObject { get; protected set; }

		public bool IsClass { get; protected set; }

		public bool IsEnumerableOfUnityObjects { get; protected set; }

		public bool IsEnumeratedClass { get; protected set; }

		public abstract object GetValue(object obj);

		public abstract void SetValue(object obj, object value);

		public abstract bool HasCustomAttribute<T>() where T : Attribute;
	}
	internal class PropertyMember : MemberBase
	{
		private readonly PropertyInfo propertyInfo;

		public PropertyMember(PropertyInfo propertyInfo)
		{
			this.propertyInfo = propertyInfo;
			base.MemberType = propertyInfo.PropertyType;
			base.IsUnityObject = base.MemberType.IsSameOrSubclass(typeof(Object));
			base.IsClass = base.MemberType.IsClass;
			base.HasGetMethod = propertyInfo.GetIndexParameters().Length == 0 && propertyInfo.GetMethod != null;
			base.EnumeratedType = base.MemberType.GetEnumeratedType();
			base.IsEnumerableOfUnityObjects = base.EnumeratedType?.IsSameOrSubclass(typeof(Object)) ?? false;
			base.IsEnumeratedClass = base.EnumeratedType?.IsClass ?? false;
		}

		public override object GetValue(object obj)
		{
			try
			{
				return propertyInfo.GetValue(obj);
			}
			catch
			{
				return null;
			}
		}

		public override void SetValue(object obj, object value)
		{
			propertyInfo.SetValue(obj, value);
		}

		public override bool HasCustomAttribute<T>()
		{
			return propertyInfo.GetCustomAttribute<T>() != null;
		}
	}
}
namespace Jotunn.Utils
{
	public static class AssetUtils
	{
		public const char AssetBundlePathSeparator = '$';

		public static Texture2D LoadTexture(string texturePath, bool relativePath = true)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			string text = texturePath;
			if (relativePath)
			{
				text = Path.Combine(Paths.PluginPath, texturePath);
			}
			if (!File.Exists(text))
			{
				return null;
			}
			if (!text.EndsWith(".png") && !text.EndsWith(".jpg"))
			{
				throw new Exception("LoadTexture can only load png or jpg textures");
			}
			byte[] array = File.ReadAllBytes(text);
			Texture2D val = new Texture2D(2, 2);
			ImageConversion.LoadImage(val, array);
			return val;
		}

		public static Sprite LoadSpriteFromFile(string spritePath)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return LoadSpriteFromFile(spritePath, Vector2.zero);
		}

		public static Sprite LoadSpriteFromFile(string spritePath, Vector2 pivot)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = LoadTexture(spritePath);
			if ((Object)(object)val != (Object)null)
			{
				return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), pivot);
			}
			return null;
		}

		public static Mesh LoadMesh(string meshPath)
		{
			string text = Path.Combine(Paths.PluginPath, meshPath);
			if (!File.Exists(text))
			{
				return null;
			}
			return ObjImporter.ImportFile(text);
		}

		public static AssetBundle LoadAssetBundle(string bundlePath)
		{
			string text = Path.Combine(Paths.PluginPath, bundlePath);
			if (!File.Exists(text))
			{
				return null;
			}
			return AssetBundle.LoadFromFile(text);
		}

		public static AssetBundle LoadAssetBundleFromResources(string bundleName, Assembly resourceAssembly)
		{
			if (resourceAssembly == null)
			{
				throw new ArgumentNullException("Parameter resourceAssembly can not be null.");
			}
			string text = null;
			try
			{
				text = resourceAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith(bundleName));
			}
			catch (Exception)
			{
			}
			if (text == null)
			{
				Logger.LogError("AssetBundle " + bundleName + " not found in assembly manifest");
				return null;
			}
			using Stream stream = resourceAssembly.GetManifestResourceStream(text);
			return AssetBundle.LoadFromStream(stream);
		}

		public static AssetBundle LoadAssetBundleFromResources(string bundleName)
		{
			return LoadAssetBundleFromResources(bundleName, ReflectionHelper.GetCallingAssembly());
		}

		public static string LoadTextFromResources(string fileName, Assembly resourceAssembly)
		{
			if (resourceAssembly == null)
			{
				throw new ArgumentNullException("Parameter resourceAssembly can not be null.");
			}
			string text = null;
			try
			{
				text = resourceAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith(fileName));
			}
			catch (Exception)
			{
			}
			if (text == null)
			{
				Logger.LogError("File " + fileName + " not found in assembly manifest");
				return null;
			}
			using Stream stream = resourceAssembly.GetManifestResourceStream(text);
			using StreamReader streamReader = new StreamReader(stream);
			return streamReader.ReadToEnd();
		}

		public static string LoadText(string path)
		{
			string text = Path.Combine(Paths.PluginPath, path);
			if (!File.Exists(text))
			{
				Logger.LogError("Error, failed to load contents from non-existant path: $" + text);
				return null;
			}
			return File.ReadAllText(text);
		}

		public static Sprite LoadSprite(string assetPath)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			string text = Path.Combine(Paths.PluginPath, assetPath);
			if (!File.Exists(text))
			{
				return null;
			}
			if (text.Contains('$'.ToString()))
			{
				string[] array = text.Split(new char[1] { '$' });
				string text2 = array[0];
				string text3 = array[1];
				AssetBundle val = AssetBundle.LoadFromFile(text2);
				Sprite result = val.LoadAsset<Sprite>(text3);
				val.Unload(false);
				return result;
			}
			Texture2D val2 = LoadTexture(text, relativePath: false);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			return Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), Vector2.zero);
		}
	}
	public static class BepInExUtils
	{
		private static BaseUnityPlugin[] Plugins;

		private static Dictionary<PluginInfo, string> PluginInfoTypeNameCache { get; } = new Dictionary<PluginInfo, string>();


		private static Dictionary<Assembly, PluginInfo> AssemblyToPluginInfoCache { get; } = new Dictionary<Assembly, PluginInfo>();


		private static Dictionary<Type, PluginInfo> TypeToPluginInfoCache { get; } = new Dictionary<Type, PluginInfo>();


		private static BaseUnityPlugin[] CacheDependentPlugins()
		{
			List<BaseUnityPlugin> list = new List<BaseUnityPlugin>();
			foreach (BaseUnityPlugin loadedPlugin in GetLoadedPlugins())
			{
				if (loadedPlugin.Info == null)
				{
					Logger.LogWarning("Plugin without Info found: " + ((object)loadedPlugin).GetType().Assembly.FullName);
					continue;
				}
				if (loadedPlugin.Info.Metadata == null)
				{
					Logger.LogWarning("Plugin without Metadata found: " + ((object)loadedPlugin).GetType().Assembly.FullName);
					continue;
				}
				if (loadedPlugin.Info.Metadata.GUID == "com.jotunn.jotunn")
				{
					list.Add(loadedPlugin);
					continue;
				}
				foreach (BepInDependency item in ((object)loadedPlugin).GetType().GetCustomAttributes(typeof(BepInDependency), inherit: false).Cast<BepInDependency>())
				{
					if (item.DependencyGUID == "com.jotunn.jotunn")
					{
						list.Add(loadedPlugin);
					}
				}
			}
			return list.ToArray();
		}

		public static Dictionary<string, BaseUnityPlugin> GetDependentPlugins(bool includeJotunn = false)
		{
			if (Plugins == null)
			{
				if (!ReflectionHelper.GetPrivateField<bool>(typeof(Chainloader), "_loaded"))
				{
					return new Dictionary<string, BaseUnityPlugin>();
				}
				Plugins = CacheDependentPlugins();
			}
			return Plugins.Where((BaseUnityPlugin plugin) => includeJotunn || plugin.Info.Metadata.GUID != "com.jotunn.jotunn").ToDictionary((BaseUnityPlugin plugin) => plugin.Info.Metadata.GUID);
		}

		public static Dictionary<string, BaseUnityPlugin> GetPlugins(bool includeJotunn = false)
		{
			return (from plugin in GetLoadedPlugins()
				where includeJotunn || plugin.Info.Metadata.GUID != "com.jotunn.jotunn"
				select plugin).ToDictionary((BaseUnityPlugin plugin) => plugin.Info.Metadata.GUID);
		}

		public static PluginInfo GetPluginInfoFromType(Type type)
		{
			if (TypeToPluginInfoCache.TryGetValue(type, out var value))
			{
				return value;
			}
			foreach (PluginInfo value2 in Chainloader.

BepInEx/plugins/Vapok-AdventureBackpacks/AdventureBackpacks.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
using AdventureBackpacks.Assets;
using AdventureBackpacks.Assets.Effects;
using AdventureBackpacks.Assets.Factories;
using AdventureBackpacks.Assets.Items;
using AdventureBackpacks.Assets.Items.BackpackItems;
using AdventureBackpacks.Components;
using AdventureBackpacks.Configuration;
using AdventureBackpacks.Extensions;
using AdventureBackpacks.Features;
using AdventureBackpacks.Patches;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using ServerSync;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Vapok.Common.Abstractions;
using Vapok.Common.Managers;
using Vapok.Common.Managers.Configuration;
using Vapok.Common.Managers.Creature;
using Vapok.Common.Managers.LocalizationManager;
using Vapok.Common.Managers.Location;
using Vapok.Common.Managers.PieceManager;
using Vapok.Common.Managers.Skill;
using Vapok.Common.Managers.StatusEffects;
using Vapok.Common.Shared;
using Vapok.Common.Tools;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: AssemblyFileVersion("1.6.26.0")]
[assembly: Guid("997CB563-FCC7-44B7-8F71-069747D27CC5")]
[assembly: ComVisible(false)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyProduct("AdventureBackpacks")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("A Valheim Mod for adding progression multiple backpacks as an item/utility gear addition.")]
[assembly: AssemblyTitle("AdventureBackpacks")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("Vapok Gaming")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.6.26.0")]
[module: <ecee8021-3566-41d3-89ad-8ef545ee82ae>RefSafetyRules(11)]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[<0becfd5f-b05d-4a28-a284-9d8980089fe2>Embedded]
	internal sealed class <0becfd5f-b05d-4a28-a284-9d8980089fe2>EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[<0becfd5f-b05d-4a28-a284-9d8980089fe2>Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class <ecee8021-3566-41d3-89ad-8ef545ee82ae>RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public <ecee8021-3566-41d3-89ad-8ef545ee82ae>RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AdventureBackpacks
{
	[BepInPlugin("vapok.mods.adventurebackpacks", "Adventure Backpacks", "1.6.26")]
	[BepInIncompatibility("JotunnBackpacks")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class AdventureBackpacks : BaseUnityPlugin, IPluginInfo
	{
		public class Waiting
		{
			public event EventHandler StatusChanged;

			public void ValheimIsAwake(bool awakeFlag)
			{
				if (awakeFlag)
				{
					this.StatusChanged?.Invoke(this, EventArgs.Empty);
				}
			}
		}

		private const string _pluginId = "vapok.mods.adventurebackpacks";

		private const string _displayName = "Adventure Backpacks";

		private const string _version = "1.6.26";

		public static bool ValheimAwake;

		public static bool PerformYardSale;

		public static bool QuickDropping;

		public static bool BypassMoveProtection;

		public static Waiting Waiter;

		private static AdventureBackpacks _instance;

		private static ConfigSyncBase _config;

		private static ILogIt _log;

		private Harmony _harmony;

		public string PluginId => "vapok.mods.adventurebackpacks";

		public string DisplayName => "Adventure Backpacks";

		public string Version => "1.6.26";

		public BaseUnityPlugin Instance => (BaseUnityPlugin)(object)_instance;

		public static ILogIt Log => _log;

		public static ConfigSyncBase ActiveConfig => _config;

		[UsedImplicitly]
		private void Awake()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			_instance = this;
			Waiter = new Waiting();
			Initializer.LoadManagers(enableCreatureManager: false, enableItemManager: true, enableLocationManager: true, enableMaterialReplacer: true, enablePieceManager: false, enableSkillManager: false, enableEffectManager: true, enableLocalizationManager: true);
			_config = new ConfigRegistry(_instance);
			LogManager.Init(PluginId, out _log);
			ItemManager.PrefabManager.Initalized = true;
			Localizer.Waiter.StatusChanged += InitializeBackpacks;
			QuickTransfer.FeatureInitialized = true;
			_harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
		}

		private void Update()
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer) || !Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return;
			}
			if (PerformYardSale)
			{
				BackpackComponent equippedBackpack = Player.m_localPlayer.GetEquippedBackpack();
				if (equippedBackpack != null)
				{
					Backpacks.PerformYardSale(Player.m_localPlayer, equippedBackpack.Item);
				}
			}
			if (ZInput.GetButton("Forward") || ZInput.GetButton("Backward") || ZInput.GetButton("Left") || ZInput.GetButton("Right"))
			{
				KeyboardShortcut value = ConfigRegistry.HotKeyDrop.Value;
				if (ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey) && ConfigRegistry.OutwardMode.Value)
				{
					Player.m_localPlayer.QuickDropBackpack();
				}
			}
			InventoryPatches.ProcessItemsAddedQueue();
		}

		public void InitializeBackpacks(object send, EventArgs args)
		{
			if (!ValheimAwake)
			{
				new EffectsFactory(_log, _config).RegisterEffects();
				new BackpackFactory(_log, _config).CreateAssets();
				Backpacks.LoadBackpackTypes(BackpackFactory.BackpackTypes());
				BoneReorder.ApplyOnEquipmentChanged(((BaseUnityPlugin)this).Info.Metadata.GUID);
				ConfigRegistry.Waiter.ConfigurationComplete(configDone: true);
				ValheimAwake = true;
			}
		}

		private void OnDestroy()
		{
			_instance = null;
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
}
namespace AdventureBackpacks.Patches
{
	public static class ArmorStandPatches
	{
		[HarmonyPatch(typeof(ArmorStand), "UpdateAttach")]
		private static class ArmorStandUpdateAttachPatch
		{
			private static void Prefix(ArmorStand __instance)
			{
				AdventureBackpacks.BypassMoveProtection = true;
			}

			private static void Postfix(ArmorStand __instance)
			{
				AdventureBackpacks.BypassMoveProtection = false;
			}
		}
	}
	public static class ContainerPatches
	{
		[HarmonyPatch(typeof(Container), "TakeAll")]
		private static class ContainerTakeAllPatch
		{
			private static void Prefix(ArmorStand __instance)
			{
				AdventureBackpacks.BypassMoveProtection = true;
			}

			private static void Postfix(ArmorStand __instance)
			{
				AdventureBackpacks.BypassMoveProtection = false;
			}
		}

		[HarmonyPatch(typeof(Container), "Interact")]
		private static class ContainerInteractPatch
		{
			private static bool Prefix(Container __instance, ref bool __result)
			{
				if (((Object)__instance).name.Equals("Player(Clone)"))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Container), "Awake")]
		private static class ContainerAwakePatch
		{
			private static void UpdateZDO(Container instance, ZNetView nview)
			{
				if (((Object)instance).name.Equals("Player(Clone)"))
				{
					nview.GetZDO().Set(StringExtensionMethods.GetStableHashCode("creator"), 1L);
				}
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator ilGenerator)
			{
				bool patchedSuccess = false;
				List<CodeInstruction> instrs = instructions.ToList();
				int counter = 0;
				MethodInfo invokeRepeatingMethod = AccessTools.DeclaredMethod(typeof(MonoBehaviour), "InvokeRepeating", new Type[3]
				{
					typeof(string),
					typeof(float),
					typeof(float)
				}, (Type[])null);
				FieldInfo nviewField = AccessTools.DeclaredField(typeof(Container), "m_nview");
				int i = 0;
				while (i < instrs.Count)
				{
					if (i > 5 && instrs[i].opcode == OpCodes.Ret && instrs[i - 1].opcode == OpCodes.Call && instrs[i - 1].operand.Equals(invokeRepeatingMethod))
					{
						yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						counter++;
						yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						counter++;
						yield return new CodeInstruction(OpCodes.Ldfld, (object)nviewField);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(ContainerAwakePatch), "UpdateZDO", (Type[])null, (Type[])null)));
						counter++;
						patchedSuccess = true;
					}
					yield return LogMessage(instrs[i]);
					counter++;
					int num = i + 1;
					i = num;
				}
				if (!patchedSuccess)
				{
					AdventureBackpacks.Log.Error("Container.Awake Transpiler Failed To Patch");
					Thread.Sleep(5000);
				}
				CodeInstruction LogMessage(CodeInstruction instruction)
				{
					AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}");
					return instruction;
				}
			}
		}
	}
	public static class DoorPatches
	{
		[HarmonyPatch(typeof(Door), "HaveKey")]
		private static class HaveDoorKeyPatch
		{
			private static void Postfix(Door __instance, ref bool __result)
			{
				if (!((Object)(object)__instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null) && Player.m_localPlayer.IsBackpackEquipped() && !__result)
				{
					BackpackComponent equippedBackpack = Player.m_localPlayer.GetEquippedBackpack();
					__result = (Object)(object)__instance.m_keyItem == (Object)null || equippedBackpack.GetInventory().HaveItem(__instance.m_keyItem.m_itemData.m_shared.m_name, true);
				}
			}
		}
	}
	public class EnvManPatches
	{
		[HarmonyPatch(typeof(EnvMan), "IsCold")]
		public static class EnvManIsCold
		{
			[UsedImplicitly]
			[HarmonyPriority(800)]
			public static bool Prefix(EnvMan __instance, ref bool __result)
			{
				if ((Object)(object)Player.m_localPlayer == (Object)null)
				{
					return true;
				}
				if (EffectsFactory.EffectList[BackpackEffect.ColdResistance].IsEffectActive((Humanoid)(object)Player.m_localPlayer))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(EnvMan), "IsWet")]
		public static class EnvManIsWet
		{
			[HarmonyPriority(800)]
			[UsedImplicitly]
			public static bool Prefix(EnvMan __instance, ref bool __result)
			{
				if ((Object)(object)Player.m_localPlayer == (Object)null)
				{
					return true;
				}
				if (EffectsFactory.EffectList[BackpackEffect.WaterResistance].IsEffectActive((Humanoid)(object)Player.m_localPlayer))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}
	}
	public class FejdStartupPatches
	{
		[HarmonyBefore(new string[] { "org.bepinex.helpers.ItemManager" })]
		[HarmonyAfter(new string[] { "org.bepinex.helpers.LocalizationManager" })]
		[HarmonyPatch(typeof(FejdStartup), "Awake")]
		public static class FejdStartupAwakePatch
		{
			private static void Prefix()
			{
				AdventureBackpacks.Waiter.ValheimIsAwake(awakeFlag: true);
			}
		}
	}
	public class GuiBarPatches
	{
		[HarmonyPatch(typeof(GuiBar), "Awake")]
		public static class GuiBarAwakePatch
		{
			public const string eaqsGUID = "randyknapp.mods.equipmentandquickslots";

			private static bool Prefix(GuiBar __instance)
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_004a: Unknown result type (might be due to invalid IL or missing references)
				if (!Chainloader.PluginInfos.ContainsKey("randyknapp.mods.equipmentandquickslots") && ((Object)__instance).name == "durability" && __instance.m_bar.sizeDelta.x != 54f)
				{
					__instance.m_bar.sizeDelta = new Vector2(54f, 0f);
				}
				return true;
			}
		}
	}
	public class HumanoidPatches
	{
		[HarmonyPatch(typeof(Humanoid), "UpdateEquipmentStatusEffects")]
		private static class HumanoidUpdateEquipmentStatusEffectsPatch
		{
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				bool patchedSuccess = false;
				List<CodeInstruction> instrs = instructions.ToList();
				int counter = 0;
				CodeInstruction ldlocInstruction = new CodeInstruction(OpCodes.Ldloc_0, (object)null);
				int i = 0;
				while (i < instrs.Count)
				{
					yield return LogMessage(instrs[i]);
					counter++;
					if (instrs[i].opcode == OpCodes.Stloc_0 && instrs[i - 1].opcode == OpCodes.Newobj)
					{
						if (instrs[i].labels.Count > 0)
						{
							CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldlocInstruction);
						}
						yield return LogMessage(ldlocInstruction);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(EquipmentEffectCache), "AddActiveBackpackEffects", (Type[])null, (Type[])null)));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Stloc_0, (object)null));
						counter++;
						patchedSuccess = true;
					}
					int num = i + 1;
					i = num;
				}
				if (!patchedSuccess)
				{
					AdventureBackpacks.Log.Error("UpdateEquipmentStatusEffects Transpiler Failed To Patch");
					Thread.Sleep(5000);
				}
				CodeInstruction LogMessage(CodeInstruction instruction)
				{
					AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}");
					return instruction;
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "UnequipItem")]
		private static class HumanoidUnequipItemPatch
		{
			private static void Prefix(ItemData __0)
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_0086: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: Expected O, but got Unknown
				if (__0 == null || (Object)(object)Player.m_localPlayer == (Object)null)
				{
					return;
				}
				Scene activeScene = SceneManager.GetActiveScene();
				if (((Scene)(ref activeScene)).name.Equals("start"))
				{
					return;
				}
				Player localPlayer = Player.m_localPlayer;
				if (!__0.IsBackpack() || ((Humanoid)localPlayer).m_shoulderItem != __0)
				{
					return;
				}
				BackpackComponent equippedBackpack = localPlayer.GetEquippedBackpack();
				if (equippedBackpack != null)
				{
					equippedBackpack.Save();
					InventoryGui instance = InventoryGui.instance;
					if (instance.IsContainerOpen())
					{
						instance.CloseContainer();
						InventoryGuiPatches.BackpackIsOpen = false;
					}
					((Component)localPlayer).gameObject.GetComponent<Container>().m_inventory = new Inventory("Empty", (Sprite)null, 1, 1);
					InventoryGuiPatches.BackpackEquipped = false;
				}
			}
		}

		[HarmonyPatch(typeof(Humanoid), "EquipItem")]
		private static class HumanoidEquipItemPatch
		{
			private static void Postfix(ItemData __0, bool __result)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				if (__0 == null || ((Object)(object)Player.m_localPlayer == (Object)null && !__result))
				{
					return;
				}
				Scene activeScene = SceneManager.GetActiveScene();
				if (!((Scene)(ref activeScene)).name.Equals("start"))
				{
					Player localPlayer = Player.m_localPlayer;
					if (__0.IsBackpack())
					{
						InventoryGuiPatches.BackpackEquipped = true;
						Container component = ((Component)localPlayer).gameObject.GetComponent<Container>();
						BackpackComponent orCreate = __0.Data().GetOrCreate<BackpackComponent>();
						Inventory val = (component.m_inventory = orCreate.GetInventory());
						component.m_width = val.m_width;
						component.m_height = val.m_height;
						component.m_bkg = orCreate.Item.m_shared.m_icons[0];
					}
				}
			}
		}
	}
	public static class InventoryPatches
	{
		[HarmonyPatch(typeof(Inventory), "Changed")]
		private static class InventoryChangedPatch
		{
			private static void Postfix(Inventory __instance)
			{
				if (__instance != null && !((Object)(object)Player.m_localPlayer == (Object)null) && __instance.IsBackPackInventory())
				{
					Player.m_localPlayer.GetEquippedBackpack()?.Save();
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "OnDropOutside")]
		[HarmonyPriority(800)]
		private static class OnDropOutsideItemPatch
		{
			private static void Prefix(InventoryGui __instance)
			{
				if (!((Object)(object)__instance == (Object)null) && __instance.m_dragItem != null)
				{
					if (__instance.m_dragItem.IsBackpack() && __instance.m_dragItem.m_stack == 0)
					{
						__instance.m_dragItem.m_stack = 1;
					}
					_droppingOutside = true;
				}
			}

			private static void Postfix()
			{
				_droppingOutside = false;
			}
		}

		[HarmonyPatch(typeof(Humanoid), "DropItem", new Type[]
		{
			typeof(Inventory),
			typeof(ItemData),
			typeof(int)
		})]
		[HarmonyPriority(800)]
		private static class HumanoidDropItemPatch
		{
			private static void Prefix(ItemData item)
			{
				_droppingOutside = true;
			}

			private static void Postfix()
			{
				_droppingOutside = false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData) })]
		[HarmonyPriority(800)]
		private static class RemoveItem1Patch
		{
			private static void Prefix(Inventory __instance, ItemData item)
			{
				if (item != null && __instance != null)
				{
					RemoveItemPrefix(__instance, item);
				}
			}
		}

		[HarmonyPriority(800)]
		[HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[]
		{
			typeof(ItemData),
			typeof(int)
		})]
		private static class RemoveItem2Patch
		{
			private static void Prefix(Inventory __instance, ItemData item)
			{
				if (item != null && __instance != null)
				{
					RemoveItemPrefix(__instance, item);
				}
			}
		}

		[HarmonyPatch(typeof(Inventory), "RemoveOneItem", new Type[] { typeof(ItemData) })]
		[HarmonyPriority(800)]
		private static class RemoveItem3Patch
		{
			private static void Prefix(Inventory __instance, ItemData item)
			{
				if (item != null && __instance != null)
				{
					RemoveItemPrefix(__instance, item);
				}
			}
		}

		[HarmonyPriority(800)]
		[HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })]
		private static class AddItemPatch
		{
			private static bool Prefix(Inventory __instance, ItemData item, ref bool __result)
			{
				if (item == null)
				{
					return false;
				}
				if (item.IsBackpack() && __instance.HaveEmptySlot())
				{
					bool flag = Backpacks.CheckForInception(__instance, item);
					if (flag && !_movingItemBetweenContainers)
					{
						ItemsAddedQueue.Enqueue(new KeyValuePair<ItemData, DateTime>(item, DateTime.Now));
					}
					__result = flag;
					return flag;
				}
				return true;
			}
		}

		[HarmonyPriority(800)]
		[HarmonyPatch(typeof(InventoryGrid), "DropItem", new Type[]
		{
			typeof(Inventory),
			typeof(ItemData),
			typeof(int),
			typeof(Vector2i)
		})]
		private static class InventoryGridDropItemPatch
		{
			private static bool Prefix(InventoryGrid __instance, Inventory fromInventory, ItemData item, int amount, Vector2i pos)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				ItemData itemAt = __instance.m_inventory.GetItemAt(pos.x, pos.y);
				if (itemAt == item)
				{
					return true;
				}
				if (itemAt == null || (!(itemAt.m_shared.m_name != item.m_shared.m_name) && (item.m_shared.m_maxQuality <= 1 || itemAt.m_quality == item.m_quality) && itemAt.m_shared.m_maxStackSize != 1) || item.m_stack != amount)
				{
					return true;
				}
				if (AdventureBackpacks.PerformYardSale)
				{
					return true;
				}
				if (itemAt.IsBackpack() && fromInventory.IsBackPackInventory())
				{
					return Backpacks.CheckForInception(fromInventory, itemAt);
				}
				if (item.IsBackpack() && __instance.m_inventory.IsBackPackInventory())
				{
					return Backpacks.CheckForInception(__instance.m_inventory, item);
				}
				_movingItemBetweenContainers = true;
				return true;
			}
		}

		[HarmonyPatch(typeof(Inventory), "MoveAll", new Type[] { typeof(Inventory) })]
		[HarmonyPriority(800)]
		private static class MoveAllPatch
		{
			private static void Prefix(Inventory fromInventory, Inventory __instance)
			{
				if (fromInventory != null && !__instance.IsBackPackInventory())
				{
					_movingItemBetweenContainers = true;
				}
			}

			private static void Postfix()
			{
				_movingItemBetweenContainers = false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[]
		{
			typeof(Inventory),
			typeof(ItemData),
			typeof(int),
			typeof(int),
			typeof(int)
		})]
		[HarmonyPriority(800)]
		private static class MoveItemToThisPatch
		{
			private static bool Prefix(Inventory __0, ItemData __1, int __2, int __3, int __4, Inventory __instance)
			{
				if (__0 == null || __1 == null)
				{
					return false;
				}
				if (!__instance.IsBackPackInventory())
				{
					_movingItemBetweenContainers = true;
					return true;
				}
				return Backpacks.CheckForInception(__instance, __1);
			}

			private static void Postfix()
			{
				_movingItemBetweenContainers = false;
			}
		}

		[HarmonyPriority(800)]
		[HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[]
		{
			typeof(Inventory),
			typeof(ItemData)
		})]
		private static class MoveItemToThisOtherPatch
		{
			private static bool Prefix(Inventory __0, ItemData __1, Inventory __instance)
			{
				if (__0 == null || __1 == null)
				{
					return false;
				}
				if (!__instance.IsBackPackInventory())
				{
					_movingItemBetweenContainers = true;
					return true;
				}
				return Backpacks.CheckForInception(__instance, __1);
			}

			private static void Postfix()
			{
				_movingItemBetweenContainers = false;
			}
		}

		[HarmonyPatch(typeof(Inventory), "UpdateTotalWeight")]
		private static class UpdateTotalWeightPatch
		{
			[HarmonyPatch(typeof(Inventory), "IsTeleportable")]
			private static class IsTeleportablePatch
			{
				private static void Postfix(Inventory __instance, ref bool __result)
				{
					if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null)
					{
						return;
					}
					List<ItemData> allItems = __instance.GetAllItems();
					if (__instance != ((Humanoid)Player.m_localPlayer).GetInventory())
					{
						return;
					}
					if (Player.m_localPlayer.IsBackpackEquipped())
					{
						BackpackComponent equippedBackpack = Player.m_localPlayer.GetEquippedBackpack();
						if (equippedBackpack != null && !equippedBackpack.GetInventory().IsTeleportable())
						{
							__result = false;
							return;
						}
					}
					foreach (ItemData item in allItems)
					{
						if (item != null && item.IsBackpack() && !item.Data().GetOrCreate<BackpackComponent>().GetInventory()
							.IsTeleportable())
						{
							__result = false;
							break;
						}
					}
				}
			}

			private static void Postfix(Inventory __instance)
			{
				if (__instance != null && !((Object)(object)Player.m_localPlayer == (Object)null))
				{
					Player localPlayer = Player.m_localPlayer;
					if (__instance.IsBackPackInventory() && Object.op_Implicit((Object)(object)localPlayer))
					{
						((Humanoid)localPlayer).GetInventory().UpdateTotalWeight();
					}
				}
			}
		}

		private static bool _movingItemBetweenContainers;

		private static bool _droppingOutside;

		private static readonly Queue<KeyValuePair<ItemData, DateTime>> ItemsAddedQueue = new Queue<KeyValuePair<ItemData, DateTime>>();

		private static bool IsItemFromQueue(this ItemData item)
		{
			if (ItemsAddedQueue.Any((KeyValuePair<ItemData, DateTime> x) => ((object)x.Key).Equals((object?)item)))
			{
				AdventureBackpacks.Log.Debug("Item " + item.m_shared.m_name + " Found!");
				return true;
			}
			AdventureBackpacks.Log.Debug("Item Not Found!");
			return false;
		}

		public static void ProcessItemsAddedQueue()
		{
			while (ItemsAddedQueue.Any() && DateTime.Now.Subtract(ItemsAddedQueue.Peek().Value).TotalSeconds > 0.5)
			{
				AdventureBackpacks.Log.Debug($"Process Cache Removing {ItemsAddedQueue.Peek().Key.m_shared.m_name} for Date {ItemsAddedQueue.Peek().Value} with a difference of {DateTime.Now.Subtract(ItemsAddedQueue.Peek().Value).TotalSeconds} total seconds.");
				ItemsAddedQueue.Dequeue();
			}
		}

		private static void RemoveItemPrefix(Inventory __instance, ItemData item)
		{
			if (__instance == null || (Object)(object)Player.m_localPlayer == (Object)null || _movingItemBetweenContainers || _droppingOutside || AdventureBackpacks.PerformYardSale || AdventureBackpacks.QuickDropping || AdventureBackpacks.BypassMoveProtection || !item.TryGetBackpackItem(out var _))
			{
				return;
			}
			AdventureBackpacks.Log.Debug("Checking for Backpack " + item.m_shared.m_name);
			if (item.IsItemFromQueue())
			{
				AdventureBackpacks.Log.Debug("Exiting RemoveItem for " + item.m_shared.m_name);
				return;
			}
			BackpackComponent backpackComponent = item.Data().Get<BackpackComponent>();
			if (backpackComponent != null)
			{
				Inventory inventory = backpackComponent.GetInventory();
				if (inventory != null && inventory.m_inventory.Count > 0)
				{
					Backpacks.PerformYardSale(Player.m_localPlayer, item, backpackOnly: true);
				}
			}
		}
	}
	internal static class InventoryGuiPatches
	{
		[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
		private static class InventoryGuiDoCraftingPrefix
		{
			[UsedImplicitly]
			private static void Postfix(InventoryGui __instance)
			{
				if (__instance.m_craftUpgradeItem != null && __instance.m_craftUpgradeItem.IsBackpack())
				{
					__instance.m_craftUpgradeItem.Data().Get<BackpackComponent>()?.Load();
					((Humanoid)Player.m_localPlayer).UpdateEquipmentStatusEffects();
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "OnSelectedItem")]
		private static class InventoryGuiOnSelectedItem
		{
			[UsedImplicitly]
			private static Exception Finalizer(Exception __exception, InventoryGrid grid, ItemData item, Vector2i pos, Modifier mod, InventoryGui __instance)
			{
				if (__exception != null)
				{
					if (__exception is NullReferenceException && (Object)(object)__instance != (Object)null && (Object)(object)__instance.m_currentContainer == (Object)null && grid.GetInventory() != null && (Object)(object)Player.m_localPlayer != (Object)null && Backpacks.BackpackTypes.Contains(item.m_shared.m_name))
					{
						((Humanoid)Player.m_localPlayer).DropItem(((Humanoid)Player.m_localPlayer).GetInventory(), item, 1);
						BackpackIsOpen = false;
						__instance.Hide();
						((Character)Player.m_localPlayer).Message((MessageType)1, "$vapok_mod_you_droped_bag", 0, (Sprite)null);
						return null;
					}
					AdventureBackpacks.Log.Warning("The following error was captured by Adventure Backpacks, but was caused by another mod. Advanced Backpacks is going to allow the operation to continue, but is going to replay the error below:");
					AdventureBackpacks.Log.Error("External Mod Error Message: " + __exception.Message);
					AdventureBackpacks.Log.Error("External Mod Error Source: " + __exception.Source);
					AdventureBackpacks.Log.Error("External Mod Error Stack Trace: " + __exception.StackTrace);
					AdventureBackpacks.Log.Warning("Please check with other mod authors listed above.");
				}
				return null;
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "Update")]
		private static class InventoryGuiUpdateTranspiler
		{
			[UsedImplicitly]
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator ilGenerator)
			{
				List<CodeInstruction> instrs = instructions.ToList();
				int counter = 0;
				bool patchedHideBackpackMethod = false;
				bool patchedShowBackpackMethod = false;
				bool patchedDetectInputHideMethod = false;
				bool patchedDetectInputShowMethod = false;
				MethodInfo resetButtonStatus = AccessTools.DeclaredMethod(typeof(ZInput), "ResetButtonStatus", (Type[])null, (Type[])null);
				AccessTools.DeclaredMethod(typeof(Menu), "IsVisible", (Type[])null, (Type[])null);
				MethodInfo hideMethod = AccessTools.DeclaredMethod(typeof(InventoryGui), "Hide", (Type[])null, (Type[])null);
				MethodInfo showMethod = AccessTools.DeclaredMethod(typeof(InventoryGui), "Show", (Type[])null, (Type[])null);
				MethodInfo zInputKeyDown = AccessTools.DeclaredMethod(typeof(ZInput), "GetKeyDown", new Type[1] { typeof(KeyCode) }, (Type[])null);
				MethodInfo zInputButtonDown = AccessTools.DeclaredMethod(typeof(ZInput), "GetButtonDown", new Type[1] { typeof(string) }, (Type[])null);
				int i = 0;
				while (i < instrs.Count)
				{
					if (i > 6 && instrs[i].opcode == OpCodes.Call && instrs[i].operand.Equals(resetButtonStatus) && instrs[i + 1].opcode == OpCodes.Ldarg_0 && instrs[i + 2].opcode == OpCodes.Call && instrs[i + 2].operand.Equals(hideMethod))
					{
						CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						if (instrs[i].labels.Count > 0)
						{
							CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction);
						}
						yield return LogMessage(instrs[i]);
						counter++;
						yield return LogMessage(ldArgInstruction);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "HideBackpack", (Type[])null, (Type[])null)));
						counter++;
						patchedHideBackpackMethod = true;
					}
					else if (i > 6 && instrs[i].opcode == OpCodes.Call && instrs[i].operand.Equals(showMethod) && instrs[i - 1].opcode == OpCodes.Ldc_I4_1 && instrs[i - 2].opcode == OpCodes.Ldnull && instrs[i - 3].opcode == OpCodes.Ldarg_0)
					{
						CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldloc_1, (object)null);
						if (instrs[i].labels.Count > 0)
						{
							CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction);
						}
						yield return LogMessage(instrs[i]);
						counter++;
						yield return LogMessage(ldArgInstruction);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "ShowBackpack", (Type[])null, (Type[])null)));
						counter++;
						patchedShowBackpackMethod = true;
					}
					else if (i > 6 && instrs[i].opcode == OpCodes.Call && instrs[i].operand.Equals(zInputKeyDown) && instrs[i - 1].operand.Equals((sbyte)27) && instrs[i + 2].opcode == OpCodes.Ldstr && instrs[i + 2].operand.Equals("Use"))
					{
						yield return LogMessage(instrs[i]);
						counter++;
						yield return LogMessage(instrs[i + 1]);
						counter++;
						Label label2 = (Label)instrs[i + 1].operand;
						CodeInstruction val = FindInstructionWithLabel(instrs, i + 2, label2);
						if (val == null)
						{
							AdventureBackpacks.Log.Error($"Can't Find Instruction with Label {label2}");
						}
						else
						{
							i++;
							Label detectHideLabel2 = ilGenerator.DefineLabel();
							val.labels.Add(detectHideLabel2);
							yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_1, (object)null));
							counter++;
							yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
							counter++;
							yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "DetectInputToHide", (Type[])null, (Type[])null)));
							counter++;
							yield return LogMessage(new CodeInstruction(OpCodes.Brtrue, (object)detectHideLabel2));
							counter++;
							patchedDetectInputHideMethod = true;
						}
					}
					else if (i > 6 && instrs[i].opcode == OpCodes.Call && instrs[i].operand.Equals(zInputButtonDown) && instrs[i - 1].operand.Equals("Inventory") && instrs[i + 1].opcode == OpCodes.Brtrue && instrs[i + 2].opcode == OpCodes.Ldstr && instrs[i + 2].operand.Equals("JoyButtonY"))
					{
						yield return LogMessage(instrs[i]);
						counter++;
						yield return LogMessage(instrs[i + 1]);
						counter++;
						Label label3 = (Label)instrs[i + 1].operand;
						CodeInstruction val2 = FindInstructionWithLabel(instrs, i + 2, label3);
						if (val2 == null)
						{
							AdventureBackpacks.Log.Error($"Can't Find Instruction with Label {label3}");
						}
						else
						{
							i++;
							Label detectHideLabel2 = ilGenerator.DefineLabel();
							val2.labels.Add(detectHideLabel2);
							yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_1, (object)null));
							counter++;
							yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
							counter++;
							yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(InventoryGuiPatches), "DetectInputToShow", (Type[])null, (Type[])null)));
							counter++;
							yield return LogMessage(new CodeInstruction(OpCodes.Brtrue, (object)detectHideLabel2));
							counter++;
							patchedDetectInputShowMethod = true;
						}
					}
					else
					{
						yield return LogMessage(instrs[i]);
						counter++;
					}
					int num = i + 1;
					i = num;
				}
				if (!patchedHideBackpackMethod || !patchedShowBackpackMethod || !patchedDetectInputHideMethod || !patchedDetectInputShowMethod)
				{
					AdventureBackpacks.Log.Error("InventoryGui.Update Transpiler Failed To Patch");
					AdventureBackpacks.Log.Warning($" patchedHideBackpackMethod {patchedHideBackpackMethod}");
					AdventureBackpacks.Log.Warning($" patchedShowBackpackMethod {patchedShowBackpackMethod}");
					AdventureBackpacks.Log.Warning($" patchedDetectInputHideMethod {patchedDetectInputHideMethod}");
					AdventureBackpacks.Log.Warning($" patchedDetectInputShowMethod {patchedDetectInputShowMethod}");
					Thread.Sleep(5000);
				}
				static CodeInstruction FindInstructionWithLabel(List<CodeInstruction> codeInstructions, int index, Label label)
				{
					if (index >= codeInstructions.Count)
					{
						return null;
					}
					if (codeInstructions[index].labels.Contains(label))
					{
						return codeInstructions[index];
					}
					return FindInstructionWithLabel(codeInstructions, index + 1, label);
				}
				CodeInstruction LogMessage(CodeInstruction instruction)
				{
					AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}");
					return instruction;
				}
			}
		}

		[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
		private static class InventoryGuiSetupRequirementPatch
		{
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				bool patchedSuccess = false;
				List<CodeInstruction> instrs = instructions.ToList();
				int counter = 0;
				CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldarg_2, (object)null);
				MethodInfo countItemsMethod = AccessTools.DeclaredMethod(typeof(Inventory), "CountItems", new Type[3]
				{
					typeof(string),
					typeof(int),
					typeof(bool)
				}, (Type[])null);
				int i = 0;
				while (i < instrs.Count)
				{
					yield return LogMessage(instrs[i]);
					counter++;
					if (i > 5 && instrs[i - 1].opcode == OpCodes.Callvirt && instrs[i - 1].operand.Equals(countItemsMethod) && instrs[i].opcode == OpCodes.Stloc_S)
					{
						if (instrs[i].labels.Count > 0)
						{
							CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction);
						}
						yield return LogMessage(ldArgInstruction);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldarg_1, (object)null));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_S, instrs[i].operand));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(PlayerPatches), "AdjustCountIfEquipped", (Type[])null, (Type[])null)));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Stloc_S, instrs[i].operand));
						counter++;
						patchedSuccess = true;
					}
					int num = i + 1;
					i = num;
				}
				if (!patchedSuccess)
				{
					AdventureBackpacks.Log.Error("InventoryGui.SetupRequirement Transpiler Failed To Patch");
					Thread.Sleep(5000);
				}
				CodeInstruction LogMessage(CodeInstruction instruction)
				{
					AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}");
					return instruction;
				}
			}
		}

		public static bool BackpackIsOpen;

		public static bool BackpackEquipped;

		private static bool _showBackpack;

		public static bool CheckForTextInput()
		{
			bool result = false;
			GameObject val = GameObject.Find("_GameMain/LoadingGUI/PixelFix/IngameGui(Clone)/TextInput/panel");
			if ((Object)(object)val != (Object)null && val.activeInHierarchy)
			{
				result = true;
			}
			return result;
		}

		public static void ShowBackpack(Player player, InventoryGui instance)
		{
			if (ConfigRegistry.OpenWithInventory.Value && !BackpackIsOpen && player.CanOpenBackpack())
			{
				_showBackpack = true;
			}
			if (_showBackpack)
			{
				if (!BackpackIsOpen && (Object)(object)instance.m_currentContainer != (Object)null)
				{
					instance.m_currentContainer.SetInUse(false);
					instance.m_currentContainer = null;
				}
				_showBackpack = false;
				player.OpenBackpack(instance);
			}
		}

		public static void HideBackpack(InventoryGui instance)
		{
			if (BackpackIsOpen)
			{
				instance.CloseContainer();
				BackpackIsOpen = false;
				if (ConfigRegistry.CloseInventory.Value && !ConfigRegistry.OpenWithHoverInteract.Value)
				{
					instance.Hide();
				}
			}
		}

		public static bool DetectInputToHide(Player player, InventoryGui instance)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			KeyboardShortcut value = ConfigRegistry.HotKeyOpen.Value;
			bool keyDown = ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey);
			bool flag = ConfigRegistry.CloseInventory.Value && keyDown && !ConfigRegistry.OpenWithHoverInteract.Value;
			int num;
			if (ConfigRegistry.OutwardMode.Value)
			{
				value = ConfigRegistry.HotKeyDrop.Value;
				num = (ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey) ? 1 : 0);
			}
			else
			{
				num = 0;
			}
			bool flag2 = (byte)num != 0;
			bool flag3 = keyDown && !BackpackIsOpen && player.CanOpenBackpack() && !ConfigRegistry.OpenWithHoverInteract.Value;
			List<InventoryGrid> list = new List<InventoryGrid>();
			list.AddRange(((Component)instance.m_player).GetComponentsInChildren<InventoryGrid>());
			if (keyDown && !BackpackIsOpen && ConfigRegistry.OpenWithHoverInteract.Value && !CheckForTextInput())
			{
				ItemData val = null;
				foreach (InventoryGrid item in list)
				{
					if (item.GetHoveredElement() != null)
					{
						Element hoveredElement = item.GetHoveredElement();
						val = item.GetInventory().GetItemAt(hoveredElement.m_pos.x, hoveredElement.m_pos.y);
					}
				}
				if (ZInput.IsGamepadActive() && val == null)
				{
					foreach (InventoryGrid item2 in list)
					{
						if (item2.GetGamepadSelectedItem() != null)
						{
							val = item2.GetGamepadSelectedItem();
						}
					}
				}
				if (val != null && val.IsBackpack() && val.m_equipped && !BackpackIsOpen && player.CanOpenBackpack())
				{
					flag3 = true;
				}
			}
			if (flag3 & !CheckForTextInput())
			{
				if ((Object)(object)instance.m_currentContainer != (Object)null)
				{
					instance.m_currentContainer.SetInUse(false);
					instance.m_currentContainer = null;
				}
				player.OpenBackpack(instance);
				return false;
			}
			if (keyDown && BackpackIsOpen && (!flag || ConfigRegistry.OpenWithHoverInteract.Value) && !CheckForTextInput())
			{
				bool flag4 = false;
				if (ConfigRegistry.OpenWithHoverInteract.Value)
				{
					ItemData val2 = null;
					foreach (InventoryGrid item3 in list)
					{
						if (item3.GetHoveredElement() != null)
						{
							Element hoveredElement2 = item3.GetHoveredElement();
							val2 = item3.GetInventory().GetItemAt(hoveredElement2.m_pos.x, hoveredElement2.m_pos.y);
						}
					}
					if (ZInput.IsGamepadActive() && val2 == null)
					{
						foreach (InventoryGrid item4 in list)
						{
							if (item4.GetGamepadSelectedItem() != null)
							{
								val2 = item4.GetGamepadSelectedItem();
							}
						}
					}
					if (val2 != null && val2.IsBackpack() && val2.m_equipped && BackpackIsOpen)
					{
						flag4 = true;
					}
				}
				else
				{
					flag4 = true;
				}
				if (flag4)
				{
					instance.CloseContainer();
					BackpackIsOpen = false;
					return false;
				}
			}
			if (flag2 && !CheckForTextInput())
			{
				player.QuickDropBackpack();
			}
			if (flag || flag2)
			{
				return !CheckForTextInput();
			}
			return false;
		}

		public static bool DetectInputToShow(Player player, InventoryGui instance)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			KeyboardShortcut value = ConfigRegistry.HotKeyOpen.Value;
			bool keyDown = ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey);
			if (ConfigRegistry.OutwardMode.Value)
			{
				value = ConfigRegistry.HotKeyDrop.Value;
				if (ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey) && !CheckForTextInput())
				{
					player.QuickDropBackpack();
				}
			}
			if (keyDown && !ConfigRegistry.OpenWithHoverInteract.Value && !BackpackIsOpen && player.CanOpenBackpack() && !CheckForTextInput())
			{
				_showBackpack = true;
			}
			if (_showBackpack)
			{
				return !CheckForTextInput();
			}
			return false;
		}
	}
	public class ItemDropPatches
	{
		[HarmonyPatch(typeof(ItemData), "GetWeight")]
		private static class ItemDataGetWeightTranspiler
		{
			public static float OverrideBackpackWeight(ItemData item, float originalWeight)
			{
				float num = originalWeight;
				if (!string.IsNullOrEmpty(item.m_shared.m_name) && item.TryGetBackpackItem(out var backpack))
				{
					Inventory inventory = item.Data().GetOrCreate<BackpackComponent>().GetInventory();
					float num2 = ((inventory != null) ? inventory.GetTotalWeight() : 0f);
					num += num2 * backpack.WeightMultiplier.Value;
				}
				return num;
			}

			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				bool patchedSuccess = false;
				List<CodeInstruction> instrs = instructions.ToList();
				int counter = 0;
				FieldInfo scaleWeightByQualityField = AccessTools.DeclaredField(typeof(SharedData), "m_scaleWeightByQuality");
				int i = 0;
				while (i < instrs.Count)
				{
					if (i > 6 && instrs[i].opcode == OpCodes.Ldloc_0 && instrs[i - 1].opcode == OpCodes.Stloc_0 && instrs[i - 2].opcode == OpCodes.Add && instrs[i - 3].opcode == OpCodes.Mul && instrs[i - 4].opcode == OpCodes.Ldfld && instrs[i - 4].operand.Equals(scaleWeightByQualityField))
					{
						CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
						if (instrs[i].labels.Count > 0)
						{
							CodeInstructionExtensions.MoveLabelsTo(instrs[i], val);
						}
						yield return LogMessage(val);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_0, (object)null));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(ItemDataGetWeightTranspiler), "OverrideBackpackWeight", (Type[])null, (Type[])null)));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Stloc_0, (object)null));
						counter++;
						yield return LogMessage(instrs[i]);
						counter++;
						patchedSuccess = true;
					}
					else
					{
						yield return LogMessage(instrs[i]);
						counter++;
					}
					int num = i + 1;
					i = num;
				}
				if (!patchedSuccess)
				{
					AdventureBackpacks.Log.Error("GetWeight Transpiler Failed To Patch");
					Thread.Sleep(5000);
				}
				CodeInstruction LogMessage(CodeInstruction instruction)
				{
					AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}");
					return instruction;
				}
			}
		}
	}
	public class PlayerPatches
	{
		[HarmonyPatch(typeof(Player), "Awake")]
		private static class PlayerAwakePatch
		{
			private static void Postfix(Player __instance)
			{
				((Component)__instance).gameObject.AddComponent<Container>();
			}
		}

		[HarmonyPatch(typeof(Player), "HaveRequirementItems")]
		private static class PlayerHaveRequirementItemsPatch
		{
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator ilGenerator)
			{
				bool patchedSuccess = false;
				List<CodeInstruction> instrs = instructions.ToList();
				int counter = 0;
				CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
				AccessTools.DeclaredMethod(typeof(Inventory), "CountItems", new Type[3]
				{
					typeof(string),
					typeof(int),
					typeof(bool)
				}, (Type[])null);
				int i = 0;
				while (i < instrs.Count)
				{
					if (i > 5 && instrs[i].opcode == OpCodes.Stloc_S && instrs[i + 1].opcode == OpCodes.Ldarg_1 && instrs[i + 2].opcode == OpCodes.Ldfld)
					{
						if (instrs[i].labels.Count > 0)
						{
							CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction);
						}
						yield return LogMessage(instrs[i]);
						counter++;
						yield return LogMessage(ldArgInstruction);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_2, (object)null));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_S, instrs[i].operand));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(PlayerPatches), "AdjustCountIfEquipped", (Type[])null, (Type[])null)));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Stloc_S, instrs[i].operand));
						counter++;
						patchedSuccess = true;
					}
					else
					{
						yield return LogMessage(instrs[i]);
						counter++;
					}
					int num = i + 1;
					i = num;
				}
				if (!patchedSuccess)
				{
					AdventureBackpacks.Log.Error("HaveRequirementItems Transpiler Failed To Patch");
					Thread.Sleep(5000);
				}
				CodeInstruction LogMessage(CodeInstruction instruction)
				{
					AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}");
					return instruction;
				}
			}
		}

		[HarmonyPatch(typeof(Player), "ConsumeResources")]
		private static class PlayerConsumeResourcesPatch
		{
			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				bool patchedSuccess = false;
				List<CodeInstruction> instrs = instructions.ToList();
				int counter = 0;
				CodeInstruction ldArgInstruction = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
				MethodInfo getAmountMethod = AccessTools.DeclaredMethod(typeof(Requirement), "GetAmount", new Type[1] { typeof(int) }, (Type[])null);
				int i = 0;
				while (i < instrs.Count)
				{
					yield return LogMessage(instrs[i]);
					counter++;
					if (i > 5 && instrs[i - 1].opcode == OpCodes.Callvirt && instrs[i - 1].operand.Equals(getAmountMethod) && instrs[i].opcode == OpCodes.Stloc_3)
					{
						if (instrs[i].labels.Count > 0)
						{
							CodeInstructionExtensions.MoveLabelsTo(instrs[i], ldArgInstruction);
						}
						yield return LogMessage(ldArgInstruction);
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_2, (object)null));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Ldloc_3, (object)null));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(PlayerPatches), "ConsumeUnEquippedItems", (Type[])null, (Type[])null)));
						counter++;
						yield return LogMessage(new CodeInstruction(OpCodes.Stloc_3, (object)null));
						counter++;
						patchedSuccess = true;
					}
					int num = i + 1;
					i = num;
				}
				if (!patchedSuccess)
				{
					AdventureBackpacks.Log.Error("ConsumeResources Transpiler Failed To Patch");
					Thread.Sleep(5000);
				}
				CodeInstruction LogMessage(CodeInstruction instruction)
				{
					AdventureBackpacks.Log.Debug($"IL_{counter}: Opcode: {instruction.opcode} Operand: {instruction.operand}");
					return instruction;
				}
			}
		}

		public static int AdjustCountIfEquipped(Player player, Requirement resource, int itemCount)
		{
			int num = itemCount;
			if (num < 1 || !resource.m_resItem.m_itemData.IsEquipable())
			{
				return num;
			}
			string itemName = resource.m_resItem.m_itemData.m_shared.m_name;
			if (((Humanoid)player).GetInventory().GetEquippedItems().Any((ItemData x) => x.m_shared.m_name.Equals(itemName)))
			{
				num--;
			}
			return num;
		}

		public static int ConsumeUnEquippedItems(Player player, Requirement resource, int amount)
		{
			if (amount < 1 || !resource.m_resItem.m_itemData.IsEquipable())
			{
				return amount;
			}
			string itemName = resource.m_resItem.m_itemData.m_shared.m_name;
			List<ItemData> list = (from x in ((Humanoid)player).m_inventory.GetAllItems()
				where x.m_shared.m_name.Equals(itemName)
				select x).ToList();
			int num = 0;
			for (int i = 0; i < amount; i++)
			{
				foreach (ItemData item in list)
				{
					if (!item.m_equipped && num < amount)
					{
						((Humanoid)player).m_inventory.RemoveItem(item, 1);
						num++;
					}
				}
			}
			return amount - num;
		}
	}
	public static class SEManPatches
	{
		[HarmonyPatch(typeof(SEMan), "RemoveStatusEffect", new Type[]
		{
			typeof(int),
			typeof(bool)
		})]
		public static class RemoveStatusEffects
		{
			[UsedImplicitly]
			[HarmonyPriority(800)]
			public static bool Prefix(int nameHash, ref bool __result)
			{
				if (EquipmentEffectCache.ActiveEffects == null)
				{
					return true;
				}
				if (EquipmentEffectCache.ActiveEffects.Any((StatusEffect x) => x.NameHash().Equals(nameHash)))
				{
					__result = false;
					return false;
				}
				return true;
			}
		}
	}
}
namespace AdventureBackpacks.Features
{
	public static class EquipmentEffectCache
	{
		public static HashSet<StatusEffect> ActiveEffects = new HashSet<StatusEffect>();

		public static HashSet<StatusEffect> AddActiveBackpackEffects(HashSet<StatusEffect> other, Humanoid instance)
		{
			if (other == null)
			{
				AdventureBackpacks.Log.Debug("other HashSet argument is null. Expecting initialized object.");
				other = new HashSet<StatusEffect>();
			}
			Player val = (Player)(object)((instance is Player) ? instance : null);
			if (val != null && (Object)(object)val == (Object)(object)Player.m_localPlayer)
			{
				ActiveEffects = new HashSet<StatusEffect>();
				foreach (KeyValuePair<BackpackEffect, EffectsBase> effect in EffectsFactory.EffectList)
				{
					if (effect.Value.HasActiveStatusEffect((Humanoid)(object)val, out var statusEffect))
					{
						ActiveEffects.Add(statusEffect);
					}
				}
				other.UnionWith(ActiveEffects);
				AdventureBackpacks.Log.Debug($"Adding {other.Count} Active Backpack Effects.");
			}
			return other;
		}
	}
	public static class QuickTransfer
	{
		[HarmonyPatch(typeof(InventoryGui), "OnRightClickItem")]
		[HarmonyPriority(800)]
		private static class OnRightClickItemPatch
		{
			private static void Prefix(InventoryGui __instance, InventoryGrid grid, ItemData item)
			{
				//IL_0095: Unknown result type (might be due to invalid IL or missing references)
				//IL_009a: Unknown result type (might be due to invalid IL or missing references)
				//IL_009b: Unknown result type (might be due to invalid IL or missing references)
				//IL_009d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e3: Expected I4, but got Unknown
				if (!FeatureInitialized || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)__instance == (Object)null || item == null || (Object)(object)__instance.m_currentContainer == (Object)null || !__instance.IsContainerOpen() || !EnableQuickTransfer.Value)
				{
					return;
				}
				if (Chainloader.PluginInfos.ContainsKey("blumaye.quicktransfer"))
				{
					AdventureBackpacks.Log.Warning("blumaye.quicktransfer mod is enabled. Adventure Backpack's Quick Transfer disabled.");
				}
				else
				{
					if (item.m_equipped)
					{
						return;
					}
					if (item.IsEquipable() && grid.m_inventory == ((Humanoid)Player.m_localPlayer).GetInventory())
					{
						ItemType itemType = item.m_shared.m_itemType;
						switch (itemType - 3)
						{
						case 3:
							if (((Humanoid)Player.m_localPlayer).m_helmetItem == null)
							{
								return;
							}
							break;
						case 4:
							if (((Humanoid)Player.m_localPlayer).m_chestItem == null)
							{
								return;
							}
							break;
						case 8:
							if (((Humanoid)Player.m_localPlayer).m_legItem == null)
							{
								return;
							}
							break;
						case 0:
						case 1:
						case 11:
							if (((Humanoid)Player.m_localPlayer).m_rightItem == null)
							{
								return;
							}
							break;
						case 14:
							if (((Humanoid)Player.m_localPlayer).m_shoulderItem == null)
							{
								return;
							}
							break;
						case 15:
							if (((Humanoid)Player.m_localPlayer).m_utilityItem == null)
							{
								return;
							}
							break;
						case 2:
							if (((Humanoid)Player.m_localPlayer).m_leftItem == null)
							{
								return;
							}
							break;
						}
					}
					Inventory inventory = __instance.m_currentContainer.GetInventory();
					if (item.IsBackpack() && inventory.IsBackPackInventory())
					{
						return;
					}
					Inventory inventory2 = ((Humanoid)Player.m_localPlayer).GetInventory();
					if (inventory2 != null && inventory != null && !((Object)(object)grid == (Object)null))
					{
						_inventoryGuiInstance = __instance;
						if (grid.m_inventory == inventory)
						{
							_fromInventory = inventory;
							_toInventory = inventory2;
						}
						else
						{
							_fromInventory = inventory2;
							_toInventory = inventory;
						}
						_processingRightClick = true;
					}
				}
			}

			private static void Postfix()
			{
				_processingRightClick = false;
				_toInventory = null;
				_fromInventory = null;
				_inventoryGuiInstance = null;
			}
		}

		[HarmonyPriority(800)]
		[HarmonyPatch(typeof(Humanoid), "UseItem")]
		private static class UseItemPatch
		{
			private static bool Prefix(ItemData item)
			{
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				if (!_processingRightClick)
				{
					return true;
				}
				_toInventory.MoveItemToThis(_fromInventory, item);
				_inventoryGuiInstance.m_moveItemEffects.Create(((Component)_inventoryGuiInstance).transform.position, Quaternion.identity, (Transform)null, 1f, -1);
				return false;
			}
		}

		public static bool FeatureInitialized;

		private static InventoryGui _inventoryGuiInstance;

		private static Inventory _fromInventory;

		private static Inventory _toInventory;

		private static bool _processingRightClick;

		public static ConfigEntry<bool> EnableQuickTransfer { get; private set; }

		static QuickTransfer()
		{
			ConfigRegistry.Waiter.StatusChanged += delegate
			{
				RegisterConfiguraitonFile();
			};
		}

		private static void RegisterConfiguraitonFile()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			EnableQuickTransfer = ConfigSyncBase.UnsyncedConfig("Local Config", "Enable Quick Right Click Item Transfer", value: false, new ConfigDescription("When enabled, can move items to/from player inventory to container, by right clicking.", (AcceptableValueBase)null, new object[1]
			{
				new Vapok.Common.Shared.ConfigurationManagerAttributes
				{
					Order = 5
				}
			}));
		}
	}
}
namespace AdventureBackpacks.Extensions
{
	public static class InventoryExtensions
	{
		public static bool IsBackPackInventory(this Inventory inventory)
		{
			return inventory.m_name.Contains("$vapok_mod_level");
		}

		public static bool ContainsBackpack(this Inventory inventory, ItemData backpackItem)
		{
			return IsBackpackItemAt(inventory.m_width - 1, inventory.m_height - 1);
			bool IsBackpackItemAt(int x, int y)
			{
				if (x < 0)
				{
					x = inventory.m_width - 1;
					y--;
				}
				if (y < 0)
				{
					return false;
				}
				ItemData itemAt = inventory.GetItemAt(x, y);
				if (itemAt != null && itemAt == backpackItem)
				{
					return true;
				}
				return IsBackpackItemAt(x - 1, y);
			}
		}

		public static bool HasEmptySlot(this Inventory inventory)
		{
			return IsBackpackItemAt(inventory.m_width - 1, inventory.m_height - 1);
			bool IsBackpackItemAt(int x, int y)
			{
				if (x < 0)
				{
					x = inventory.m_width - 1;
					y--;
				}
				if (y < 0)
				{
					return false;
				}
				if (inventory.GetItemAt(x, y) == null)
				{
					return true;
				}
				return IsBackpackItemAt(x - 1, y);
			}
		}

		public static ItemData FindNonBackpackItem(this Inventory inventory)
		{
			return GetNonBackpackItem(inventory.m_width - 1, inventory.m_height - 1);
			ItemData GetNonBackpackItem(int x, int y)
			{
				if (x < 0)
				{
					x = inventory.m_width - 1;
					y--;
				}
				if (y < 0)
				{
					return null;
				}
				ItemData val = inventory.GetItemAt(x, y);
				if (val != null && val.IsBackpack())
				{
					val = GetNonBackpackItem(x - 1, y);
				}
				return val;
			}
		}
	}
	public static class ItemDataExtensions
	{
		public static bool IsBackpack(this ItemData item)
		{
			return Backpacks.BackpackTypes.Contains(item.m_shared.m_name);
		}
	}
	public static class PlayerExtensions
	{
		public static bool IsBackpackEquipped(this Player player)
		{
			if ((Object)(object)player == (Object)null || ((Humanoid)player).GetInventory() == null)
			{
				return false;
			}
			if (((Humanoid)player).m_shoulderItem == null)
			{
				return false;
			}
			return ((Humanoid)player).m_shoulderItem.IsBackpack();
		}

		public static BackpackComponent GetEquippedBackpack(this Player player)
		{
			if ((Object)(object)player == (Object)null || ((Humanoid)player).GetInventory() == null)
			{
				return null;
			}
			if (((Humanoid)player).m_shoulderItem == null)
			{
				return null;
			}
			if (((Humanoid)player).m_shoulderItem.IsBackpack())
			{
				return ((Humanoid)player).m_shoulderItem.Data().GetOrCreate<BackpackComponent>();
			}
			return null;
		}

		public static bool CanOpenBackpack(this Player player)
		{
			return player.IsBackpackEquipped();
		}

		public static void OpenBackpack(this Player player, InventoryGui instance)
		{
			if (!((Object)(object)player == (Object)null))
			{
				Container component = ((Component)player).gameObject.GetComponent<Container>();
				InventoryGuiPatches.BackpackIsOpen = true;
				instance.Show(component, 1);
			}
		}

		public static void QuickDropBackpack(this Player player)
		{
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			BackpackComponent equippedBackpack = player.GetEquippedBackpack();
			if (equippedBackpack == null)
			{
				return;
			}
			ItemData val = null;
			bool flag = false;
			Inventory inventory = ((Humanoid)player).GetInventory();
			if (!inventory.ContainsBackpack(equippedBackpack.Item) && !inventory.HasEmptySlot())
			{
				val = inventory.FindNonBackpackItem();
				if (val == null || !inventory.RemoveItem(val))
				{
					((Character)player).Message((MessageType)2, "$vapok_mod_quick_drop_unavailable", 0, (Sprite)null);
					return;
				}
				flag = true;
			}
			AdventureBackpacks.QuickDropping = true;
			AdventureBackpacks.Log.Message("Quick dropping backpack.");
			((Humanoid)player).RemoveEquipAction(equippedBackpack.Item);
			((Humanoid)player).UnequipItem(equippedBackpack.Item, true);
			((Humanoid)player).m_inventory.RemoveItem(equippedBackpack.Item);
			ItemDrop obj = ItemDrop.DropItem(equippedBackpack.Item, 1, ((Component)player).transform.position - ((Component)player).transform.forward + ((Component)player).transform.up, ((Component)player).transform.rotation);
			((Component)obj).GetComponent<Rigidbody>().velocity = (Vector3.up - ((Component)player).transform.forward) * 5f;
			((Humanoid)player).m_dropEffects.Create(((Component)player).transform.position, Quaternion.identity, (Transform)null, 1f, -1);
			obj.Save();
			if (flag)
			{
				inventory.AddItem(val);
			}
			InventoryGuiPatches.BackpackIsOpen = false;
			AdventureBackpacks.QuickDropping = false;
		}
	}
}
namespace AdventureBackpacks.Configuration
{
	public class ConfigRegistry : ConfigSyncBase
	{
		public static Waiting Waiter;

		internal static ConfigEntry<KeyboardShortcut> HotKeyOpen { get; private set; }

		internal static ConfigEntry<KeyboardShortcut> HotKeyDrop { get; private set; }

		internal static ConfigEntry<bool> OpenWithInventory { get; private set; }

		internal static ConfigEntry<bool> OpenWithHoverInteract { get; private set; }

		internal static ConfigEntry<bool> CloseInventory { get; private set; }

		internal static ConfigEntry<bool> OutwardMode { get; private set; }

		public ConfigRegistry(IPluginInfo mod)
			: base(mod)
		{
			Waiter = new Waiting();
			InitializeConfigurationSettings();
		}

		public sealed override void InitializeConfigurationSettings()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Expected O, but got Unknown
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Expected O, but got Unknown
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Expected O, but got Unknown
			if (ConfigSyncBase._config != null)
			{
				HotKeyOpen = ConfigSyncBase._config.Bind<KeyboardShortcut>("Local Config", "Open Backpack", new KeyboardShortcut((KeyCode)105, Array.Empty<KeyCode>()), new ConfigDescription("Hotkey to open backpack.", (AcceptableValueBase)null, new object[1]
				{
					new Vapok.Common.Shared.ConfigurationManagerAttributes
					{
						Order = 3
					}
				}));
				HotKeyDrop = ConfigSyncBase._config.Bind<KeyboardShortcut>("Local Config", "Quickdrop Backpack", new KeyboardShortcut((KeyCode)121, Array.Empty<KeyCode>()), new ConfigDescription("Hotkey to quickly drop backpack while on the run.", (AcceptableValueBase)null, new object[1]
				{
					new Vapok.Common.Shared.ConfigurationManagerAttributes
					{
						Order = 1
					}
				}));
				OpenWithInventory = ConfigSyncBase._config.Bind<bool>("Local Config", "Open with Inventory", false, new ConfigDescription("If enabled, both backpack and inventory will open when Inventory is opened.", (AcceptableValueBase)null, new object[1]
				{
					new Vapok.Common.Shared.ConfigurationManagerAttributes
					{
						Order = 3
					}
				}));
				OpenWithHoverInteract = ConfigSyncBase._config.Bind<bool>("Local Config", "Open with Interactive Hover", false, new ConfigDescription("If enabled, backpack will only open while hovering over equipped backpack and pressing hotkey.  This option overrides Open with Inventory.", (AcceptableValueBase)null, new object[1]
				{
					new Vapok.Common.Shared.ConfigurationManagerAttributes
					{
						Order = 3
					}
				}));
				CloseInventory = ConfigSyncBase._config.Bind<bool>("Local Config", "Close Inventory", true, new ConfigDescription("If enabled, both backpack and inventory will close with Open Backpack keybind is pressed while Inventory is open.", (AcceptableValueBase)null, new object[1]
				{
					new Vapok.Common.Shared.ConfigurationManagerAttributes
					{
						Order = 2
					}
				}));
				OutwardMode = ConfigSyncBase._config.Bind<bool>("Local Config", "Outward Mode", false, new ConfigDescription("You can use a hotkey to quickly drop your equipped backpack in order to run faster away from danger.", (AcceptableValueBase)null, new object[1]
				{
					new Vapok.Common.Shared.ConfigurationManagerAttributes
					{
						Order = 1
					}
				}));
			}
		}
	}
	public class Waiting
	{
		public event EventHandler StatusChanged;

		public void ConfigurationComplete(bool configDone)
		{
			if (configDone)
			{
				this.StatusChanged?.Invoke(this, EventArgs.Empty);
			}
		}
	}
}
namespace AdventureBackpacks.Components
{
	public class BackpackComponent : CustomItemData
	{
		public static string OldPluginCustomData = "JotunnBackpacks#JotunnBackpacks.BackpackComponent";

		private Inventory _backpackInventory;

		private CustomSE _statusEffects;

		private ILogIt _log = AdventureBackpacks.Log;

		public void SetInventory(Inventory inventoryInstance)
		{
			_backpackInventory = inventoryInstance;
			Save(_backpackInventory);
		}

		public Inventory GetInventory()
		{
			return _backpackInventory;
		}

		public string Serialize()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			_log.Debug("[Serialize()] Starting..");
			ZPackage val = new ZPackage();
			if (_backpackInventory == null)
			{
				_backpackInventory = Backpacks.NewInventoryInstance(base.Item.m_shared.m_name, base.Item.m_quality);
			}
			_backpackInventory.Save(val);
			string result = (base.Value = val.GetBase64());
			_log.Debug("[Serialize()] Value = " + base.Value);
			return result;
		}

		public void Deserialize(string data)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			_log.Debug("[Deserialize()] Starting..");
			try
			{
				string name = base.Item.m_shared.m_name;
				_backpackInventory = Backpacks.NewInventoryInstance(name, base.Item.m_quality);
				base.Value = data;
				_log.Debug("[Deserialize()] Value = " + base.Value);
				ZPackage val = new ZPackage(data);
				_backpackInventory.Load(val);
				_statusEffects = Backpacks.UpdateStatusEffects(base.Item);
			}
			catch (Exception arg)
			{
				_log.Error($"Backpack info is corrupt!\n{arg}");
			}
		}

		public override void FirstLoad()
		{
			string name = base.Item.m_shared.m_name;
			_log.Debug("[FirstLoad] " + name);
			if (!Backpacks.BackpackTypes.Contains(name))
			{
				return;
			}
			if (_backpackInventory == null)
			{
				_backpackInventory = Backpacks.NewInventoryInstance(name, base.Item.m_quality);
				if (!string.IsNullOrEmpty(base.Value))
				{
					Deserialize(base.Value);
				}
				if (base.Item.m_customData.ContainsKey(OldPluginCustomData) && string.IsNullOrEmpty(base.Value))
				{
					string value = base.Item.m_customData[OldPluginCustomData];
					base.Value = value;
					Deserialize(base.Value);
				}
				else
				{
					_log.Debug("[Load] Backpack null, creating...");
					Serialize();
				}
			}
			else if (string.IsNullOrEmpty(base.Value))
			{
				Serialize();
			}
		}

		public override void Load()
		{
			_log.Debug("[Load] Starting");
			if (!string.IsNullOrEmpty(base.Value))
			{
				_log.Debug("[Load] Value = " + base.Value);
				Deserialize(base.Value);
				return;
			}
			if (_backpackInventory == null)
			{
				_log.Debug("[Load] Backpack null, creating...");
				string name = base.Item.m_shared.m_name;
				_backpackInventory = Backpacks.NewInventoryInstance(name, base.Item.m_quality);
			}
			Serialize();
		}

		public override void Save()
		{
			_log.Debug("[Save()] Starting Value = " + base.Value);
			base.Value = Serialize();
		}

		public void Save(Inventory backpack)
		{
			_log.Debug($"[Save(Inventory)] Starting backpack count {backpack.m_inventory.Count}");
			_backpackInventory = backpack;
			Save();
		}

		public CustomItemData Clone()
		{
			return MemberwiseClone() as CustomItemData;
		}
	}
}
namespace AdventureBackpacks.Assets
{
	public static class Backpacks
	{
		private static ILogIt _log = AdventureBackpacks.Log;

		private static List<string> _backpackTypes = new List<string>();

		public static List<string> BackpackTypes => _backpackTypes;

		public static void LoadBackpackTypes(List<string> backpackTypes)
		{
			_backpackTypes = backpackTypes;
		}

		internal static bool TryGetBackpackItem(this ItemData itemData, out BackpackItem backpack)
		{
			backpack = null;
			if (itemData == null)
			{
				return false;
			}
			return TryGetBackpackItemByName(itemData.m_shared.m_name, out backpack);
		}

		internal static bool TryGetBackpackItemByName(string name, out BackpackItem backpack)
		{
			backpack = null;
			if (Utility.IsNullOrWhiteSpace(name))
			{
				return false;
			}
			backpack = BackpackFactory.BackpackItems.FirstOrDefault((BackpackItem x) => x.ItemName.Equals(name));
			return backpack != null;
		}

		public static void UpdateItemDataConfigValues(object sender, EventArgs e)
		{
			if (!((Object)(object)Player.m_localPlayer == (Object)null) && ((Humanoid)Player.m_localPlayer).GetInventory() != null)
			{
				InventoryGui.instance.Hide();
				Inventory inventory2 = ((Humanoid)Player.m_localPlayer).GetInventory();
				if (inventory2 != null)
				{
					SearchInventory(inventory2.m_inventory);
				}
				List<ItemData> equippedItems = ((Humanoid)Player.m_localPlayer).GetInventory().GetEquippedItems();
				if (equippedItems != null)
				{
					SearchInventory(equippedItems);
				}
				((Humanoid)Player.m_localPlayer).UpdateEquipmentStatusEffects();
			}
			static void SearchInventory(List<ItemData> inventory)
			{
				if (inventory == null)
				{
					return;
				}
				foreach (ItemData item in inventory)
				{
					if (item != null && item.IsBackpack())
					{
						item.Data().GetOrCreate<BackpackComponent>().Load();
					}
				}
			}
		}

		public static Inventory NewInventoryInstance(string name, int itemMQuality = 1)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			string text = $"{name} $vapok_mod_level {itemMQuality}";
			if (!TryGetBackpackItemByName(name, out var backpack))
			{
				return null;
			}
			Vector2i inventorySize = backpack.GetInventorySize(itemMQuality);
			return new Inventory(text, (Sprite)null, inventorySize.x, inventorySize.y);
		}

		public static bool CheckForInception(Inventory instance, ItemData item)
		{
			if (instance.IsBackPackInventory() && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				if (item.TryGetBackpackItem(out var backpack))
				{
					backpack.InceptionCounter++;
					switch (backpack.InceptionCounter)
					{
					case 1:
						((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception1", 0, (Sprite)null);
						break;
					case 2:
						((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception2", 0, (Sprite)null);
						break;
					case 5:
						((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception3", 0, (Sprite)null);
						break;
					case 10:
					{
						((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception4", 0, (Sprite)null);
						int num = new Random(42).Next(5000, 20000);
						backpack.YardSaleTimer = new System.Timers.Timer(num);
						backpack.YardSaleTimer.AutoReset = false;
						backpack.YardSaleTimer.Enabled = false;
						backpack.YardSaleTimer.Elapsed += delegate
						{
							YardSaleEvent(backpack);
						};
						backpack.YardSaleTimer.Start();
						break;
					}
					}
					return false;
				}
			}
			return true;
		}

		public static void PerformYardSale(Player mLocalPlayer, ItemData itemData, bool backpackOnly = false)
		{
			if (!itemData.IsBackpack())
			{
				return;
			}
			BackpackComponent backpackComponent = itemData.Data().Get<BackpackComponent>();
			if (backpackComponent != null)
			{
				EmtpyInventory(backpackComponent.GetInventory());
				if (!backpackOnly)
				{
					Inventory inventory2 = ((Humanoid)mLocalPlayer).GetInventory();
					EmtpyInventory(inventory2);
					((Humanoid)mLocalPlayer).UnequipAllItems();
					EmtpyInventory(inventory2);
					((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_no_inception5", 0, (Sprite)null);
					AdventureBackpacks.PerformYardSale = false;
				}
				else
				{
					((Character)Player.m_localPlayer).Message((MessageType)2, "$vapok_mod_thor_saves_contents", 0, (Sprite)null);
				}
			}
			void EmtpyInventory(Inventory inventory)
			{
				_ = inventory.m_inventory.Count;
				while (inventory.m_inventory.Count > 0)
				{
					ItemData val = inventory.m_inventory[0];
					int num = inventory.CountItems(val.m_shared.m_name, -1, true);
					((Humanoid)mLocalPlayer).DropItem(inventory, val, num);
				}
			}
		}

		private static void YardSaleEvent(BackpackItem backpack)
		{
			backpack.YardSaleTimer.Stop();
			AdventureBackpacks.PerformYardSale = true;
		}

		public static CustomSE UpdateStatusEffects(ItemData itemData)
		{
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			if (itemData == null)
			{
				return null;
			}
			if (!itemData.TryGetBackpackItem(out var backpack))
			{
				return null;
			}
			string name = itemData.m_shared.m_name;
			int quality = itemData.m_quality;
			CustomSE customSE = new CustomSE(Enums.StatusEffects.Stats, $"SE_{name}_{quality}");
			string text = $"{name} $vapok_mod_level {quality} $vapok_mod_effect";
			if (backpack.ShowBackpackStatusEffect.Value)
			{
				customSE.Effect.m_name = (string.IsNullOrEmpty(backpack.CustomStatusEffectName.Value) ? text : backpack.CustomStatusEffectName.Value);
				customSE.Effect.m_startMessageType = (MessageType)1;
				customSE.Effect.m_startMessage = "$vapok_mod_useful_backpack";
			}
			List<DamageModPair> list = new List<DamageModPair>();
			itemData.m_shared.m_armor = itemData.m_shared.m_armorPerLevel * (float)quality;
			if (EffectsFactory.EffectList[BackpackEffect.FrostResistance].IsEffectActive(itemData))
			{
				list.Add(FrostResistance.EffectMod);
			}
			if (EffectsFactory.EffectList[BackpackEffect.TrollArmor].HasActiveStatusEffect(itemData, out var statusEffect))
			{
				itemData.m_shared.m_setName = "troll";
				itemData.m_shared.m_setSize = 4;
				itemData.m_shared.m_setStatusEffect = statusEffect;
			}
			else
			{
				itemData.m_shared.m_setName = string.Empty;
				itemData.m_shared.m_setSize = 0;
				itemData.m_shared.m_setStatusEffect = null;
			}
			if (Chainloader.PluginInfos.ContainsKey("com.chebgonaz.ChebsNecromancy"))
			{
				if (EffectsFactory.EffectList[BackpackEffect.NecromancyArmor].HasActiveStatusEffect(itemData, out var statusEffect2))
				{
					itemData.m_shared.m_setStatusEffect = statusEffect2;
				}
				else
				{
					itemData.m_shared.m_setStatusEffect = null;
				}
			}
			backpack.UpdateStatusEffects(quality, customSE, list, itemData);
			itemData.m_shared.m_maxDurability = 1000f;
			((SE_Stats)customSE.Effect).m_mods = list;
			if (backpack.ShowBackpackStatusEffect.Value)
			{
				((StatusEffect)(SE_Stats)customSE.Effect).m_icon = itemData.GetIcon();
			}
			itemData.AddSEToItem(customSE);
			return customSE;
		}
	}
}
namespace AdventureBackpacks.Assets.Items
{
	internal interface IAssetItem
	{
		string PrefabName { get; }

		string ItemName { get; }

		Item Item { get; }
	}
	internal abstract class AssetItem : IAssetItem
	{
		private const string AssetName = "vapokbackpacks";

		private const string AssetFolderName = "Assets.Bundles";

		private string _prefabName;

		private string _itemName;

		private Item _item;

		public string PrefabName => _prefabName;

		public string ItemName => _itemName;

		public Item Item => _item;

		internal AssetItem(string prefabName, string itemName)
		{
			_prefabName = prefabName;
			_itemName = itemName;
			_item = new Item("vapokbackpacks", PrefabName, "Assets.Bundles")
			{
				Configurable = Configurability.Disabled
			};
			SetPersistence();
			ResetPrefabArmor();
		}

		internal void AssignCraftingTable(ItemManager.CraftingTable craftingTable, int stationLevel)
		{
			_item.Crafting.Add(craftingTable, stationLevel);
		}

		internal void AddRecipeIngredient(string prefabName, int quantity)
		{
			_item.RequiredItems.Add(prefabName, quantity);
		}

		internal void AddUpgradeIngredient(string prefabName, int quantity)
		{
			_item.RequiredUpgradeItems.Add(prefabName, quantity);
		}

		internal ItemDrop GetItemDrop()
		{
			Item item = _item;
			if (item == null)
			{
				return null;
			}
			return item.Prefab.GetComponent<ItemDrop>();
		}

		internal void RegisterShaderSwap(MaterialReplacer.ShaderType shaderType = MaterialReplacer.ShaderType.PieceShader)
		{
			MaterialReplacer.RegisterGameObjectForShaderSwap(_item.Prefab, shaderType);
		}

		internal void SetPersistence()
		{
			_item.Prefab.GetComponent<ZNetView>().m_persistent = true;
		}

		internal void ResetPrefabArmor()
		{
			ItemDrop itemDrop = GetItemDrop();
			ItemData itemData = itemDrop.m_itemData;
			if (itemData != null)
			{
				itemDrop.m_autoPickup = true;
				itemData.m_shared.m_armor = itemData.m_shared.m_armorPerLevel;
				itemDrop.Save();
			}
		}
	}
	internal interface IBackpackItem : IAssetItem
	{
	}
	internal abstract class BackpackItem : AssetItem, IBackpackItem, IAssetItem
	{
		private static ConfigSyncBase _config;

		private static ILogIt _logger;

		private string _configSection;

		private string _englishSection;

		private string _localizedCategory;

		private Localization _english;

		public System.Timers.Timer InceptionTimer;

		public System.Timers.Timer YardSaleTimer;

		private int _inceptionCounter;

		private Localization english => _english ?? (_english = ItemManager.LocalizationCache.ForLanguage("English"));

		public int InceptionCounter
		{
			get
			{
				return _inceptionCounter;
			}
			set
			{
				_inceptionCounter = value;
				if (value > 0)
				{
					InceptionTimer.Stop();
					InceptionTimer.Start();
				}
			}
		}

		internal Dictionary<int, ConfigEntry<Vector2>> BackpackSize { get; private set; }

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

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

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

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

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

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

		internal ConfigEntry<BackpackBiomes> BackpackBiome { get; private set; }

		internal ConfigSyncBase Config => _config;

		internal ILogIt Log => _logger;

		protected BackpackItem(string prefabName, string itemName, string configSection = "", bool externalLocalize = false)
			: base(prefabName, itemName)
		{
			_configSection = (string.IsNullOrEmpty(configSection) ? ("Backpack: " + itemName) : configSection);
			_englishSection = english.Localize(_configSection);
			if (externalLocalize)
			{
				_localizedCategory = Localization.m_instance.Localize(_configSection);
			}
			else
			{
				_localizedCategory = Localization.instance.Localize(_configSection);
			}
			base.Item.SectionName = _configSection;
			BackpackSize = new Dictionary<int, ConfigEntry<Vector2>>();
			InceptionTimer = new System.Timers.Timer(10000.0);
			InceptionTimer.AutoReset = false;
			InceptionTimer.Enabled = false;
			InceptionTimer.Elapsed += InceptionCounterReset;
		}

		private void InceptionCounterReset(object source, ElapsedEventArgs e)
		{
			InceptionCounter = 0;
			Log.Message("Odin walks away.");
		}

		internal static void SetConfig(ConfigSyncBase configSync)
		{
			_config = configSync;
		}

		internal static void SetLogger(ILogIt logger)
		{
			_logger = logger;
		}

		internal abstract void RegisterConfigSettings();

		internal virtual Vector2i GetInventorySize(int quality)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			quality = Mathf.Clamp(quality, 1, 4);
			return new Vector2i(Mathf.Clamp((int)BackpackSize[quality].Value.x, 1, 8), (int)BackpackSize[quality].Value.y);
		}

		internal abstract void UpdateStatusEffects(int quality, CustomSE statusEffects, List<DamageModPair> modifierList, ItemData itemData);

		internal virtual void RegisterBackpackSize(int quality = 1, int x = 6, int y = 3)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			BackpackSize.Add(quality, ConfigSyncBase.SyncedConfig<Vector2>(_englishSection, $"Backpack Size - Level {quality}", new Vector2((float)x, (float)y), new ConfigDescription("Backpack size (width, height).\nMax width is 8 unless you want to break things.", (AcceptableValueBase)null, new object[1]
			{
				new Vapok.Common.Shared.ConfigurationManagerAttributes
				{
					Category = _localizedCategory,
					Order = 3
				}
			})));
			BackpackSize[quality].SettingChanged += Backpacks.UpdateItemDataConfigValues;
		}

		internal virtual void RegisterWeightMultiplier(float defaultValue = 0.5f)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			WeightMultiplier = ConfigSyncBase.SyncedConfig(_englishSection, "Weight Multiplier", defaultValue, new ConfigDescription("The weight of items stored in the backpack gets multiplied by this value.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[1]
			{
				new Vapok.Common.Shared.ConfigurationManagerAttributes
				{
					Category = _localizedCategory,
					Order = 4
				}
			}));
			WeightMultiplier.SettingChanged += Backpacks.UpdateItemDataConfigValues;
		}

		internal virtual void RegisterBackpackBiome(BackpackBiomes defaultValue = BackpackBiomes.None)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			BackpackBiome = ConfigSyncBase.SyncedConfig(_englishSection, "Backpack Biome", defaultValue, new ConfigDescription("The Biome this bag will draw it's effects from.", (AcceptableValueBase)null, new object[1]
			{
				new Vapok.Common.Shared.ConfigurationManagerAttributes
				{
					Category = _localizedCategory,
					Order = 5
				}
			}));
			BackpackBiome.SettingChanged += Backpacks.UpdateItemDataConfigValues;
		}

		internal virtual void RegisterCarryBonus(int defaultValue = 0)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			CarryBonus = ConfigSyncBase.SyncedConfig(_englishSection, "Carry Bonus", defaultValue, new ConfigDescription("Increases your carry capacity by this much (multiplied by item level) while wearing the backpack.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), new object[1]
			{
				new Vapok.Common.Shared.ConfigurationManagerAttributes
				{
					Category = _localizedCategory,
					Order = 6
				}
			}));
			CarryBonus.SettingChanged += Backpacks.UpdateItemDataConfigValues;
		}

		internal virtual void RegisterStatusEffectInfo(bool defaultShowStatus = true, string defaultEffectName = "")
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			ShowBackpackStatusEffect = ConfigSyncBase.SyncedConfig(_englishSection, "Show Status Effect", defaultShowStatus, new ConfigDescription("Toggles the visibility of the Backpack Status Effect", (AcceptableValueBase)null, new object[1]
			{
				new Vapok.Common.Shared.ConfigurationManagerAttributes
				{
					Category = _localizedCategory,
					Order = 1
				}
			}));
			ShowBackpackStatusEffect.SettingChanged += Backpacks.UpdateItemDataConfigValues;
			CustomStatusEffectName = ConfigSyncBase.SyncedConfig(_englishSection, "Custom Effect Name", defaultEffectName, new ConfigDescription("Set your own effect name. Leave Empty to use Default Effect name", (AcceptableValueBase)null, new object[1]
			{
				new Vapok.Common.Shared.ConfigurationManagerAttributes
				{
					Category = _localizedCategory,
					Order = 2
				}
			}));
			CustomStatusEffectName.SettingChanged += Backpacks.UpdateItemDataConfigValues;
		}

		internal virtual void RegisterSpeedMod(float defaultValue = -0.15f)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			SpeedMod = ConfigSyncBase.SyncedConfig(_englishSection, "Speed Modifier", defaultValue, new ConfigDescription("Wearing the backpack slows you down by this much.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1f, -0f), new object[1]
			{
				new Vapok.Common.Shared.ConfigurationManagerAttributes
				{
					Category = _localizedCategory,
					Order = 7
				}
			}));
			SpeedMod.SettingChanged += Backpacks.UpdateItemDataConfigValues;
		}

		internal virtual void RegisterEnableFreezing(bool defaultValue = true)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			EnableFreezing = ConfigSyncBase.SyncedConfig(_englishSection, "Prevent freezing/cold?", defaultValue, new ConfigDescription("Wearing the backpack protects you against freezing/cold, just like capes.", (AcceptableValueBase)null, new object[1]
			{
				new Vapok.Common.Shared.ConfigurationManagerAttributes
				{
					Category = _localizedCategory,
					Order = 8
				}
			}));
			EnableFreezing.SettingChanged += Backpacks.UpdateItemDataConfigValues;
		}
	}
}
namespace AdventureBackpacks.Assets.Items.BackpackItems
{
	internal class BackpackBlackForest : BackpackItem
	{
		public BackpackBlackForest(string prefabName, string itemName)
			: base(prefabName, itemName)
		{
			RegisterConfigSettings();
			base.Item.Configurable = Configurability.Recipe | Configurability.Drop;
			AssignCraftingTable(ItemManager.CraftingTable.Forge, 1);
			base.Item.MaximumRequiredStationLevel = 3;
			AddRecipeIngredient("CapeTrollHide", 1);
			AddRecipeIngredient("Copper", 5);
			AddUpgradeIngredient("TrollHide", 3);
			AddUpgradeIngredient("Bronze", 3);
			base.Item.DropsFrom.Add("Greydwarf", 0.002f);
			base.Item.DropsFrom.Add("Greydwarf_Elite", 0.004f);
			base.Item.DropsFrom.Add("Greydwarf_Shaman", 0.004f);
			base.Item.DropsFrom.Add("Troll", 0.01f);
		}

		internal sealed override void RegisterConfigSettings()
		{
			RegisterBackpackBiome(BackpackBiomes.BlackForest);
			RegisterBackpackSize(1, 3, 2);
			RegisterBackpackSize(2, 4, 2);
			RegisterBackpackSize(3, 5, 2);
			RegisterBackpackSize(4, 6, 2);
			RegisterStatusEffectInfo();
			RegisterWeightMultiplier();
			RegisterCarryBonus(10);
			RegisterSpeedMod();
			if ((base.BackpackBiome.Value & BackpackBiomes.BlackForest) != 0)
			{
				EffectsFactory.EffectList[BackpackEffect.ColdResistance].RegisterEffectBiomeQuality(BackpackBiomes.BlackForest, 1);
				EffectsFactory.EffectList[BackpackEffect.TrollArmor].RegisterEffectBiomeQuality(BackpackBiomes.BlackForest, 2);
			}
		}

		internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List<DamageModPair> modifierList, ItemData itemData)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			itemData.m_shared.m_movementModifier = base.SpeedMod.Value / (float)quality;
			((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = base.CarryBonus.Value * quality;
		}
	}
	internal class BackpackMeadows : BackpackItem
	{
		public BackpackMeadows(string prefabName, string itemName)
			: base(prefabName, itemName)
		{
			RegisterConfigSettings();
			base.Item.Configurable = Configurability.Recipe | Configurability.Drop;
			AssignCraftingTable(ItemManager.CraftingTable.Workbench, 2);
			base.Item.MaximumRequiredStationLevel = 3;
			AddRecipeIngredient("CapeDeerHide", 1);
			AddRecipeIngredient("DeerHide", 8);
			AddRecipeIngredient("BoneFragments", 2);
			AddUpgradeIngredient("LeatherScraps", 5);
			AddUpgradeIngredient("DeerHide", 3);
			base.Item.DropsFrom.Add("Greyling", 0.002f);
		}

		internal sealed override void RegisterConfigSettings()
		{
			RegisterBackpackBiome(BackpackBiomes.Meadows);
			RegisterBackpackSize(1, 3, 1);
			RegisterBackpackSize(2, 4, 1);
			RegisterBackpackSize(3, 5, 1);
			RegisterBackpackSize(4, 6, 1);
			RegisterStatusEffectInfo();
			RegisterWeightMultiplier();
			RegisterCarryBonus(5);
			RegisterSpeedMod();
			if ((base.BackpackBiome.Value & BackpackBiomes.Meadows) != 0)
			{
				EffectsFactory.EffectList[BackpackEffect.ColdResistance].RegisterEffectBiomeQuality(BackpackBiomes.Meadows, 3);
			}
		}

		internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List<DamageModPair> modifierList, ItemData itemData)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			itemData.m_shared.m_movementModifier = base.SpeedMod.Value / (float)quality;
			((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = base.CarryBonus.Value * quality;
		}
	}
	internal class BackpackMistlands : BackpackItem
	{
		public BackpackMistlands(string prefabName, string itemName)
			: base(prefabName, itemName)
		{
			RegisterConfigSettings();
			base.Item.Configurable = Configurability.Recipe | Configurability.Drop;
			AssignCraftingTable(ItemManager.CraftingTable.BlackForge, 1);
			base.Item.MaximumRequiredStationLevel = 2;
			AddRecipeIngredient("CapeFeather", 1);
			AddRecipeIngredient("ScaleHide", 5);
			AddRecipeIngredient("Eitr", 10);
			AddUpgradeIngredient("ScaleHide", 4);
			AddUpgradeIngredient("Eitr", 2);
			AddUpgradeIngredient("Softtissue", 5);
			base.Item.DropsFrom.Add("Dverger", 0.002f);
			base.Item.DropsFrom.Add("DvergerMage", 0.002f);
			base.Item.DropsFrom.Add("DvergerMageFire", 0.002f);
			base.Item.DropsFrom.Add("DvergerMageIce", 0.002f);
			base.Item.DropsFrom.Add("DvergerMageSupport", 0.002f);
		}

		internal sealed override void RegisterConfigSettings()
		{
			RegisterBackpackBiome(BackpackBiomes.Mistlands);
			RegisterBackpackSize(1, 8, 2);
			RegisterBackpackSize(2, 5, 4);
			RegisterBackpackSize(3, 6, 4);
			RegisterBackpackSize(4, 7, 4);
			RegisterStatusEffectInfo();
			RegisterWeightMultiplier();
			RegisterCarryBonus(30);
			RegisterSpeedMod();
			if ((base.BackpackBiome.Value & BackpackBiomes.Mistlands) != 0)
			{
				EffectsFactory.EffectList[BackpackEffect.FeatherFall].RegisterEffectBiomeQuality(BackpackBiomes.Mistlands, 3);
				EffectsFactory.EffectList[BackpackEffect.Demister].RegisterEffectBiomeQuality(BackpackBiomes.Mistlands, 4);
				EffectsFactory.EffectList[BackpackEffect.FrostResistance].RegisterEffectBiomeQuality(BackpackBiomes.Mistlands, 1);
			}
		}

		internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List<DamageModPair> modifierList, ItemData itemData)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			itemData.m_shared.m_movementModifier = base.SpeedMod.Value / (float)quality;
			((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = base.CarryBonus.Value * quality;
		}
	}
	internal class BackpackMountains : BackpackItem
	{
		public BackpackMountains(string prefabName, string itemName)
			: base(prefabName, itemName)
		{
			RegisterConfigSettings();
			base.Item.Configurable = Configurability.Recipe | Configurability.Drop;
			AssignCraftingTable(ItemManager.CraftingTable.Forge, 3);
			base.Item.MaximumRequiredStationLevel = 7;
			AddRecipeIngredient("CapeWolf", 1);
			AddRecipeIngredient("WolfHairBundle", 10);
			AddUpgradeIngredient("WolfPelt", 5);
			AddUpgradeIngredient("Silver", 5);
			base.Item.DropsFrom.Add("Fenring_Cultist", 0.002f);
			base.Item.DropsFrom.Add("Fenring", 0.008f);
		}

		internal sealed override void RegisterConfigSettings()
		{
			RegisterBackpackBiome(BackpackBiomes.Mountains);
			RegisterBackpackSize(1, 3);
			RegisterBackpackSize(2, 4);
			RegisterBackpackSize(3, 5);
			RegisterBackpackSize(4);
			RegisterStatusEffectInfo();
			RegisterWeightMultiplier();
			RegisterCarryBonus(20);
			RegisterSpeedMod();
			if ((base.BackpackBiome.Value & BackpackBiomes.Mountains) != 0)
			{
				EffectsFactory.EffectList[BackpackEffect.FrostResistance].RegisterEffectBiomeQuality(BackpackBiomes.Mountains, 1);
			}
		}

		internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List<DamageModPair> modifierList, ItemData itemData)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			itemData.m_shared.m_movementModifier = base.SpeedMod.Value / (float)quality;
			((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = base.CarryBonus.Value * quality;
		}
	}
	internal class BackpackNecromancy : BackpackItem
	{
		public BackpackNecromancy(string prefabName, string itemName)
			: base(prefabName, itemName, "", externalLocalize: true)
		{
			RegisterConfigSettings();
			base.Item.Configurable = Configurability.Recipe | Configurability.Drop;
			AssignCraftingTable(ItemManager.CraftingTable.Workbench, 1);
			base.Item.MaximumRequiredStationLevel = 4;
			AddRecipeIngredient("ChebGonaz_SpectralShroud", 1);
			AddRecipeIngredient("TrollHide", 5);
			AddUpgradeIngredient("Chain", 1);
			AddUpgradeIngredient("TrollHide", 5);
			base.Item.DropsFrom.Add("ChebGonaz_GuardianWraith", 0.002f);
		}

		internal sealed override void RegisterConfigSettings()
		{
			RegisterBackpackBiome(BackpackBiomes.BlackForest | BackpackBiomes.Necromancy);
			RegisterBackpackSize(1, 3);
			RegisterBackpackSize(2, 4);
			RegisterBackpackSize(3, 5);
			RegisterBackpackSize(4);
			RegisterWeightMultiplier();
			RegisterCarryBonus(20);
			RegisterSpeedMod();
			RegisterShaderSwap();
			if ((base.BackpackBiome.Value & BackpackBiomes.Necromancy) != 0)
			{
				EffectsFactory.EffectList[BackpackEffect.NecromancyArmor].RegisterEffectBiomeQuality(BackpackBiomes.Necromancy, 1);
			}
		}

		internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List<DamageModPair> modifierList, ItemData itemData)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			itemData.m_shared.m_movementModifier = base.SpeedMod.Value / (float)quality;
			((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = base.CarryBonus.Value * quality;
		}
	}
	internal class BackpackPlains : BackpackItem
	{
		public BackpackPlains(string prefabName, string itemName)
			: base(prefabName, itemName)
		{
			RegisterConfigSettings();
			base.Item.Configurable = Configurability.Recipe | Configurability.Drop;
			AssignCraftingTable(ItemManager.CraftingTable.Forge, 3);
			base.Item.MaximumRequiredStationLevel = 7;
			AddRecipeIngredient("CapeLox", 1);
			AddRecipeIngredient("Tar", 5);
			AddRecipeIngredient("BlackMetal", 5);
			AddUpgradeIngredient("LoxPelt", 2);
			AddUpgradeIngredient("BlackMetal", 5);
			base.Item.DropsFrom.Add("Goblin", 0.002f);
			base.Item.DropsFrom.Add("GoblinArcher", 0.002f);
			base.Item.DropsFrom.Add("GoblinBrute", 0.002f);
			base.Item.DropsFrom.Add("GoblinShaman", 0.002f);
		}

		internal sealed override void RegisterConfigSettings()
		{
			RegisterBackpackBiome(BackpackBiomes.Plains);
			RegisterBackpackSize(1, 3, 4);
			RegisterBackpackSize(2, 4, 4);
			RegisterBackpackSize(3, 5, 4);
			RegisterBackpackSize(4, 6, 4);
			RegisterStatusEffectInfo();
			RegisterWeightMultiplier();
			RegisterCarryBonus(25);
			RegisterSpeedMod();
			if ((base.BackpackBiome.Value & BackpackBiomes.Plains) != 0)
			{
				EffectsFactory.EffectList[BackpackEffect.FrostResistance].RegisterEffectBiomeQuality(BackpackBiomes.Plains, 1);
			}
		}

		internal override void UpdateStatusEffects(int quality, CustomSE statusEffects, List<DamageModPair> modifierList, ItemData itemData)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			itemData.m_shared.m_movementModifier = base.SpeedMod.Value / (float)quality;
			((SE_Stats)statusEffects.Effect).m_addMaxCarryWeight = base.CarryBonus.Value * quality;
		}
	}
	internal class BackpackSwamp : BackpackItem
	{
		public BackpackSwamp(string prefabName, string itemName)
			: base(prefabName, itemName)
		{
			RegisterConfigSettings();
			base.Item.Configurable = Configurability.Recipe | Configurability.Drop;
			AssignCraftingTable(ItemManager.CraftingTable.Workbench, 2);
			base.Item.MaximumRequiredStationLevel = 5;
			AddRecipeIngredient("Bloodbag", 10);
			AddRecipeIngredient("Root", 4);
			AddRecipeIngredient("Guck", 4);
			AddUpgradeIngredient("Bloodbag", 2);
			AddUpgradeIngredient("Iron", 5);
			base.Item.DropsFrom.Add("Draugr", 0.002f);
			base.Item.DropsFrom.Add("Draugr_Ranged", 0.004f);
			base.Item.DropsFrom.Add("Draugr_Elite", 0.004f);
			base.Item.DropsFrom.Add("Troll", 0.00

BepInEx/plugins/virtuaCode-TrashItems/TrashItems.dll

Decompiled 8 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("TrashItems")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TrashItems")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("8135d2ba-59ab-4fc3-8fac-3c1e06a67b2f")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = "")]
[assembly: AssemblyVersion("1.0.0.0")]
public class WavUtility
{
	private const int BlockSize_16Bit = 2;

	public static AudioClip ToAudioClip(string filePath)
	{
		if (!filePath.StartsWith(Application.persistentDataPath) && !filePath.StartsWith(Application.dataPath))
		{
			Debug.LogWarning((object)"This only supports files that are stored using Unity's Application data path. \nTo load bundled resources use 'Resources.Load(\"filename\") typeof(AudioClip)' method. \nhttps://docs.unity3d.com/ScriptReference/Resources.Load.html");
			return null;
		}
		return ToAudioClip(File.ReadAllBytes(filePath));
	}

	public static AudioClip ToAudioClip(byte[] fileBytes, int offsetSamples = 0, string name = "wav")
	{
		int num = BitConverter.ToInt32(fileBytes, 16);
		FormatCode(BitConverter.ToUInt16(fileBytes, 20));
		ushort num2 = BitConverter.ToUInt16(fileBytes, 22);
		int num3 = BitConverter.ToInt32(fileBytes, 24);
		ushort num4 = BitConverter.ToUInt16(fileBytes, 34);
		int num5 = 20 + num + 4;
		int dataSize = BitConverter.ToInt32(fileBytes, num5);
		float[] array = num4 switch
		{
			8 => Convert8BitByteArrayToAudioClipData(fileBytes, num5, dataSize), 
			16 => Convert16BitByteArrayToAudioClipData(fileBytes, num5, dataSize), 
			24 => Convert24BitByteArrayToAudioClipData(fileBytes, num5, dataSize), 
			32 => Convert32BitByteArrayToAudioClipData(fileBytes, num5, dataSize), 
			_ => throw new Exception(num4 + " bit depth is not supported."), 
		};
		AudioClip obj = AudioClip.Create(name, array.Length, (int)num2, num3, false);
		obj.SetData(array, 0);
		return obj;
	}

	private static float[] Convert8BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
	{
		int num = BitConverter.ToInt32(source, headerOffset);
		headerOffset += 4;
		float[] array = new float[num];
		sbyte b = sbyte.MaxValue;
		for (int i = 0; i < num; i++)
		{
			array[i] = (float)(int)source[i] / (float)b;
		}
		return array;
	}

	private static float[] Convert16BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
	{
		int num = BitConverter.ToInt32(source, headerOffset);
		headerOffset += 4;
		int num2 = 2;
		int num3 = num / num2;
		float[] array = new float[num3];
		short num4 = short.MaxValue;
		int num5 = 0;
		for (int i = 0; i < num3; i++)
		{
			num5 = i * num2 + headerOffset;
			array[i] = (float)BitConverter.ToInt16(source, num5) / (float)num4;
		}
		return array;
	}

	private static float[] Convert24BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
	{
		int num = BitConverter.ToInt32(source, headerOffset);
		headerOffset += 4;
		int num2 = 3;
		int num3 = num / num2;
		int num4 = int.MaxValue;
		float[] array = new float[num3];
		byte[] array2 = new byte[4];
		int num5 = 0;
		for (int i = 0; i < num3; i++)
		{
			num5 = i * num2 + headerOffset;
			Buffer.BlockCopy(source, num5, array2, 1, num2);
			array[i] = (float)BitConverter.ToInt32(array2, 0) / (float)num4;
		}
		return array;
	}

	private static float[] Convert32BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
	{
		int num = BitConverter.ToInt32(source, headerOffset);
		headerOffset += 4;
		int num2 = 4;
		int num3 = num / num2;
		int num4 = int.MaxValue;
		float[] array = new float[num3];
		int num5 = 0;
		for (int i = 0; i < num3; i++)
		{
			num5 = i * num2 + headerOffset;
			array[i] = (float)BitConverter.ToInt32(source, num5) / (float)num4;
		}
		return array;
	}

	public static byte[] FromAudioClip(AudioClip audioClip)
	{
		string filepath;
		return FromAudioClip(audioClip, out filepath, saveAsFile: false);
	}

	public static byte[] FromAudioClip(AudioClip audioClip, out string filepath, bool saveAsFile = true, string dirname = "recordings")
	{
		MemoryStream stream = new MemoryStream();
		ushort bitDepth = 16;
		int fileSize = audioClip.samples * audioClip.channels * 2 + 44;
		WriteFileHeader(ref stream, fileSize);
		WriteFileFormat(ref stream, audioClip.channels, audioClip.frequency, bitDepth);
		WriteFileData(ref stream, audioClip, bitDepth);
		byte[] array = stream.ToArray();
		if (saveAsFile)
		{
			filepath = string.Format("{0}/{1}/{2}.{3}", Application.persistentDataPath, dirname, DateTime.UtcNow.ToString("yyMMdd-HHmmss-fff"), "wav");
			Directory.CreateDirectory(Path.GetDirectoryName(filepath));
			File.WriteAllBytes(filepath, array);
		}
		else
		{
			filepath = null;
		}
		stream.Dispose();
		return array;
	}

	private static int WriteFileHeader(ref MemoryStream stream, int fileSize)
	{
		byte[] bytes = Encoding.ASCII.GetBytes("RIFF");
		int num = 0 + WriteBytesToMemoryStream(ref stream, bytes, "ID");
		int value = fileSize - 8;
		int num2 = num + WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(value), "CHUNK_SIZE");
		byte[] bytes2 = Encoding.ASCII.GetBytes("WAVE");
		return num2 + WriteBytesToMemoryStream(ref stream, bytes2, "FORMAT");
	}

	private static int WriteFileFormat(ref MemoryStream stream, int channels, int sampleRate, ushort bitDepth)
	{
		byte[] bytes = Encoding.ASCII.GetBytes("fmt ");
		int num = 0 + WriteBytesToMemoryStream(ref stream, bytes, "FMT_ID");
		int value = 16;
		int num2 = num + WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(value), "SUBCHUNK_SIZE");
		ushort value2 = 1;
		int num3 = num2 + WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(value2), "AUDIO_FORMAT");
		ushort value3 = Convert.ToUInt16(channels);
		int num4 = num3 + WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(value3), "CHANNELS") + WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(sampleRate), "SAMPLE_RATE");
		int value4 = sampleRate * channels * BytesPerSample(bitDepth);
		int num5 = num4 + WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(value4), "BYTE_RATE");
		ushort value5 = Convert.ToUInt16(channels * BytesPerSample(bitDepth));
		return num5 + WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(value5), "BLOCK_ALIGN") + WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(bitDepth), "BITS_PER_SAMPLE");
	}

	private static int WriteFileData(ref MemoryStream stream, AudioClip audioClip, ushort bitDepth)
	{
		float[] array = new float[audioClip.samples * audioClip.channels];
		audioClip.GetData(array, 0);
		byte[] bytes = ConvertAudioClipDataToInt16ByteArray(array);
		byte[] bytes2 = Encoding.ASCII.GetBytes("data");
		int num = 0 + WriteBytesToMemoryStream(ref stream, bytes2, "DATA_ID");
		int value = Convert.ToInt32(audioClip.samples * audioClip.channels * 2);
		return num + WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(value), "SAMPLES") + WriteBytesToMemoryStream(ref stream, bytes, "DATA");
	}

	private static byte[] ConvertAudioClipDataToInt16ByteArray(float[] data)
	{
		MemoryStream memoryStream = new MemoryStream();
		int count = 2;
		short num = short.MaxValue;
		for (int i = 0; i < data.Length; i++)
		{
			memoryStream.Write(BitConverter.GetBytes(Convert.ToInt16(data[i] * (float)num)), 0, count);
		}
		byte[] result = memoryStream.ToArray();
		memoryStream.Dispose();
		return result;
	}

	private static int WriteBytesToMemoryStream(ref MemoryStream stream, byte[] bytes, string tag = "")
	{
		int num = bytes.Length;
		stream.Write(bytes, 0, num);
		return num;
	}

	public static ushort BitDepth(AudioClip audioClip)
	{
		return Convert.ToUInt16((float)(audioClip.samples * audioClip.channels) * audioClip.length / (float)audioClip.frequency);
	}

	private static int BytesPerSample(ushort bitDepth)
	{
		return bitDepth / 8;
	}

	private static int BlockSize(ushort bitDepth)
	{
		return bitDepth switch
		{
			32 => 4, 
			16 => 2, 
			8 => 1, 
			_ => throw new Exception(bitDepth + " bit depth is not supported."), 
		};
	}

	private static string FormatCode(ushort code)
	{
		switch (code)
		{
		case 1:
			return "PCM";
		case 2:
			return "ADPCM";
		case 3:
			return "IEEE";
		case 7:
			return "μ-law";
		case 65534:
			return "WaveFormatExtensable";
		default:
			Debug.LogWarning((object)("Unknown wav code format:" + code));
			return "";
		}
	}
}
namespace TrashItems;

[BepInPlugin("virtuacode.valheim.trashitems", "Trash Items Mod", "1.2.6")]
internal class TrashItems : BaseUnityPlugin
{
	public enum SoundEffect
	{
		None,
		Sound1,
		Sound2,
		Sound3,
		Random
	}

	public class TrashButton : MonoBehaviour
	{
		private Canvas canvas;

		private GraphicRaycaster raycaster;

		private RectTransform rectTransform;

		private GameObject buttonGo;

		private void Awake()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Expected O, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Expected O, but got Unknown
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)InventoryGui.instance == (Object)null))
			{
				Transform transform = ((Component)InventoryGui.instance.m_player).transform;
				RectTransform component = ((Component)this).GetComponent<RectTransform>();
				component.anchoredPosition -= new Vector2(0f, 78f);
				SetText(TrashLabel.Value);
				SetColor(TrashColor.Value);
				Transform obj = ((Component)this).transform.Find("armor_icon");
				if (!Object.op_Implicit((Object)(object)obj))
				{
					LogErr("armor_icon not found!");
				}
				((Component)obj).GetComponent<Image>().sprite = trashSprite;
				((Component)this).transform.SetSiblingIndex(0);
				((Object)((Component)((Component)this).transform).gameObject).name = "Trash";
				buttonGo = new GameObject("ButtonCanvas");
				rectTransform = buttonGo.AddComponent<RectTransform>();
				((Component)rectTransform).transform.SetParent(((Component)((Component)this).transform).transform, true);
				rectTransform.anchoredPosition = Vector2.zero;
				rectTransform.sizeDelta = new Vector2(70f, 74f);
				canvas = buttonGo.AddComponent<Canvas>();
				raycaster = buttonGo.AddComponent<GraphicRaycaster>();
				((UnityEvent)buttonGo.AddComponent<Button>().onClick).AddListener(new UnityAction(TrashItem));
				((Graphic)buttonGo.AddComponent<Image>()).color = new Color(0f, 0f, 0f, 0f);
				GameObject val = Object.Instantiate<GameObject>(((Component)transform.Find("selected_frame").GetChild(0)).gameObject, ((Component)this).transform);
				val.GetComponent<Image>().sprite = bgSprite;
				val.transform.SetAsFirstSibling();
				val.GetComponent<RectTransform>().sizeDelta = new Vector2(-8f, 22f);
				val.GetComponent<RectTransform>().anchoredPosition = new Vector2(6f, 7.5f);
				UIGroupHandler val2 = ((Component)this).gameObject.AddComponent<UIGroupHandler>();
				val2.m_groupPriority = 1;
				val2.m_enableWhenActiveAndGamepad = val;
				_gui.m_uiGroups = CollectionExtensions.AddToArray<UIGroupHandler>(_gui.m_uiGroups, val2);
				((Component)this).gameObject.AddComponent<TrashHandler>();
			}
		}

		private void Start()
		{
			((MonoBehaviour)this).StartCoroutine(DelayedOverrideSorting());
		}

		private IEnumerator DelayedOverrideSorting()
		{
			yield return null;
			if (!((Object)(object)canvas == (Object)null))
			{
				canvas.overrideSorting = true;
				canvas.sortingOrder = 1;
			}
		}

		public void SetText(string text)
		{
			Transform val = ((Component)this).transform.Find("ac_text");
			if (!Object.op_Implicit((Object)(object)val))
			{
				LogErr("ac_text not found!");
			}
			else
			{
				((Component)val).GetComponent<Text>().text = text;
			}
		}

		public void SetColor(Color color)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			Transform val = ((Component)this).transform.Find("ac_text");
			if (!Object.op_Implicit((Object)(object)val))
			{
				LogErr("ac_text not found!");
			}
			else
			{
				((Graphic)((Component)val).GetComponent<Text>()).color = color;
			}
		}
	}

	public static ConfigEntry<bool> ConfirmDialog;

	public static ConfigEntry<KeyboardShortcut> TrashHotkey;

	public static ConfigEntry<SoundEffect> Sfx;

	public static ConfigEntry<Color> TrashColor;

	public static ConfigEntry<string> TrashLabel;

	public static bool _clickedTrash = false;

	public static bool _confirmed = false;

	public static InventoryGui _gui;

	public static Sprite trashSprite;

	public static Sprite bgSprite;

	public static GameObject dialog;

	public static AudioClip[] sounds = (AudioClip[])(object)new AudioClip[3];

	public static Transform trash;

	public static AudioSource audio;

	public static TrashButton trashButton;

	public static ManualLogSource MyLogger;

	public static void Log(string msg)
	{
		ManualLogSource myLogger = MyLogger;
		if (myLogger != null)
		{
			myLogger.LogInfo((object)msg);
		}
	}

	public static void LogErr(string msg)
	{
		ManualLogSource myLogger = MyLogger;
		if (myLogger != null)
		{
			myLogger.LogError((object)msg);
		}
	}

	public static void LogWarn(string msg)
	{
		ManualLogSource myLogger = MyLogger;
		if (myLogger != null)
		{
			myLogger.LogWarning((object)msg);
		}
	}

	private void Awake()
	{
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_0188: Unknown result type (might be due to invalid IL or missing references)
		MyLogger = ((BaseUnityPlugin)this).Logger;
		ConfirmDialog = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ConfirmDialog", false, "Show confirm dialog");
		Sfx = ((BaseUnityPlugin)this).Config.Bind<SoundEffect>("General", "SoundEffect", SoundEffect.Random, "Sound effect when trashing items");
		TrashHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Input", "TrashHotkey", KeyboardShortcut.Deserialize("Delete"), "Hotkey for destroying items");
		TrashLabel = ((BaseUnityPlugin)this).Config.Bind<string>("General", "TrashLabel", "Trash", "Label for the trash button");
		TrashColor = ((BaseUnityPlugin)this).Config.Bind<Color>("General", "TrashColor", new Color(1f, 0.8482759f, 0f), "Color for the trash label");
		TrashLabel.SettingChanged += delegate
		{
			if ((Object)(object)trashButton != (Object)null)
			{
				trashButton.SetText(TrashLabel.Value);
			}
		};
		TrashColor.SettingChanged += delegate
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)trashButton != (Object)null)
			{
				trashButton.SetColor(TrashColor.Value);
			}
		};
		Log("TrashItems Loaded!");
		trashSprite = LoadSprite("TrashItems.res.trash.png", new Rect(0f, 0f, 64f, 64f), new Vector2(32f, 32f));
		bgSprite = LoadSprite("TrashItems.res.trashmask.png", new Rect(0f, 0f, 96f, 112f), new Vector2(48f, 56f));
		sounds[0] = LoadAudioClip("TrashItems.res.trash1.wav");
		sounds[1] = LoadAudioClip("TrashItems.res.trash2.wav");
		sounds[2] = LoadAudioClip("TrashItems.res.trash3.wav");
		Harmony.CreateAndPatchAll(typeof(TrashItems), (string)null);
	}

	public static AudioClip LoadAudioClip(string path)
	{
		Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path);
		using MemoryStream memoryStream = new MemoryStream();
		manifestResourceStream.CopyTo(memoryStream);
		return WavUtility.ToAudioClip(memoryStream.GetBuffer());
	}

	public static Sprite LoadSprite(string path, Rect size, Vector2 pivot, int units = 100)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Expected O, but got Unknown
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path);
		Texture2D val = new Texture2D((int)((Rect)(ref size)).width, (int)((Rect)(ref size)).height, (TextureFormat)4, false, true);
		using MemoryStream memoryStream = new MemoryStream();
		manifestResourceStream.CopyTo(memoryStream);
		ImageConversion.LoadImage(val, memoryStream.ToArray());
		val.Apply();
		return Sprite.Create(val, size, pivot, (float)units);
	}

	[HarmonyPatch(typeof(InventoryGui), "Show")]
	[HarmonyPostfix]
	public static void Show_Postfix(InventoryGui __instance)
	{
		Transform transform = ((Component)InventoryGui.instance.m_player).transform;
		trash = transform.Find("Trash");
		if (!((Object)(object)trash != (Object)null))
		{
			_gui = InventoryGui.instance;
			trash = Object.Instantiate<Transform>(transform.Find("Armor"), transform);
			trashButton = ((Component)trash).gameObject.AddComponent<TrashButton>();
			AudioMixerGroup outputAudioMixerGroup = AudioMan.instance.m_masterMixer.FindMatchingGroups("GUI")[0];
			audio = ((Component)trash).gameObject.AddComponent<AudioSource>();
			audio.playOnAwake = false;
			audio.loop = false;
			audio.outputAudioMixerGroup = outputAudioMixerGroup;
			audio.bypassReverbZones = true;
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "Hide")]
	[HarmonyPostfix]
	public static void Postfix()
	{
		OnCancel();
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(InventoryGui), "UpdateItemDrag")]
	public static void UpdateItemDrag_Postfix(InventoryGui __instance, ref GameObject ___m_dragGo, ItemData ___m_dragItem, Inventory ___m_dragInventory, int ___m_dragAmount)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		KeyboardShortcut value = TrashHotkey.Value;
		if (((KeyboardShortcut)(ref value)).IsDown())
		{
			_clickedTrash = true;
		}
		if (_clickedTrash && ___m_dragItem != null && ___m_dragInventory.ContainsItem(___m_dragItem))
		{
			if (ConfirmDialog.Value)
			{
				if (!_confirmed)
				{
					ShowConfirmDialog(___m_dragItem, ___m_dragAmount);
					_clickedTrash = false;
					return;
				}
				_confirmed = false;
			}
			if (___m_dragAmount == ___m_dragItem.m_stack)
			{
				((Humanoid)Player.m_localPlayer).RemoveEquipAction(___m_dragItem);
				((Humanoid)Player.m_localPlayer).UnequipItem(___m_dragItem, false);
				___m_dragInventory.RemoveItem(___m_dragItem);
			}
			else
			{
				___m_dragInventory.RemoveItem(___m_dragItem, ___m_dragAmount);
			}
			if ((Object)(object)audio != (Object)null)
			{
				switch (Sfx.Value)
				{
				case SoundEffect.Random:
					audio.PlayOneShot(sounds[Random.Range(0, 3)]);
					break;
				case SoundEffect.Sound1:
					audio.PlayOneShot(sounds[0]);
					break;
				case SoundEffect.Sound2:
					audio.PlayOneShot(sounds[1]);
					break;
				case SoundEffect.Sound3:
					audio.PlayOneShot(sounds[2]);
					break;
				}
			}
			((object)__instance).GetType().GetMethod("SetupDragItem", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[3] { null, null, 0 });
			((object)__instance).GetType().GetMethod("UpdateCraftingPanel", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(__instance, new object[1] { false });
		}
		_clickedTrash = false;
	}

	public static void ShowConfirmDialog(ItemData item, int itemAmount)
	{
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Expected O, but got Unknown
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Expected O, but got Unknown
		if (!((Object)(object)InventoryGui.instance == (Object)null) && !((Object)(object)dialog != (Object)null))
		{
			dialog = Object.Instantiate<GameObject>(((Component)InventoryGui.instance.m_splitPanel).gameObject, ((Component)InventoryGui.instance).transform);
			Button component = ((Component)dialog.transform.Find("win_bkg/Button_ok")).GetComponent<Button>();
			((UnityEventBase)component.onClick).RemoveAllListeners();
			((UnityEvent)component.onClick).AddListener(new UnityAction(OnConfirm));
			((Component)component).GetComponentInChildren<Text>().text = "Trash";
			((Graphic)((Component)component).GetComponentInChildren<Text>()).color = new Color(1f, 0.2f, 0.1f);
			Button component2 = ((Component)dialog.transform.Find("win_bkg/Button_cancel")).GetComponent<Button>();
			((UnityEventBase)component2.onClick).RemoveAllListeners();
			((UnityEvent)component2.onClick).AddListener(new UnityAction(OnCancel));
			((Component)dialog.transform.Find("win_bkg/Slider")).gameObject.SetActive(false);
			((Component)dialog.transform.Find("win_bkg/Text")).GetComponent<Text>().text = Localization.instance.Localize(item.m_shared.m_name);
			((Component)dialog.transform.Find("win_bkg/Icon_bkg/Icon")).GetComponent<Image>().sprite = item.GetIcon();
			((Component)dialog.transform.Find("win_bkg/amount")).GetComponent<Text>().text = itemAmount + "/" + item.m_shared.m_maxStackSize;
			dialog.gameObject.SetActive(true);
		}
	}

	public static void OnConfirm()
	{
		_confirmed = true;
		if ((Object)(object)dialog != (Object)null)
		{
			Object.Destroy((Object)(object)dialog);
			dialog = null;
		}
		TrashItem();
	}

	public static void OnCancel()
	{
		_confirmed = false;
		if ((Object)(object)dialog != (Object)null)
		{
			Object.Destroy((Object)(object)dialog);
			dialog = null;
		}
	}

	public static void TrashItem()
	{
		Log("Trash Items clicked!");
		if ((Object)(object)_gui == (Object)null)
		{
			LogErr("_gui is null");
			return;
		}
		_clickedTrash = true;
		((object)_gui).GetType().GetMethod("UpdateItemDrag", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(_gui, new object[0]);
	}
}
public class TrashHandler : MonoBehaviour
{
	private UIGroupHandler handler;

	private void Awake()
	{
		handler = ((Component)this).GetComponent<UIGroupHandler>();
	}

	private void Update()
	{
		if (ZInput.GetButtonDown("JoyButtonA") && handler.IsActive)
		{
			TrashItems.TrashItem();
			typeof(InventoryGui).GetMethod("SetActiveGroup", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(InventoryGui.instance, new object[1] { 1 });
		}
	}
}

BepInEx/plugins/Xenofell-TorchesEternal/TorchesEternal.dll

Decompiled 8 months ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("TorchesEternal")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TorchesEternal")]
[assembly: AssemblyCopyright("Copyright ©  2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4845a6cc-2f52-44c8-8b7e-b378584a4c66")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace TorchesEternal;

public static class PluginInfo
{
	public const string Name = "TorchesEternal";

	public const string Guid = "Xenofell.TorchesEternal";

	public const string Version = "0.2";
}
[BepInPlugin("Xenofell.TorchesEternal", "TorchesEternal", "0.2")]
public class Plugin : BaseUnityPlugin
{
	public void Awake()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		new Harmony("Xenofell.TorchesEternal").PatchAll();
	}
}
[HarmonyPatch]
public static class Patches
{
	[HarmonyPrefix]
	[HarmonyPatch(typeof(Fireplace), "UpdateFireplace")]
	public static void Fireplace_UpdateFireplace(Fireplace __instance, ref ZNetView ___m_nview)
	{
		___m_nview.GetZDO().Set("fuel", __instance.m_maxFuel);
	}
}