Decompiled source of JeviLibBL Debug v3.0.0

Mods/JeviLib.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
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.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BoneLib;
using BoneLib.BoneMenu;
using BoneLib.RandomShit;
using HarmonyLib;
using Il2CppCysharp.Threading.Tasks;
using Il2CppInterop.Common;
using Il2CppInterop.Common.XrefScans;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSLZ.Bonelab;
using Il2CppSLZ.Marrow;
using Il2CppSLZ.Marrow.Audio;
using Il2CppSLZ.Marrow.Data;
using Il2CppSLZ.Marrow.Pool;
using Il2CppSLZ.Marrow.PuppetMasta;
using Il2CppSLZ.Marrow.Warehouse;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Runtime.ExceptionServices;
using Il2CppSystem.Threading;
using Jevil;
using Jevil.IMGUI;
using Jevil.Internal.Patching;
using Jevil.Internal.SelfTesting;
using Jevil.Internal.Stats;
using Jevil.Internal.Utilities;
using Jevil.Patching;
using Jevil.PostProcessing;
using Jevil.Spawning;
using Jevil.Tweening;
using Jevil.Waiting;
using MelonLoader;
using MelonLoader.NativeUtils;
using MelonLoader.Preferences;
using MelonLoader.TinyJSON;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using Semver;
using Unity.XR.Oculus;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTrademark(null)]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("JeviLib Dynamic Patch Assembly Host")]
[assembly: InternalsVisibleTo("JevilPlugin")]
[assembly: MelonInfo(typeof(JeviLib), "JeviLib", "3.0.0", "extraes", "https://bonelab.thunderstore.io/package/extraes/JeviLibBL/")]
[assembly: MelonPriority(-20925)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: MelonOptionalDependencies(new string[] { "Mono.Cecil.Rocks" })]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("JeviLib")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+aa806bd4090455e919a1ed346b6a2fbe4aebea8a")]
[assembly: AssemblyProduct("JeviLib")]
[assembly: AssemblyTitle("JeviLib")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.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;
		}
	}
	public static class IsExternalInit
	{
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	[AttributeUsage(AttributeTargets.All)]
	public sealed class IsUnmanagedAttribute : Attribute
	{
	}
	internal sealed class AsyncMethodBuilderAttribute : Attribute
	{
		public Type BuilderType { get; private set; }

		public AsyncMethodBuilderAttribute(Type builderType)
		{
			BuilderType = builderType;
		}
	}
}
namespace Jevil
{
	public static class ActionExtensions
	{
		public static void InvokeSafeParallel(this Action? a)
		{
			if (a == null)
			{
				return;
			}
			Delegate[] invocations = a.GetInvocationList();
			if (invocations.Length == 0)
			{
				return;
			}
			Parallel.For(0, invocations.Length, delegate(int i)
			{
				try
				{
					((Action)invocations[i])();
				}
				catch (Exception obj)
				{
					JeviLib.Error("Exception while parallel safe-invoking on iteration " + (i + 1) + " of " + invocations.Length + "!");
					JeviLib.Error(obj);
				}
			});
		}

		public static void InvokeSafeSync(this Action? a)
		{
			if (a == null)
			{
				return;
			}
			Delegate[] invocationList = a.GetInvocationList();
			if (invocationList.Length == 0)
			{
				return;
			}
			for (int i = 0; i < invocationList.Length; i++)
			{
				try
				{
					((Action)invocationList[i])();
				}
				catch (Exception obj)
				{
					JeviLib.Error("Errored while safe-invoking!");
					JeviLib.Error(obj);
				}
			}
		}

		public static void InvokeSafeSync<T>(this Action<T>? a, T param)
		{
			if (a == null)
			{
				return;
			}
			Delegate[] invocationList = a.GetInvocationList();
			if (invocationList.Length == 0)
			{
				return;
			}
			for (int i = 0; i < invocationList.Length; i++)
			{
				try
				{
					((Action<T>)invocationList[i])(param);
				}
				catch (Exception obj)
				{
					JeviLib.Error("Errored while safe-invoking!");
					JeviLib.Error(obj);
				}
			}
		}

		public static void InvokeSafeSync<T1, T2>(this Action<T1, T2>? a, T1 param1, T2 param2)
		{
			if (a == null)
			{
				return;
			}
			Delegate[] invocationList = a.GetInvocationList();
			if (invocationList.Length == 0)
			{
				return;
			}
			for (int i = 0; i < invocationList.Length; i++)
			{
				try
				{
					((Action<T1, T2>)invocationList[i])(param1, param2);
				}
				catch (Exception obj)
				{
					JeviLib.Error("Errored while safe-invoking!");
					JeviLib.Error(obj);
				}
			}
		}

		public static void InvokeSafeSync<T1, T2, T3>(this Action<T1, T2, T3>? a, T1 param1, T2 param2, T3 param3)
		{
			if (a == null)
			{
				return;
			}
			Delegate[] invocationList = a.GetInvocationList();
			if (invocationList.Length == 0)
			{
				return;
			}
			for (int i = 0; i < invocationList.Length; i++)
			{
				try
				{
					((Action<T1, T2, T3>)invocationList[i])(param1, param2, param3);
				}
				catch (Exception obj)
				{
					JeviLib.Error("Errored while safe-invoking!");
					JeviLib.Error(obj);
				}
			}
		}
	}
	public static class ArrayPool<T>
	{
		public record struct RentScope(T[] Rented, int Length) : IDisposable
		{
			public void Dispose()
			{
				ArrayPool<T>.Return(Rented);
			}
		}

		private class ArrayLengthComparer : IComparer<T[]>
		{
			public static readonly ArrayLengthComparer Instance = new ArrayLengthComparer();

			public int Compare(T[]? x, T[]? y)
			{
				if (x == null)
				{
					return (y != null) ? (-1) : 0;
				}
				if (y == null)
				{
					return 1;
				}
				return x.Length - y.Length;
			}
		}

		private static List<T[]> allArrays = new List<T[]>();

		private static List<T[]> freeArrays = new List<T[]>();

		public static T[] Rent(int length, bool allowOversized = false)
		{
			int num = BinarySearch(freeArrays, length);
			if (num == freeArrays.Count)
			{
				return CreateArray(length);
			}
			T[] array = freeArrays[num];
			if (!allowOversized && array.Length != length)
			{
				return CreateArray(length);
			}
			freeArrays.RemoveAt(num);
			return array;
		}

		public static void Return(T[] arr)
		{
			if (!allArrays.Contains(arr))
			{
				throw new InvalidOperationException("Do not return an array you have created! Only return rented arrays!");
			}
			if (freeArrays.Contains(arr))
			{
				throw new InvalidOperationException("You cannot return an array that hasn't been rented, or you can't return an array twice!");
			}
			int idx = BinarySearch(freeArrays, arr.Length);
			InsertOrAppend(freeArrays, idx, arr);
		}

		public static RentScope RentTemp(int length, bool allowOversized = false)
		{
			T[] rented = Rent(length, allowOversized);
			return new RentScope(rented, length);
		}

		private static int BinarySearch(List<T[]> orderedList, int desiredLength)
		{
			T[]? array = orderedList.FirstOrDefault();
			int num = ((array != null) ? array.Length : 0);
			foreach (T[] ordered in orderedList)
			{
				if (ordered.Length > num)
				{
					num = ordered.Length;
				}
				else if (ordered.Length < num)
				{
					JeviLib.Error("BinarySearch can only be performed on a list that is in order! The list will be sorted to rectify this.");
					JeviLib.Error("(Don't worry, unless you're JeviLib's developer, extraes, this isn't your fault, but it should be reported)");
					JeviLib.Error("Stack trace: " + new StackTrace(1));
					orderedList.Sort(ArrayLengthComparer.Instance);
					break;
				}
			}
			return BinarySearchImpl(orderedList, desiredLength, 0, orderedList.Count);
		}

		private static int BinarySearchImpl(List<T[]> orderedList, int desiredLength, int startIdx, int endIdx)
		{
			if (startIdx == endIdx)
			{
				return startIdx;
			}
			int num = (startIdx + endIdx) / 2;
			T[] array = orderedList[num];
			if (array.Length > desiredLength)
			{
				return BinarySearchImpl(orderedList, desiredLength, startIdx, num);
			}
			if (array.Length < desiredLength)
			{
				return BinarySearchImpl(orderedList, desiredLength, num + 1, endIdx);
			}
			return num;
		}

		private static void InsertOrAppend(List<T[]> list, int idx, T[] item)
		{
			if (idx == list.Count)
			{
				list.Add(item);
			}
			else
			{
				list.Insert(idx, item);
			}
		}

		private static T[] CreateArray(int length)
		{
			T[] array = new T[length];
			int idx = BinarySearch(allArrays, length);
			InsertOrAppend(allArrays, idx, array);
			return array;
		}
	}
	public static class AsyncExtensions
	{
		public static async Task<AssetBundle> ToTask(this AssetBundleCreateRequest abcr, PlayerLoopTiming timing = 8)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			Awaiter val = UnityAsyncExtensions.ToUniTask((AsyncOperation)(object)abcr, (IProgress<float>)null, timing, new CancellationToken()).GetAwaiter();
			if (!val.IsCompleted)
			{
				await val;
				object obj = default(object);
				val = (Awaiter)obj;
			}
			val.GetResult();
			return abcr.assetBundle;
		}

		public static UniTask ToUniTask(this AssetBundleRequest abr, PlayerLoopTiming timing = 8)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			return UnityAsyncExtensions.ToUniTask((AsyncOperation)(object)abr, (IProgress<float>)null, timing, new CancellationToken());
		}

		public static async Task RunOnFinish(this Task awaited, Action runAfter)
		{
			MethodBase caller = null;
			StackTrace st = new StackTrace(1);
			for (int i = 0; i < st.FrameCount; i++)
			{
				StackFrame frame = st.GetFrame(i);
				if (frame != null)
				{
					MethodBase mb = frame.GetMethod();
					if (mb != null && mb.DeclaringType != null && mb.DeclaringType.Assembly != typeof(object).Assembly && mb.DeclaringType != typeof(AsyncExtensions))
					{
						caller = mb;
						break;
					}
				}
			}
			try
			{
				await awaited;
				runAfter();
			}
			catch (Exception ex)
			{
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(110, 2);
				defaultInterpolatedStringHandler.AppendLiteral("(UNCAUGHT IN RELEASE) Exception while invoking method ");
				defaultInterpolatedStringHandler.AppendFormatted(GeneralExtensions.FullDescription((MethodBase)runAfter.Method));
				defaultInterpolatedStringHandler.AppendLiteral(" - RunOnFinish originally invoked from ");
				MethodBase methodBase = caller;
				defaultInterpolatedStringHandler.AppendFormatted((((object)methodBase != null) ? GeneralExtensions.FullDescription(methodBase) : null) ?? "<Unknown method>");
				defaultInterpolatedStringHandler.AppendLiteral("; Details below\n\t");
				JeviLib.Warn(defaultInterpolatedStringHandler.ToStringAndClear() + ex);
			}
		}

		public static async Task RunOnFinish<T>(this Task<T> awaited, Action<T> runAfter)
		{
			MethodBase caller = null;
			StackTrace st = new StackTrace(1);
			for (int i = 0; i < st.FrameCount; i++)
			{
				StackFrame frame = st.GetFrame(i);
				if (frame != null)
				{
					MethodBase mb = frame.GetMethod();
					if (mb != null && mb.DeclaringType != null && mb.DeclaringType.Assembly != typeof(object).Assembly && mb.DeclaringType != typeof(AsyncExtensions))
					{
						caller = mb;
						break;
					}
				}
			}
			try
			{
				await awaited;
				runAfter(awaited.Result);
			}
			catch (Exception ex)
			{
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(110, 2);
				defaultInterpolatedStringHandler.AppendLiteral("(UNCAUGHT IN RELEASE) Exception while invoking method ");
				defaultInterpolatedStringHandler.AppendFormatted(GeneralExtensions.FullDescription((MethodBase)runAfter.Method));
				defaultInterpolatedStringHandler.AppendLiteral(" - RunOnFinish originally invoked from ");
				MethodBase methodBase = caller;
				defaultInterpolatedStringHandler.AppendFormatted((((object)methodBase != null) ? GeneralExtensions.FullDescription(methodBase) : null) ?? "<Unknown method>");
				defaultInterpolatedStringHandler.AppendLiteral("; Details below\n\t");
				JeviLib.Warn(defaultInterpolatedStringHandler.ToStringAndClear() + ex);
			}
		}
	}
	public static class AsyncUtilities
	{
		internal struct MainThreadExecutor
		{
			public Action execute;

			public UniTaskCompletionSource completer;
		}

		public delegate void ForEachRefCallback<T>(ref T param);

		internal static ConcurrentQueue<MainThreadExecutor> mainThreadCallbacks = new ConcurrentQueue<MainThreadExecutor>();

		public static async Task ForEachTimeSlice<T>(IEnumerable<T> collection, Action<T> whatToDo, float msPerTick = 1f, PlayerLoopTiming timing = 8)
		{
			//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)
			Stopwatch sw = Stopwatch.StartNew();
			TimeSpan ms = TimeSpan.FromMilliseconds(msPerTick);
			foreach (T item in collection)
			{
				whatToDo(item);
				if (sw.Elapsed > ms)
				{
					await UniTask.Yield(timing);
					sw.Restart();
				}
			}
		}

		public static async Task RefForEachTimeSlice<T>(T[] array, ForEachRefCallback<T> whatToDo, float msPerTick = 1f, PlayerLoopTiming timing = 8)
		{
			//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)
			Stopwatch sw = Stopwatch.StartNew();
			TimeSpan ms = TimeSpan.FromMilliseconds(msPerTick);
			for (int i = 0; i < array.Length; i++)
			{
				whatToDo(ref array[i]);
				if (sw.Elapsed > ms)
				{
					await UniTask.Yield(timing);
					sw.Restart();
				}
			}
		}

		public static async Task ForTimeSlice(int start, int approach, Action<int> whatToDo, float msPerFrame = 1f, PlayerLoopTiming timing = 8)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (start == approach)
			{
				return;
			}
			Stopwatch sw = Stopwatch.StartNew();
			TimeSpan ms = TimeSpan.FromMilliseconds(msPerFrame);
			int incOrDecBy = Math.Sign(approach - start);
			for (int i = 0; i != approach; i += incOrDecBy)
			{
				whatToDo(i);
				if (sw.Elapsed > ms)
				{
					await UniTask.Yield(timing);
					sw.Restart();
				}
			}
		}

		public static async Task ForTimeSlice(int start, int approach, Func<int, Task> whatToDo, float msPerFrame = 1f, PlayerLoopTiming timing = 8)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (start == approach)
			{
				return;
			}
			Stopwatch sw = Stopwatch.StartNew();
			TimeSpan ms = TimeSpan.FromMilliseconds(msPerFrame);
			int incOrDecBy = Math.Sign(approach - start);
			for (int i = 0; i != approach; i += incOrDecBy)
			{
				await whatToDo(i);
				if (sw.Elapsed > ms)
				{
					await UniTask.Yield(timing);
					sw.Restart();
				}
			}
		}

		public static UniTask ToUniTask(AsyncOperation ao, PlayerLoopTiming timing = 8)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			return UnityAsyncExtensions.ToUniTask(ao, (IProgress<float>)null, timing, new CancellationToken());
		}

		public static UniTask RunOnMainThread(Action fun)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			MainThreadExecutor mainThreadExecutor = default(MainThreadExecutor);
			mainThreadExecutor.completer = new UniTaskCompletionSource();
			mainThreadExecutor.execute = fun;
			MainThreadExecutor item = mainThreadExecutor;
			mainThreadCallbacks.Enqueue(item);
			return item.completer.Task;
		}

		public static async Task<Exception?> WrapNoThrow(Func<Task> taskReturner)
		{
			try
			{
				await taskReturner();
				return null;
			}
			catch (Exception result)
			{
				return result;
			}
		}

		public static async Task<Exception?> WrapNoThrow<TParam1>(Func<TParam1, Task> taskReturner, TParam1 param1)
		{
			try
			{
				await taskReturner(param1);
				return null;
			}
			catch (Exception result)
			{
				return result;
			}
		}

		public static async Task<Exception?> WrapNoThrow<TParam1, TParam2>(Func<TParam1, TParam2, Task> taskReturner, TParam1 param1, TParam2 param2)
		{
			try
			{
				await taskReturner(param1, param2);
				return null;
			}
			catch (Exception result)
			{
				return result;
			}
		}

		public static async Task<Exception?> WrapNoThrow<TParam1, TParam2, TParam3>(Func<TParam1, TParam2, TParam3, Task> taskReturner, TParam1 param1, TParam2 param2, TParam3 param3)
		{
			try
			{
				await taskReturner(param1, param2, param3);
				return null;
			}
			catch (Exception result)
			{
				return result;
			}
		}

		public static async Task<OneOf<TRes, Exception>> WrapNoThrowWithResult<TRes>(Func<Task<TRes>> taskReturner)
		{
			try
			{
				return new OneOf<TRes, Exception>(await taskReturner());
			}
			catch (Exception ex2)
			{
				Exception ex = ex2;
				return new OneOf<TRes, Exception>(ex, taskReturner.Method);
			}
		}

		public static async Task<OneOf<TRes, Exception>> WrapNoThrowWithResult<TParam1, TRes>(Func<TParam1, Task<TRes>> taskReturner, TParam1 param1)
		{
			try
			{
				return new OneOf<TRes, Exception>(await taskReturner(param1));
			}
			catch (Exception ex2)
			{
				Exception ex = ex2;
				return new OneOf<TRes, Exception>(ex, taskReturner.Method);
			}
		}

		public static async Task<OneOf<TRes, Exception>> WrapNoThrowWithResult<TParam1, TParam2, TRes>(Func<TParam1, TParam2, Task<TRes>> taskReturner, TParam1 param1, TParam2 param2)
		{
			try
			{
				return new OneOf<TRes, Exception>(await taskReturner(param1, param2));
			}
			catch (Exception ex2)
			{
				Exception ex = ex2;
				return new OneOf<TRes, Exception>(ex, taskReturner.Method);
			}
		}

		public static async Task<OneOf<TRes, Exception>> WrapNoThrowWithResult<TParam1, TParam2, TParam3, TRes>(Func<TParam1, TParam2, TParam3, Task<TRes>> taskReturner, TParam1 param1, TParam2 param2, TParam3 param3)
		{
			try
			{
				return new OneOf<TRes, Exception>(await taskReturner(param1, param2, param3));
			}
			catch (Exception ex2)
			{
				Exception ex = ex2;
				return new OneOf<TRes, Exception>(ex, taskReturner.Method);
			}
		}
	}
	public sealed class BundledAsset<T> where T : Object
	{
		private static Dictionary<AssetBundle, string[]> assetPaths = new Dictionary<AssetBundle, string[]>(UnityObjectComparer<AssetBundle>.Instance);

		public readonly string path;

		private AssetBundle? bundle;

		private readonly bool hide;

		private T? asset;

		public BundledAsset(AssetBundle bundle, string path, bool hideWhenPersisting = true, bool loadImmediately = false)
		{
			if (((Object?)(object)bundle).INOC())
			{
				throw new ArgumentNullException("bundle");
			}
			if (string.IsNullOrWhiteSpace(path))
			{
				throw new ArgumentException("Asset path cannot be null, empty, or only whitespace.", "path");
			}
			this.bundle = bundle;
			this.path = path;
			hide = hideWhenPersisting;
			((Object)(object)bundle).Persist();
			if (loadImmediately)
			{
				Get();
			}
		}

		public BundledAsset(string path, bool hideWhenPersisting = true)
		{
			this.path = path;
			hide = hideWhenPersisting;
		}

		public void Bind(AssetBundle bundle, bool loadImmediately = false)
		{
			if (!((Object?)(object)this.bundle).INOC())
			{
				JeviLib.Warn("It's not recommended to live-switch the AssetBundle reference of a bundled asset! Asset path: " + path);
			}
			if (((Object?)(object)bundle).INOC())
			{
				throw new ArgumentNullException("bundle");
			}
			this.bundle = bundle;
			((Object)(object)bundle).Persist();
			if (loadImmediately)
			{
				Get();
			}
		}

		public Task<T> BindAsync(AssetBundle bundle)
		{
			if (!((Object?)(object)this.bundle).INOC())
			{
				JeviLib.Warn("It's not recommended to live-switch the AssetBundle reference of a bundled asset! Asset path: " + path);
			}
			if (((Object?)(object)bundle).INOC())
			{
				throw new ArgumentNullException("bundle");
			}
			this.bundle = bundle;
			((Object)(object)bundle).Persist();
			return GetAsync();
		}

		public T Get()
		{
			if (((Object?)(object)asset).INOC())
			{
				if (((Object?)(object)bundle).INOC())
				{
					throw new InvalidOperationException("BundledAsset be associated with an existing assetbundle! You have either failed to bind an AssetBundle to this asset or the provided AssetBundle was collected! Asset path: " + path);
				}
				asset = ((Il2CppObjectBase)bundle.LoadAsset(path)).Cast<T>();
				((Object)(object)asset).Persist(hide);
			}
			return asset;
		}

		public async Task<T> GetAsync()
		{
			if (((Object?)(object)asset).INOC())
			{
				if (((Object?)(object)bundle).INOC())
				{
					throw new InvalidOperationException("BundledAsset be associated with an existing assetbundle! You have either failed to bind an AssetBundle to this asset or the provided AssetBundle was collected! Asset path: " + path);
				}
				if (!GetPaths().Contains(path.ToLower()))
				{
					string[] paths = GetPaths();
					for (int i = 0; i < paths.Length; i++)
					{
						JeviLib.Log(string.Concat(str3: paths[i], str0: "Bundle ", str1: ((Object)bundle).name, str2: " - "));
					}
					throw new InvalidOperationException($"Assetbundle '{((Object)bundle).name}' does not contain any asset at path {path} - Logged all asset paths");
				}
				AssetBundleRequest abr = bundle.LoadAssetAsync(path);
				Awaiter val = abr.ToUniTask((PlayerLoopTiming)8).GetAwaiter();
				if (!val.IsCompleted)
				{
					await val;
					object obj2 = default(object);
					val = (Awaiter)obj2;
				}
				val.GetResult();
				if ((Object)(object)((Il2CppObjectBase)abr.asset).TryCast<T>() == (Object)null)
				{
					throw new InvalidCastException("Asset type " + ((Object)abr.asset).GetIl2CppType().FullName + " does not match " + typeof(T).FullName);
				}
				asset = ((Il2CppObjectBase)abr.asset).Cast<T>();
				((Object)(object)asset).Persist(hide);
			}
			return asset;
		}

		private string[] GetPaths()
		{
			if (((Object?)(object)bundle).INOC())
			{
				throw new InvalidOperationException("AssetBundle is null! Cannot retrieve asset paths.");
			}
			if (assetPaths.TryGetValue(bundle, out string[] value))
			{
				return value;
			}
			value = Il2CppArrayBase<string>.op_Implicit((Il2CppArrayBase<string>)(object)bundle.GetAllAssetNames());
			assetPaths.Add(bundle, value);
			return value;
		}

		public static implicit operator T(BundledAsset<T> bundledAsset)
		{
			return bundledAsset.Get();
		}
	}
	public static class ByteArrayPool
	{
		public record struct RentedVector(byte[] Rented) : IDisposable
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public void Dispose()
			{
				ReturnVector(Rented);
			}
		}

		private static List<byte[]> vectorArrays = new List<byte[]>();

		public static byte[] RentVector()
		{
			if (vectorArrays.Count == 0)
			{
				return new byte[12];
			}
			byte[] result = vectorArrays[0];
			vectorArrays.RemoveAt(0);
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static RentedVector RentVectorTemp()
		{
			return new RentedVector(RentVector());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ReturnVector(byte[] vectorArray)
		{
			if (vectorArray.Length != 12)
			{
				throw new Exception("Cannot return an array that is not the right size! This method is only intended to be used to return arrays that have been rented using RentVector.");
			}
			if (vectorArrays.Contains(vectorArray))
			{
				throw new Exception("That array has already been returned! Do not double-return an array!");
			}
			vectorArrays.Add(vectorArray);
		}

		public static byte[] Rent(int length, bool allowOversized = false)
		{
			return ArrayPool<byte>.Rent(length, allowOversized);
		}

		public static ArrayPool<byte>.RentScope RentTemp(int length, bool allowOversized = false)
		{
			return ArrayPool<byte>.RentTemp(length, allowOversized);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Return(byte[] nonVectorArray)
		{
			if (nonVectorArray.Length == 12)
			{
				JeviLib.Warn("This array is the size of a Vector3. Did you mean to use ReturnVector? For info, see call stack below:");
				JeviLib.Warn(new StackTrace(1));
			}
			ArrayPool<byte>.Return(nonVectorArray);
		}
	}
	public static class Const
	{
		public const int SizeV3 = 12;

		public const float FPI = (float)Math.PI;

		public const BindingFlags AllBindingFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public const string RigManagerName = "[RigManager (Blank)]";

		public const string UrpLitName = "Universal Render Pipeline/Lit (PBR Workflow)";

		public const string LITMAS_NAME = "SLZ/LitMAS/LitMAS Opaque";

		public const string UrpLitMainTexName = "_BaseMap";

		public const string MOD_STATS_DOMAIN = "https://stats.extraes.xyz/";

		public static readonly int UrpLitMainTexID = Shader.PropertyToID("_BaseMap");
	}
	public sealed class DebugLineCounter : IDisposable
	{
		public enum Kind
		{
			CHECKPOINT_COUNTER,
			LINE_NUMBER
		}

		private readonly Instance logger;

		private readonly string whatDoing;

		private readonly Kind kind;

		private bool success;

		private int num;

		public DebugLineCounter(Instance logger, Kind kind, string doingWhat)
		{
			this.logger = logger;
			this.kind = kind;
			whatDoing = doingWhat;
		}

		public void UpdateProgress([CallerLineNumber] int progressNum = -1)
		{
			if (kind == Kind.CHECKPOINT_COUNTER)
			{
				num++;
			}
			else
			{
				num = progressNum;
			}
		}

		public void Success()
		{
			success = true;
		}

		public void Dispose()
		{
			if (!success)
			{
				switch (kind)
				{
				case Kind.CHECKPOINT_COUNTER:
					logger.Error($"Reached the {num}-th checkpoint before unexpectedly erroring during {whatDoing}! If there was no error thrown, be sure to call {"DebugLineCounter"}.{"Success"}().");
					break;
				case Kind.LINE_NUMBER:
					logger.Error($"Got past line {num} before unexpectedly erroring during ({whatDoing})! If there was no error thrown, be sure to call {"DebugLineCounter"}.{"Success"}().");
					break;
				}
			}
		}
	}
	[Serializable]
	public abstract class Il2CppMismatchException : Exception
	{
		internal Il2CppMismatchException()
		{
		}

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

		internal Il2CppMismatchException(string message, Exception inner)
			: base(message, inner)
		{
		}

		internal Il2CppMismatchException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	[Serializable]
	public sealed class Il2CppConversionException : Il2CppMismatchException
	{
		internal Il2CppConversionException(Type monoType, Type il2cppType)
			: this($"Mono type '{monoType.FullName}' cannot be converted between its IL2CPP equivalent '{il2cppType.FullName}'.")
		{
		}

		internal Il2CppConversionException()
		{
		}

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

		internal Il2CppConversionException(string message, Exception inner)
			: base(message, inner)
		{
		}

		internal Il2CppConversionException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	public static class Extensions
	{
		public static void Reset(this Transform transform)
		{
			//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_0013: 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)
			transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
			transform.localScale = Vector3.one;
			transform.localPosition = Vector3.zero;
			transform.localRotation = Quaternion.identity;
		}

		public static bool InHierarchyOf(this Transform t, string parentName)
		{
			if (((Object)t).name == parentName)
			{
				return true;
			}
			if ((Object)(object)t.parent == (Object)null)
			{
				return false;
			}
			t = t.parent;
			return t.InHierarchyOf(parentName);
		}

		public static bool IsChildOfRigManager(this Transform t)
		{
			return t.InHierarchyOf("[RigManager (Blank)]");
		}

		public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> fun)
		{
			foreach (T item in sequence)
			{
				fun(item);
			}
		}

		public static void ForEachSafe<T>(this IEnumerable<T> sequence, Action<T> fun)
		{
			foreach (T item in sequence)
			{
				try
				{
					fun(item);
				}
				catch (Exception obj)
				{
					JeviLib.Warn("Exception whilst safe foreaching - still continuing though. The exception is below.");
					JeviLib.Warn(obj);
				}
			}
		}

		public static float Interpolate(KeyValuePair<float, float> kvp, float time)
		{
			return (kvp.Key, kvp.Value).Interpolate(time);
		}

		public static float Interpolate(this (float, float) tuple, float time, bool ease = true)
		{
			float num = Mathf.Clamp(time, 0f, 1f);
			float num2 = tuple.Item2 - tuple.Item1;
			if (ease)
			{
				float num3 = (0f - (Mathf.Cos(num * (float)Math.PI) - 1f)) / 2f;
				return tuple.Item1 + num2 * num3;
			}
			return tuple.Item1 + num2 * num;
		}

		public static void Destroy(this GameObject go)
		{
			Object.Destroy((Object)(object)go);
		}

		public static void UseEmbeddedResource(this Assembly assembly, string resourcePath, Action<byte[]> whatToDoWithResource)
		{
			string resourcePath2 = resourcePath;
			string[] manifestResourceNames = assembly.GetManifestResourceNames();
			if (!manifestResourceNames.Any((string s) => s == resourcePath2))
			{
				string[] array = manifestResourceNames;
				foreach (string str in array)
				{
					JeviLib.Log(str);
				}
				throw new FileNotFoundException("The specified resource was not found in the Assembly " + assembly.GetName().Name + ". All resource paths have been logged, use these to get an existent resource path.", resourcePath2);
			}
			whatToDoWithResource(assembly.GetEmbeddedResource(resourcePath2));
		}

		public static byte[] GetEmbeddedResource(this Assembly assembly, string resourcePath)
		{
			string resourcePath2 = resourcePath;
			string[] manifestResourceNames = assembly.GetManifestResourceNames();
			if (!manifestResourceNames.Any((string s) => s == resourcePath2))
			{
				string[] array = manifestResourceNames;
				foreach (string str in array)
				{
					JeviLib.Log(str);
				}
				throw new FileNotFoundException("The specified resource was not found in the Assembly " + assembly.GetName().Name + ". All resource paths have been logged, use these to get an existent resource path.", resourcePath2);
			}
			using Stream stream = assembly.GetManifestResourceStream(resourcePath2) ?? throw new NullReferenceException();
			using MemoryStream memoryStream = new MemoryStream((int)stream.Length);
			stream.CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		public static T Random<T>(this IEnumerable<T> sequence)
		{
			return sequence.ElementAt(Random.Range(0, sequence.Count()));
		}

		public static T Random<T>(this T[] sequence)
		{
			return sequence[Random.Range(0, sequence.Length)];
		}

		public static string GetFullPath(this Transform t)
		{
			if (((Object?)(object)t).INOC())
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append('/');
			stringBuilder.Append(((Object)t).name);
			while ((Object)(object)t.parent != (Object)null)
			{
				t = t.parent;
				stringBuilder.Insert(0, ((Object)t).name);
				stringBuilder.Insert(0, '/');
			}
			return stringBuilder.ToString();
		}

		public unsafe static byte[] ToBytes(this Vector3 vec)
		{
			//IL_0023: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = new byte[12];
			fixed (byte* ptr = array)
			{
				*(float*)ptr = vec.x;
				*(float*)(ptr + 4) = vec.y;
				*(float*)(ptr + 8) = vec.z;
			}
			return array;
		}

		public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> arrarr)
		{
			IEnumerable<T> enumerable = new List<T>();
			foreach (IEnumerable<T> item in arrarr)
			{
				enumerable = enumerable.Concat(item);
			}
			return enumerable;
		}

		public static byte[] Flatten(this byte[][] arrarr)
		{
			int num = 0;
			int num2 = arrarr.Sum((byte[] arr) => arr.Length);
			byte[] array = new byte[num2];
			for (int i = 0; i < arrarr.Length; i++)
			{
				Buffer.BlockCopy(arrarr[i], 0, array, num, arrarr[i].Length);
				num += arrarr[i].Length;
			}
			return array;
		}

		public static string Join<T>(this IEnumerable<T> seq, string delim = ", ")
		{
			return string.Join(delim, seq);
		}

		public static IEnumerable<IEnumerable<T>> SplitList<T>(this IEnumerable<T> source, int maxPerList)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			IList<T> source2 = (source as IList<T>) ?? source.ToList();
			if (!source2.Any())
			{
				return new List<IEnumerable<T>>();
			}
			return new List<IEnumerable<T>> { source2.Take(maxPerList) }.Concat(source2.Skip(maxPerList).SplitList(maxPerList));
		}

		public static byte[] SerializePosRot(this Transform t)
		{
			//IL_000a: 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)
			byte[] array = new byte[24];
			t.position.ToBytes().CopyTo(array, 0);
			Quaternion rotation = t.rotation;
			((Quaternion)(ref rotation)).eulerAngles.ToBytes().CopyTo(array, 12);
			return array;
		}

		public static void DeserializePosRot(this Transform t, byte[] serializedPosRot, bool dontWarn = false)
		{
			//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_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_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)
			if (!dontWarn && serializedPosRot.Length != 24)
			{
				JeviLib.Warn("Deserializing posrot of unexpected length " + serializedPosRot.Length + "!!! This could be bad!!!");
			}
			Vector3 val = Utilities.DebyteV3(serializedPosRot);
			Quaternion val2 = Quaternion.Euler(Utilities.DebyteV3(serializedPosRot, 12));
			t.SetPositionAndRotation(val, val2);
		}

		public static string GetString(this Encoding enc, byte[] bytes, int startOffset)
		{
			return enc.GetString(bytes, startOffset, bytes.Length - startOffset);
		}

		public static IEnumerator<Transform> GetEnumerator(this GameObject go)
		{
			Transform t = go.transform;
			int childCount = t.childCount;
			for (int i = 0; i < childCount; i++)
			{
				if (t.childCount != childCount)
				{
					throw new InvalidOperationException("The child count of a transform should not be modified while it is being enumerated!");
				}
				yield return t.GetChild(i);
			}
		}

		public static IEnumerable<(T1, T2)> Zip<T1, T2>(this IEnumerable<T1> sequence, IEnumerable<T2> otherSeq, bool throwOnUnequalCounts = true)
		{
			if (throwOnUnequalCounts && sequence.Count() != otherSeq.Count())
			{
				throw new IndexOutOfRangeException("Zipped enumerables must have the same length otherwise the operation will go out of bounds!");
			}
			return sequence.Zip(otherSeq, (T1 x, T2 y) => (x, y));
		}

		public static (T1, T2)[] Zip<T1, T2>(this T1[] arr, T2[] otherArr)
		{
			if (arr.Length != otherArr.Length)
			{
				throw new IndexOutOfRangeException("Zipped arrays must have the same length otherwise the operation will go out of bounds!");
			}
			(T1, T2)[] array = new(T1, T2)[arr.Length];
			for (int i = 0; i < arr.Length; i++)
			{
				array[i] = (arr[i], otherArr[i]);
			}
			return array;
		}

		public static IEnumerable<T> NoNull<T>(this IEnumerable<T?> sequence)
		{
			return sequence.Where<T>((T o) => o != null);
		}

		public static IEnumerable<T> NoUNull<T>(this IEnumerable<T> sequence) where T : Object
		{
			return sequence.Where((T o) => !((Object?)(object)o).INOC());
		}

		public static IEnumerable<IEnumerable<T>> SplitByProcessors<T>(this IEnumerable<T> sequence, bool onePerCore = false)
		{
			int num = SystemInfo.processorCount;
			if (onePerCore)
			{
				num /= 2;
			}
			int maxPerList = Mathf.CeilToInt((float)sequence.Count() / (float)num);
			return sequence.SplitList(maxPerList);
		}

		public static T FirstMin<T>(this IEnumerable<T> sequence, Func<T, int> selector)
		{
			Func<T, int> selector2 = selector;
			int min = sequence.Min(selector2);
			return sequence.First((T t) => selector2(t) == min);
		}

		public static MethodInfo? GetMethodEasy(this Type type, string methodName, Type[]? paramTypes = null)
		{
			string methodName2 = methodName;
			if (paramTypes == null)
			{
				MethodInfo[] array = (from m in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
					where m.Name == methodName2
					select m).ToArray();
				if (array.Length == 0)
				{
					return null;
				}
				return array.FirstMin((MethodInfo m) => m.GetParameters().Length);
			}
			return type.GetMethod(methodName2, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any, paramTypes, null);
		}

		public static MethodInfo[] GetMethods(this Type type, string methodName)
		{
			string methodName2 = methodName;
			return (from MethodInfo method in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
				where method.Name == methodName2
				select method).ToArray();
		}

		public static void Add<T1, T2>(this List<(T1, T2)> list, T1 item1, T2 item2)
		{
			list.Add((item1, item2));
		}

		public static MethodInfo? ToInfo(this MethodBase mb)
		{
			return mb.DeclaringType?.GetMethod(mb.Name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		}

		[DebuggerStepThrough]
		public static bool INOC([NotNullWhen(false)] this Object? obj)
		{
			if (obj == null || ((Il2CppObjectBase)obj).WasCollected)
			{
				return true;
			}
			try
			{
				return obj == (Object)null;
			}
			catch
			{
			}
			IntPtr intPtr = IntPtr.Zero;
			try
			{
				intPtr = ((Il2CppObjectBase)obj).Pointer;
			}
			catch
			{
			}
			return intPtr == IntPtr.Zero;
		}

		public static string ToString(this JevilBarcode jBarcode)
		{
			return Barcodes.ToBarcodeString(jBarcode);
		}

		public static void Spawn(this JevilBarcode spawnableBarcode, Vector3 position, Quaternion rotation)
		{
			//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)
			Barcodes.SpawnAsync(spawnableBarcode, position, rotation);
		}

		public static void AddVelocityChange(this PhysicsRig physRig, Vector3 velocity)
		{
			//IL_000c: 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_0032: 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_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_0075: 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)
			physRig.torso.rbChest.AddForce(velocity, (ForceMode)2);
			physRig.torso.rbPelvis.AddForce(velocity, (ForceMode)2);
			physRig.torso.rbSpine.AddForce(velocity, (ForceMode)2);
			physRig.torso.rbHead.AddForce(velocity, (ForceMode)2);
			physRig.rbFeet.AddForce(velocity, (ForceMode)2);
			physRig.rbKnee.AddForce(velocity, (ForceMode)2);
			try
			{
				physRig.leftHand.rb.AddForce(velocity, (ForceMode)2);
				physRig.rightHand.rb.AddForce(velocity, (ForceMode)2);
			}
			catch
			{
			}
		}

		public static void Spawn(this SpawnableCrate crate, Vector3 pos, Quaternion rot)
		{
			//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)
			Spawnable val = Barcodes.ToSpawnable(((Scannable)crate).Barcode.ID);
			AssetSpawner.Spawn(val, pos, rot, Utilities.NulledNullable<Vector3>(), (Transform)null, false, Utilities.NulledNullable<int>(), (Action<GameObject>)null, (Action<GameObject>)null);
		}

		public static UniTask<Poolee> SpawnAsync(this SpawnableCrate crate, Vector3 pos, Quaternion rot)
		{
			//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)
			Spawnable val = Barcodes.ToSpawnable(((Scannable)crate).Barcode.ID);
			return AssetSpawner.SpawnAsync(val, pos, rot, Utilities.NulledNullable<Vector3>(), (Transform)null, false, Utilities.NulledNullable<int>(), (Action<GameObject>)null, (Action<GameObject>)null, (Action<GameObject>)null);
		}

		public static void Spawn(this Spawnable spawnable, Vector3 pos, Quaternion rot, bool? enableOnSpawn = null)
		{
			//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)
			Action<GameObject> action = null;
			if (enableOnSpawn.HasValue)
			{
				action = delegate(GameObject go)
				{
					go.SetActive(enableOnSpawn.Value);
				};
			}
			AssetSpawner.Spawn(spawnable, pos, rot, Utilities.NulledNullable<Vector3>(), (Transform)null, false, Utilities.NulledNullable<int>(), Action<GameObject>.op_Implicit(action), (Action<GameObject>)null);
		}

		public static UniTask<Poolee> SpawnAsync(this Spawnable spawnable, Vector3 pos, Quaternion rot)
		{
			//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 AssetSpawner.SpawnAsync(spawnable, pos, rot, Utilities.NulledNullable<Vector3>(), (Transform)null, false, Utilities.NulledNullable<int>(), (Action<GameObject>)null, (Action<GameObject>)null, (Action<GameObject>)null);
		}

		public static void Dupe(this Poolee asspoole, Vector3 pos, Quaternion rot)
		{
			//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)
			asspoole.SpawnableCrate.Spawn(pos, rot);
		}

		public static IEnumerable<KeyValuePair<T1, T2>> MonoEnumerable<T1, T2>(this Dictionary<T1, T2> enumerable)
		{
			Enumerator<T1, T2> enumerator = enumerable.GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValuePair<T1, T2> item = enumerator.Current;
				yield return new KeyValuePair<T1, T2>(item.Key, item.Value);
			}
		}

		public static IEnumerable<T> MonoEnumerable<T>(this List<T> enumerable)
		{
			Enumerator<T> enumerator = enumerable.GetEnumerator();
			while (enumerator.MoveNext())
			{
				yield return enumerator.Current;
			}
		}

		public static FieldType? GetStatic<FieldType>(this AndroidJavaObject ajo, string fieldName)
		{
			IntPtr fieldID = AndroidJNIHelper.GetFieldID<FieldType>(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldName, true);
			if (typeof(FieldType).IsPrimitive)
			{
				if (typeof(FieldType) == typeof(int))
				{
					return (FieldType)(object)AndroidJNISafe.GetStaticIntField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				}
				if (typeof(FieldType) == typeof(bool))
				{
					return (FieldType)(object)AndroidJNISafe.GetStaticBooleanField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				}
				if (typeof(FieldType) == typeof(byte))
				{
					JeviLib.Warn("Field type <Byte> for Java get field call is obsolete, use field type <SByte> instead");
					return (FieldType)(object)AndroidJNISafe.GetStaticSByteField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				}
				if (typeof(FieldType) == typeof(sbyte))
				{
					return (FieldType)(object)AndroidJNISafe.GetStaticSByteField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				}
				if (typeof(FieldType) == typeof(short))
				{
					return (FieldType)(object)AndroidJNISafe.GetStaticShortField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				}
				if (typeof(FieldType) == typeof(long))
				{
					return (FieldType)(object)AndroidJNISafe.GetStaticLongField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				}
				if (typeof(FieldType) == typeof(float))
				{
					return (FieldType)(object)AndroidJNISafe.GetStaticFloatField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				}
				if (typeof(FieldType) == typeof(double))
				{
					return (FieldType)(object)AndroidJNISafe.GetStaticDoubleField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				}
				if (typeof(FieldType) == typeof(char))
				{
					return (FieldType)(object)AndroidJNISafe.GetStaticCharField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				}
				return default(FieldType);
			}
			if (typeof(FieldType) == typeof(string))
			{
				return (FieldType)(object)AndroidJNISafe.GetStaticStringField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
			}
			if (typeof(FieldType) == typeof(AndroidJavaClass))
			{
				IntPtr staticObjectField = AndroidJNISafe.GetStaticObjectField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				return (staticObjectField == IntPtr.Zero) ? default(FieldType) : ((FieldType)(object)AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(staticObjectField));
			}
			if (typeof(FieldType) == typeof(AndroidJavaObject))
			{
				IntPtr staticObjectField2 = AndroidJNISafe.GetStaticObjectField(GlobalJavaObjectRef.op_Implicit(ajo.m_jclass), fieldID);
				return (staticObjectField2 == IntPtr.Zero) ? default(FieldType) : ((FieldType)(object)AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(staticObjectField2));
			}
			if (typeof(FieldType).IsAssignableFrom(typeof(Array)))
			{
				throw new Il2CppConversionException("Arrays must be retrieved as their IL2CPP types, not their Mono domain types.");
			}
			if (AndroidReflection.IsAssignableFrom(Il2CppType.Of<Array>(), Il2CppType.Of<FieldType>()))
			{
				throw new Il2CppConversionException("Arrays cannot be retrieved. Too much wonk. If you wish to get arrays, implement it and test it.");
			}
			throw new Exception("JNI: Unknown field type '" + typeof(FieldType).ToString() + "'");
		}

		public static void Persist(this Object unityObj, bool hide = true)
		{
			unityObj.hideFlags = (HideFlags)(hide ? 61 : 32);
			Object.DontDestroyOnLoad(unityObj);
		}

		public static void Write(this Stream stream, byte[] arr)
		{
			stream.Write(arr, 0, arr.Length);
		}

		public static Task WriteAsync(this Stream stream, byte[] arr)
		{
			return stream.WriteAsync(arr, 0, arr.Length);
		}

		public static int FindIndexOf<T>(this IEnumerable<T> enumerator, T value)
		{
			int num = 0;
			foreach (T item in enumerator)
			{
				if (value == null && item == null)
				{
					return num;
				}
				if (value != null && item != null && value.Equals(item))
				{
					return num;
				}
				num++;
			}
			return -1;
		}

		public static int FindIndexOf<T>(this IEnumerable<T> enumerator, T value, IEqualityComparer<T> comparer)
		{
			int num = 0;
			foreach (T item in enumerator)
			{
				if (comparer.Equals(item, value))
				{
					return num;
				}
				num++;
			}
			return -1;
		}

		public static Nullable<T> ToIl2<T>(this T? nullable) where T : struct
		{
			Nullable<T> val = new Nullable<T>(nullable.GetValueOrDefault());
			val.hasValue = nullable.HasValue;
			return val;
		}
	}
	[Obsolete("Il2CppThreadScope is no longer recommended. If calling allocating native methods from an async method, use [assembly: Ungovernable(...)]. If explicitly creating threads, just call IL2CPP.il2cpp_thread_attach(IL2CPP.il2cpp_domain_get()). It's not an expensive call.")]
	public class Il2CppThreadScope : IDisposable
	{
		[ThreadStatic]
		internal static int usesOfThisThreadInIl2Cpp;

		[ThreadStatic]
		internal static IntPtr thisThreadInIl2Cpp;

		[ThreadStatic]
		private static int? managedThreadId;

		private int startingThread;

		public Il2CppThreadScope()
		{
			using (new ProfilingScope(((MelonBase)JeviLib.instance).LoggerInstance, ProfilingScope.ProfilingType.STOPWATCH_EXECUTION_TIME, "Thread attach"))
			{
				Enter();
			}
		}

		public async Task Await(Task task)
		{
			if (startingThread != managedThreadId)
			{
				throw new ThreadStateException("Il2CppThreadScope should stay on the same thread! This may be due to something being 'await'ed without using Il2CppThreadScope.Await.");
			}
			Exit();
			await task;
			Enter();
		}

		public async Task<T> Await<T>(Task<T> task)
		{
			if (startingThread != managedThreadId)
			{
				throw new ThreadStateException("Il2CppThreadScope should stay on the same thread! This may be due to something being 'await'ed without using Il2CppThreadScope.Await.");
			}
			Exit();
			await task;
			Enter();
			return task.Result;
		}

		public void Dispose()
		{
			if (startingThread != managedThreadId)
			{
				throw new ThreadStateException("Il2CppThreadScope should stay on the same thread! This may be due to something being 'await'ed.");
			}
			if (managedThreadId != JeviLib.unityMainThread)
			{
				Exit();
			}
		}

		private void Enter()
		{
			ThisThreadInUse();
			int valueOrDefault = managedThreadId.GetValueOrDefault();
			if (!managedThreadId.HasValue)
			{
				valueOrDefault = Environment.CurrentManagedThreadId;
				managedThreadId = valueOrDefault;
			}
			startingThread = managedThreadId.Value;
		}

		private void Exit()
		{
		}

		private static void ThisThreadInUse()
		{
			if (managedThreadId != JeviLib.unityMainThread)
			{
				usesOfThisThreadInIl2Cpp++;
				if (usesOfThisThreadInIl2Cpp == 1)
				{
					JeviLib.Log("Attaching IL2CPP to current thread");
					thisThreadInIl2Cpp = IL2CPP.il2cpp_thread_attach(IL2CPP.il2cpp_domain_get());
				}
			}
		}

		private static void ThisThreadNoLongerInUse()
		{
			if (managedThreadId != JeviLib.unityMainThread)
			{
				usesOfThisThreadInIl2Cpp--;
				if (usesOfThisThreadInIl2Cpp == 0)
				{
					JeviLib.Log("Detaching IL2CPP from current thread");
					IL2CPP.il2cpp_thread_detach(thisThreadInIl2Cpp);
					thisThreadInIl2Cpp = IntPtr.Zero;
				}
			}
		}
	}
	public static class Instances
	{
		public static readonly Dictionary<string, Assembly> namespaceToAssembly = new Dictionary<string, Assembly>();

		internal static int allPoolsVersion = -1;

		internal static IReadOnlyList<Pool> allPools;

		internal static List<IDictionary> instanceCachesToClear = new List<IDictionary>();

		public static BodyVitals Player_BodyVitals { get; internal set; }

		public static RigManager Player_RigManager { get; internal set; }

		public static PhysicsRig Player_PhysicsRig { get; internal set; }

		public static Player_Health Player_Health { get; internal set; }

		public static Camera SpectatorCam { get; internal set; }

		public static Camera InHeadsetCam { get; internal set; }

		public static Camera[] RigCameras { get; internal set; }

		public static Audio2dManager Audio2dManager { get; internal set; }

		public static AudioMixerGroup MusicMixer { get; internal set; }

		public static AudioMixerGroup SFXMixer { get; internal set; }

		public static AudioPlayer MusicPlayer { get; internal set; }

		public static AudioPlayer SFXPlayer { get; internal set; }

		public static Object NeverCancel { get; internal set; }

		public static IReadOnlyCollection<Pool> AllPools
		{
			get
			{
				List<Pool> poolList = AssetSpawner._instance._poolList;
				if (poolList._version == allPoolsVersion)
				{
					return allPools;
				}
				allPools = ((IEnumerable<Pool>)poolList.ToArray()).ToList().AsReadOnly();
				allPoolsVersion = poolList._version;
				return allPools;
			}
		}
	}
	public static class Instances<T> where T : Component
	{
		private static T? mostRecent;

		private static bool triedAutocache;

		private static bool isAutocaching;

		private static readonly Dictionary<GameObject, T> cache;

		private static readonly HarmonyMethod autoCacheHMethod;

		public static T? MostRecentlyCached => ((Object?)(object)mostRecent).INOC() ? default(T) : mostRecent;

		public static bool ClearOnSceneInit
		{
			get
			{
				return Instances.instanceCachesToClear.Contains(cache);
			}
			set
			{
				bool clearOnSceneInit = ClearOnSceneInit;
				if (value && !clearOnSceneInit)
				{
					Instances.instanceCachesToClear.Add(cache);
				}
				else if (clearOnSceneInit)
				{
					Instances.instanceCachesToClear.Remove(cache);
				}
			}
		}

		static Instances()
		{
			triedAutocache = false;
			isAutocaching = false;
			cache = new Dictionary<GameObject, T>(UnityObjectComparer<GameObject>.Instance);
			autoCacheHMethod = Utilities.ToHarmony(new Action<T>(AutoCachePatch));
			JeviLib.Log("Initialized Instances Cache of " + typeof(T).Name);
			Instances.instanceCachesToClear.Add(cache);
		}

		public static bool Remove(GameObject go)
		{
			return cache.Remove(go);
		}

		public static T GetOrAdd(GameObject go)
		{
			T val = Get(go);
			if ((Object)(object)val == (Object)null)
			{
				val = go.AddComponent<T>();
				cache[go] = val;
				mostRecent = val;
			}
			return val;
		}

		public static bool AddManual(GameObject go, T component)
		{
			if ((Object)(object)go == (Object)null)
			{
				return false;
			}
			bool result = cache.ContainsKey(go);
			cache[go] = component;
			return result;
		}

		public static T? Get(GameObject go)
		{
			if (cache.TryGetValue(go, out var value))
			{
				return value;
			}
			T component = go.GetComponent<T>();
			if ((Object)(object)component != (Object)null)
			{
				cache[go] = component;
				mostRecent = component;
			}
			return component;
		}

		public static bool TryGetFromCache(GameObject go, [NotNullWhen(true)] out T? component)
		{
			if (((Object?)(object)go).INOC())
			{
				component = default(T);
				return false;
			}
			return cache.TryGetValue(go, out component);
		}

		public static T? Get(Transform t)
		{
			return Get(((Component)t).gameObject);
		}

		public static bool Has(GameObject go)
		{
			return cache.ContainsKey(go);
		}

		public static bool Has(Transform t)
		{
			return Has(((Component)t).gameObject);
		}

		public static Transform? HasUpwards(Transform t)
		{
			if (Has(((Component)t).gameObject))
			{
				return t;
			}
			if ((Object)(object)t.parent == (Object)null)
			{
				return null;
			}
			return HasUpwards(t.parent);
		}

		private static T? GetUpwardsImpl(Transform t)
		{
			T val = Get(t);
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			if ((Object)(object)t.parent == (Object)null)
			{
				return default(T);
			}
			return GetUpwardsImpl(t.parent);
		}

		public static T? GetUpwards(Transform t)
		{
			Transform val = HasUpwards(t);
			if ((Object)(object)val != (Object)null)
			{
				return Get(((Component)val).gameObject);
			}
			return GetUpwardsImpl(t);
		}

		public static T? GetUpwards(GameObject go)
		{
			return GetUpwards(go.transform);
		}

		public static T? GetInImmediateChildren(GameObject go, bool cacheOnly = true)
		{
			T val = default(T);
			foreach (Transform item in go)
			{
				val = ((!cacheOnly || !Has(item)) ? Get(item) : Get(item));
				if ((Object)(object)val != (Object)null)
				{
					break;
				}
			}
			return val;
		}

		public static bool TryAutoCache()
		{
			if (triedAutocache)
			{
				return isAutocaching;
			}
			triedAutocache = true;
			string name = typeof(T).Assembly.GetName().Name;
			if (name != null && name.StartsWith("UnityEngine"))
			{
				JeviLib.Warn($"The component {typeof(T).FullName} from the engine assembly {name} is likely implemented exclusively in native code! It likely will not be able to be autocached as a result.");
			}
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
			Type typeFromHandle = typeof(T);
			MethodInfo methodInfo = typeFromHandle.GetMethod("Awake", bindingAttr) ?? typeFromHandle.GetMethod("Start", bindingAttr);
			if (methodInfo == null)
			{
				return false;
			}
			try
			{
				Hook.OntoMethod<Action<T>>(methodInfo, AutoCachePatch);
				JeviLib.Log($"Successfully hooked {typeFromHandle.Name}'s {methodInfo.Name}() method for autocaching.");
				isAutocaching = true;
				return true;
			}
			catch
			{
				JeviLib.Log("Failed to patch " + typeFromHandle.Name + " to autocache.");
				return false;
			}
		}

		private static void AutoCachePatch(T instance)
		{
			JeviLib.Log("Autocache for " + typeof(T).Name + " called, caching now.");
			cache[((Component)instance).gameObject] = instance;
			mostRecent = instance;
		}
	}
	public static class JevilBuildInfo
	{
		internal const string NAME = "JeviLib";

		internal const string AUTHOR = "extraes";

		internal const string COMPANY = null;

		public const string VERSION = "3.0.0";

		public const string DOWNLOAD_LINK = "https://bonelab.thunderstore.io/package/extraes/JeviLibBL/";

		public const bool DEBUG = true;

		public const bool SELFCONTAINED = false;

		public static string RuntimeVersion()
		{
			return "3.0.0";
		}

		public static bool RuntimeDebug()
		{
			return true;
		}

		public static bool RuntimeVersionGreaterThanOrEqual(string version)
		{
			SemVersion val = SemVersion.Parse(version, false);
			SemVersion val2 = SemVersion.Parse("3.0.0", false);
			return val2 >= val;
		}

		public static bool RuntimeSelfContained()
		{
			return false;
		}
	}
	public class JeviLib : MelonMod
	{
		internal static JeviLib instance;

		internal readonly Assembly Assembly = typeof(JeviLib).Assembly;

		internal static ConcurrentDictionary<string, ConcurrentBag<Assembly>> namespaceAssemblies = new ConcurrentDictionary<string, ConcurrentBag<Assembly>>();

		internal static int unityMainThread;

		private static readonly ConcurrentQueue<string> toLog = new ConcurrentQueue<string>();

		private static Stopwatch mainThreadInvokeTimer = new Stopwatch();

		private static Task<string>? nsCacheTask;

		public static bool DoneMappingNamespacesToAssemblies { get; private set; }

		public static bool SelfContainedThrowNotImplemented { get; private set; }

		internal static event Action? onUpdateCallback;

		internal static event Action? onNamespaceAssembliesCompleted;

		public JeviLib()
		{
			instance = this;
		}

		public void _OnEarlyInitializeMelon()
		{
			bool flag = Core.IsDebug && typeof(MelonEnvironment).Assembly.GetName().Version?.ToString() == "0.6.4.0" && !Utilities.IsPlatformQuest();
			Log("ML isDbg: " + Core.IsDebug);
			Log("ML ver: " + typeof(MelonEnvironment).Assembly.GetName().Version);
			Log("On Quest: " + Utilities.IsPlatformQuest());
			Log("Need launch dbgr: " + flag);
			Log(Debugger.IsAttached);
			if (flag && !Debugger.IsAttached)
			{
				Debugger.Launch();
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			Stopwatch stopwatch2 = Stopwatch.StartNew();
			DebugDraw.InitTokens();
			if (Utilities.IsPlatformQuest())
			{
				AndroidAsyncUnfucker.Init();
			}
			((MelonBase)this).HarmonyInstance.PatchAll();
			Barcodes.Init();
			PostProcessingManager.Init();
			Ungovernable.Init();
			stopwatch2.Stop();
			((MelonBase)this).LoggerInstance.Msg(ConsoleColor.Blue, $"JeviLib submodules initialized in {stopwatch2.ElapsedMilliseconds}ms");
			nsCacheTask = Task.Run((Func<Task<string>?>)GetNamespaces);
			Hooking.OnLevelLoaded += delegate(LevelInfo li)
			{
				//IL_0003: Unknown result type (might be due to invalid IL or missing references)
				((MelonMod)this).OnSceneWasInitialized(-1, li.barcode);
			};
			stopwatch.Stop();
			((MelonBase)this).LoggerInstance.Msg(ConsoleColor.Blue, $"Pre-initialized {"JeviLib"} v{"3.0.0"}{" Debug (Development)"} in {stopwatch.ElapsedMilliseconds}ms");
		}

		public override void OnInitializeMelon()
		{
			//IL_00a4: 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)
			_OnEarlyInitializeMelon();
			Stopwatch stopwatch = Stopwatch.StartNew();
			Log("This version of JeviLib has been built with the DEBUG compiler flag!");
			Log("Functionality will remain in tact for the most part, however there will be extra log points to warn you if there is anything worrying about your usage of the library.");
			Log("You should only be using this build if you create code mods, and not if you simply use mods. Do not rely on the extra checks in this build, or require the use of a debug build for your production code.");
			if (nsCacheTask != null)
			{
				if (!nsCacheTask.IsCompleted)
				{
					Log("Waiting for namespace assembly cache task to complete.");
				}
				string result = nsCacheTask.GetAwaiter().GetResult();
				Log(result);
			}
			else
			{
				Log("Namespace cache task is null... What?");
			}
			Log("Creating BoneMenu for jevil postprocess testing...");
			Page val = Page.Root.CreatePage("Test Jevil PostFX (debug only)", Color.white, 0, true);
			Type[] nestedTypes = typeof(SharedPostProcessingMaterials).GetNestedTypes();
			foreach (Type type in nestedTypes)
			{
				Log("Creating FunctionElements for " + type.FullName);
				MethodInfo[] methods = type.GetMethods();
				foreach (MethodInfo method in methods)
				{
					if (method.Name.Contains("able"))
					{
						val.CreateFunction(method.Name + " " + type.Name, Color.white, (Action)delegate
						{
							method.Invoke(null, Array.Empty<object>());
						});
					}
				}
			}
			SharedPostProcessingMaterials.Depth.DepthPow.SetOn(SharedPostProcessingMaterials.Depth.Material, 1f);
			SharedPostProcessingMaterials.Depth.DepthMult.SetOn(SharedPostProcessingMaterials.Depth.Material, 1f);
			SharedPostProcessingMaterials.Depth.UseColor.SetOn(SharedPostProcessingMaterials.Depth.Material, value: false);
			SharedPostProcessingMaterials.Pixelate.PixelsPerAxis.SetOn(SharedPostProcessingMaterials.Pixelate.Material, 100f);
			CreateNeverCancel();
			((MelonBase)this).LoggerInstance.Msg("Device memory statistics:");
			((MelonBase)this).LoggerInstance.Msg(" - Total memory: " + SystemInfo.systemMemorySize);
			((MelonBase)this).LoggerInstance.Msg(" - Used memory (will likely spike when game starts): " + Process.GetCurrentProcess().PeakWorkingSet64 / 1024 / 1024);
			((MelonBase)this).LoggerInstance.Msg(ConsoleColor.Blue, $"Completed initialization of {"JeviLib"} v{"3.0.0"}{" Debug"} in {stopwatch.ElapsedMilliseconds}ms");
		}

		private static void CreateNeverCancel()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			GameObject val = new GameObject("NeverCollect");
			NeverCollect unityObj = val.AddComponent<NeverCollect>();
			((Object)(object)val).Persist();
			((Object)(object)unityObj).Persist();
			Instances.NeverCancel = (Object)(object)val;
		}

		public override void OnUpdate()
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Invalid comparison between Unknown and I4
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			JeviLib.onUpdateCallback.InvokeSafeSync();
			Tweener.UpdateAll();
			if (!AsyncUtilities.mainThreadCallbacks.IsEmpty)
			{
				AsyncUtilities.MainThreadExecutor result;
				while (AsyncUtilities.mainThreadCallbacks.TryDequeue(out result))
				{
					try
					{
						result.execute();
					}
					catch (Exception ex)
					{
						Error("Exception while executing a main-thread callback");
						Error(ex);
						if ((int)result.completer.UnsafeGetStatus() > 0)
						{
							continue;
						}
						result.completer.exception = new ExceptionHolder(ExceptionDispatchInfo.Capture(new Exception(ex.ToString())));
					}
					result.completer.TrySetResult();
				}
			}
			mainThreadInvokeTimer.Restart();
		}

		public override void OnSceneWasInitialized(int buildIndex, string sceneName)
		{
			//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_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Expected O, but got Unknown
			//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02aa: Expected O, but got Unknown
			Log($"OSWI CALLED: PARAMS: IDX={buildIndex}, NAME={sceneName}");
			if (!((Object?)(object)Instances.Player_RigManager).INOC())
			{
				return;
			}
			Scene activeScene = SceneManager.GetActiveScene();
			WaitForSceneInit.currSceneIdx = ((Scene)(ref activeScene)).buildIndex;
			foreach (IDictionary item in Instances.instanceCachesToClear)
			{
				item.Clear();
			}
			Log("Cleared instance caches!");
			Stopwatch stopwatch = Stopwatch.StartNew();
			if (Instances.NeverCancel.INOC())
			{
				CreateNeverCancel();
			}
			Instances.Player_RigManager = ((IEnumerable<RigManager>)Object.FindObjectsOfType<RigManager>()).FirstOrDefault((Func<RigManager, bool>)((RigManager r) => ((Component)r).gameObject.scene != default(Scene)));
			if (!((Object?)(object)Instances.Player_RigManager).INOC())
			{
				Instances.Player_BodyVitals = Object.FindObjectOfType<BodyVitals>();
				Instances.Player_PhysicsRig = Instances.Player_RigManager.physicsRig;
				Instances.Player_Health = Object.FindObjectOfType<Player_Health>();
				Instances.Audio2dManager = Object.FindObjectOfType<Audio2dManager>();
				Instances.MusicMixer = ((IEnumerable<AudioMixerGroup>)Instances.Audio2dManager.mixer.FindMatchingGroups("Music")).First();
				Instances.SFXMixer = ((IEnumerable<AudioMixerGroup>)Instances.Audio2dManager.mixer.FindMatchingGroups("SFX")).First();
				Instances.RigCameras = ((IEnumerable<Camera>)Object.FindObjectsOfType<Camera>()).Where((Camera c) => ((Component)c).transform.IsChildOfRigManager()).ToArray();
				Instances.SpectatorCam = ((IEnumerable<Camera>)Instances.RigCameras).FirstOrDefault((Func<Camera, bool>)((Camera c) => ((Object)c).name == "Spectator Camera"));
				Instances.InHeadsetCam = ((IEnumerable<Camera>)Instances.RigCameras).FirstOrDefault((Func<Camera, bool>)((Camera c) => ((Object)c).name == "Head"));
				Transform head = Player.Head;
				GameObject val = new GameObject("JeviLib Music Player");
				val.transform.parent = ((Component)head).transform;
				Instances.MusicPlayer = val.AddComponent<AudioPlayer>();
				Instances.MusicPlayer._source = val.AddComponent<AudioSource>();
				Instances.MusicPlayer.source.outputAudioMixerGroup = Instances.MusicMixer;
				Instances.MusicPlayer._defaultVolume = 0.1f;
				Instances.MusicPlayer.source.volume = 0.1f;
				((Behaviour)Instances.MusicPlayer).enabled = true;
				GameObject val2 = new GameObject("JeviLib SFX Player");
				val2.transform.parent = ((Component)head).transform;
				Instances.SFXPlayer = val2.AddComponent<AudioPlayer>();
				Instances.SFXPlayer._source = val2.AddComponent<AudioSource>();
				Instances.SFXPlayer.source.outputAudioMixerGroup = Instances.SFXMixer;
				Instances.SFXPlayer._defaultVolume = 0.25f;
				Instances.SFXPlayer.source.volume = 0.25f;
				((Behaviour)Instances.SFXPlayer).enabled = true;
				Log("Found our instances in " + stopwatch.ElapsedMilliseconds + "ms.");
			}
		}

		public override void OnGUI()
		{
			DebugDraw.PerformDraw();
		}

		private async Task<string> GetNamespaces()
		{
			Log("Getting namespaces from assemblies now");
			Stopwatch sw = Stopwatch.StartNew();
			Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
			Assembly[][] assemblies = (from e in asms.SplitByProcessors()
				select e.ToArray()).ToArray();
			Log("Getting namespaces from " + assemblies.Sum((Assembly[] a) => a.Length) + " assemblies, split across " + assemblies.Length + " threads");
			Thread[] threads = new Thread[assemblies.Length];
			for (int i = 0; i < threads.Length; i++)
			{
				Thread dictThread = new Thread(PopulateDictionary_ThreadStart)
				{
					IsBackground = true
				};
				dictThread.Start(assemblies[i]);
				threads[i] = dictThread;
			}
			Log($"Split list & started threads in {sw.ElapsedMilliseconds} ms.");
			while (threads.Any((Thread t) => t.ThreadState != System.Threading.ThreadState.Stopped))
			{
				await Task.Yield();
			}
			sw.Stop();
			DoneMappingNamespacesToAssemblies = true;
			JeviLib.onNamespaceAssembliesCompleted.InvokeSafeParallel();
			return $"Cached all {namespaceAssemblies.Count} namespaces and their respective assemblies in {sw.ElapsedMilliseconds}ms";
		}

		private void PopulateDictionary_ThreadStart(object? obj)
		{
			PopulateDictionary((Assembly[])obj);
		}

		private void PopulateDictionary(Assembly[] section)
		{
			string text = string.Empty;
			try
			{
				foreach (Assembly assembly in section)
				{
					text = assembly.FullName ?? "<unnamed>";
					if (text.Contains("JeviLib") || assembly.IsDynamic)
					{
						continue;
					}
					Type[] types = assembly.GetTypes();
					IEnumerable<string> enumerable = types.Select((Type t) => t.Namespace).NoNull().Distinct();
					foreach (string item in enumerable)
					{
						if (!namespaceAssemblies.TryGetValue(item ?? "", out ConcurrentBag<Assembly> value))
						{
							value = new ConcurrentBag<Assembly>();
							namespaceAssemblies.TryAdd(item ?? "", value);
						}
						value.Add(assembly);
					}
				}
			}
			catch (Exception ex)
			{
				Error("Caught exception while populating namespace dictionary for assembly " + text, ex);
			}
		}

		private static IEnumerable<MethodInfo> GetLogMethods()
		{
			IEnumerable<MethodInfo> enumerable = new List<MethodInfo>();
			string[] array = new string[3] { "Msg", "Warning", "Error" };
			Type[] array2 = new Type[2]
			{
				typeof(MelonLogger),
				typeof(Instance)
			};
			Type[] array3 = array2;
			foreach (Type type in array3)
			{
				string[] array4 = array;
				foreach (string methodName in array4)
				{
					enumerable = enumerable.Concat(type.GetMethods(methodName));
				}
			}
			return enumerable;
		}

		internal static void Log(string str, ConsoleColor conCol = ConsoleColor.Gray)
		{
			((MelonBase)instance).LoggerInstance.Msg(conCol, str);
		}

		internal static void Log(object obj, ConsoleColor conCol = ConsoleColor.Gray)
		{
			((MelonBase)instance).LoggerInstance.Msg(conCol, obj?.ToString() ?? "null");
		}

		internal static void Warn(string str)
		{
			((MelonBase)instance).LoggerInstance.Warning(str);
		}

		internal static void Warn(object obj)
		{
			((MelonBase)instance).LoggerInstance.Warning(obj?.ToString() ?? "null");
		}

		internal static void Error(string str)
		{
			((MelonBase)instance).LoggerInstance.Error(str);
		}

		internal static void Error(object obj)
		{
			((MelonBase)instance).LoggerInstance.Error(obj?.ToString() ?? "null");
		}

		internal static void Error(string str, Exception ex)
		{
			((MelonBase)instance).LoggerInstance.Error(str ?? "null", ex);
		}

		private void NotifiedLowRAM()
		{
			Warn("BONELAB has been notified that your system has very little free RAM left! Double check that! Consider uninstalling some items!");
		}
	}
	[RegisterTypeInIl2Cpp]
	public class NeverCollect : MonoBehaviour
	{
		public List<Object> neverCollect = new List<Object>();

		private static bool instantiated;

		public NeverCollect(IntPtr ptr)
			: base(ptr)
		{
			JeviLib.Log($"New {"NeverCollect"} created. Inital check says this is{(instantiated ? "" : " not")} the first.");
			if (instantiated)
			{
				throw new ObjectDisposedException("NeverCollect should never be instantiated twice!");
			}
			neverCollect.Add((Object)(object)this);
			neverCollect.Add((Object)(object)neverCollect);
			instantiated = true;
			JeviLib.unityMainThread = Thread.CurrentThread.ManagedThreadId;
		}
	}
	public readonly struct OneOf<TRes, TExc> where TExc : Exception
	{
		private readonly TRes result;

		private readonly TExc exception;

		private readonly MethodInfo originalMethod;

		public TRes Result
		{
			get
			{
				if (!HasResult)
				{
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(75, 3);
					defaultInterpolatedStringHandler.AppendLiteral("OneOf<");
					defaultInterpolatedStringHandler.AppendFormatted(typeof(TRes).FullName);
					defaultInterpolatedStringHandler.AppendLiteral(", ");
					defaultInterpolatedStringHandler.AppendFormatted(typeof(TExc).FullName);
					defaultInterpolatedStringHandler.AppendLiteral("> (wrapping method call to ");
					MethodInfo methodInfo = originalMethod;
					defaultInterpolatedStringHandler.AppendFormatted((((object)methodInfo != null) ? GeneralExtensions.FullDescription((MethodBase)methodInfo) : null) ?? "<User Code>");
					defaultInterpolatedStringHandler.AppendLiteral(") errored, so there is no result to get.");
					throw new InvalidOperationException(defaultInterpolatedStringHandler.ToStringAndClear(), exception);
				}
				return result;
			}
		}

		public bool HasResult => !HasException;

		public bool HasException => exception != null;

		public OneOf(TRes result)
		{
			this.result = result;
			exception = null;
			originalMethod = null;
		}

		internal OneOf(TExc exception, MethodInfo ogMethod)
		{
			result = default(TRes);
			this.exception = exception;
			originalMethod = ogMethod;
		}

		public static OneOf<TRes, TExc> FromSuccess(TRes result)
		{
			return result;
		}

		public static OneOf<TRes, TExc> FromFailure(TExc ex)
		{
			return ex;
		}

		public static implicit operator TRes(OneOf<TRes, TExc> o)
		{
			return o.Result;
		}

		public static implicit operator OneOf<TRes, TExc>(TRes value)
		{
			return new OneOf<TRes, TExc>(value);
		}

		public static implicit operator OneOf<TRes, TExc>(Exception exception)
		{
			return new OneOf<TRes, TExc>((TExc)exception, null);
		}
	}
	public class ProfilingScope : IDisposable
	{
		[Flags]
		public enum ProfilingType
		{
			NONE = 0,
			STOPWATCH_EXECUTION_TIME = 1,
			FRAME_COUNT = 2,
			ALL = -1
		}

		private Instance logger;

		private Stopwatch sw;

		private int frameStart;

		private ProfilingType profilingType;

		private string logTag;

		public float ElapsedMilliseconds => (float)sw.ElapsedTicks / 10000f;

		public float ElapsedFrames => Time.frameCount - frameStart;

		public ProfilingScope(ProfilingType whatToLog = ProfilingType.STOPWATCH_EXECUTION_TIME, [CallerMemberName] string logTag = null)
		{
			logger = ((MelonBase)JeviLib.instance).LoggerInstance;
			profilingType = whatToLog;
			this.logTag = Assembly.GetCallingAssembly().GetName().Name + " -> " + logTag;
			Restart();
		}

		public ProfilingScope(Instance logger, ProfilingType whatToLog = ProfilingType.STOPWATCH_EXECUTION_TIME, [CallerMemberName] string logTag = null)
		{
			this.logger = logger;
			profilingType = whatToLog;
			this.logTag = Assembly.GetCallingAssembly().GetName().Name + " -> " + logTag;
			Restart();
		}

		public void Restart()
		{
			if (sw == null)
			{
				sw = Stopwatch.StartNew();
			}
			sw.Restart();
			frameStart = Time.frameCount;
		}

		public void LogRestart()
		{
			Log();
			Restart();
		}

		public void Log()
		{
			if (profilingType.HasFlag(ProfilingType.STOPWATCH_EXECUTION_TIME))
			{
				logger.Msg($"{logTag}: executed for {ElapsedMilliseconds} milliseconds");
			}
			if (profilingType.HasFlag(ProfilingType.FRAME_COUNT))
			{
				logger.Msg($"{logTag}: executed for {ElapsedFrames} frames");
			}
		}

		public void Dispose()
		{
			Log();
		}
	}
	public sealed class ULazy<T> where T : Object
	{
		private T? value;

		private Func<T> valueMaker;

		private bool persist;

		private bool hide;

		public T Value
		{
			get
			{
				if (((Object?)(object)value).INOC())
				{
					value = valueMaker();
					if (persist)
					{
						((Object)(object)value).Persist(hide);
					}
					else if (hide)
					{
						((Object)value).hideFlags = (HideFlags)61;
					}
					if (((Object?)(object)value).INOC())
					{
						throw new InvalidOperationException("Value maker returned null. This should not happen!");
					}
				}
				return value;
			}
		}

		public bool ValueExists => !((Object?)(object)value).INOC();

		public ULazy(Func<T> valueMaker, bool persistOnCreate = true, bool hideOnCreate = true)
		{
			this.valueMaker = valueMaker;
			persist = persistOnCreate;
			hide = hideOnCreate;
		}
	}
	public class UnityObjectComparer<T> : IEqualityComparer<T> where T : Object
	{
		public static IEqualityComparer<T> Instance { get; } = new UnityObjectComparer<T>();


		public bool Equals(T x, T y)
		{
			bool flag = ((Object?)(object)x).INOC();
			bool flag2 = ((Object?)(object)y).INOC();
			bool flag3 = flag && flag2;
			bool flag4 = flag || flag2;
			return flag3 == flag4 && (Object)(object)x == (Object)(object)y;
		}

		public int GetHashCode(T obj)
		{
			return ((Object)(object)obj).GetHashCode();
		}
	}
	public static class Utilities
	{
		private static Type? inspectorManager;

		private static Func<string, bool> isPackageInstalled = delegate
		{
			throw new PlatformNotSupportedException();
		};

		private static IntPtr il2cppDomain = IL2CPP.il2cpp_domain_get();

		private static bool fusionLoaded = AppDomain.CurrentDomain.GetAssemblies().Any((Assembly asm) => !asm.IsDynamic && asm.GetName().Name == "LabFusion");

		private static bool? uniTasksNeedPatch;

		public static bool IsSteamVersion()
		{
			return Application.dataPath.EndsWith("BONELAB_Steam_Windows64_Data");
		}

		public static Hand GetRandomPlayerHand()
		{
			int num = Random.Range(0, 2);
			if (num == 1)
			{
				return Player.LeftHand;
			}
			return Player.RightHand;
		}

		public static GameObject SpawnAd(string str)
		{
			GameObject val = PopupBoxManager.CreateNewPopupBox(str);
			MoveAndFacePlayer(val);
			return val;
		}

		public static IEnumerable<T> FindAll<T>() where T : Object
		{
			return ((IEnumerable<Object>)Object.FindObjectsOfTypeAll(Il2CppType.Of<T>())).Select((Object obj) => ((Il2CppObjectBase)obj).Cast<T>());
		}

		public static string[] Argsify(string data, char split = ',')
		{
			string[] array = data.Split(split);
			string text = array[0];
			string text2 = string.Join(split.ToString(), array.Skip(1));
			return new string[2] { text, text2 };
		}

		public static Vector3 DebyteV3(byte[] bytes, int startIdx = 0)
		{
			//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_00ce: Unknown result type (might be due to invalid IL or missing references)
			if (startIdx == 0 && bytes.Length != 12)
			{
				JeviLib.Warn($"Trying to debyte a Vector3 of length {bytes.Length}, this is not the expected {12} bytes!");
			}
			if (startIdx + 12 > bytes.Length)
			{
				JeviLib.Warn($"{bytes.Length} is too short for the given index of {startIdx}");
			}
			return new Vector3(BitConverter.ToSingle(bytes, startIdx), BitConverter.ToSingle(bytes, startIdx + 4), BitConverter.ToSingle(bytes, startIdx + 8));
		}

		public static Vector3[] DeserializeMesh(byte[] bytes)
		{
			//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)
			Vector3[] array = (Vector3[])(object)new Vector3[bytes.Length / 12];
			if (bytes.Length % 12 != 0)
			{
				JeviLib.Warn("Malformed byte array - not divisible by the size of a vector3");
			}
			for (int i = 0; i < bytes.Length; i += 12)
			{
				array[i / 12] = DebyteV3(bytes, i);
			}
			return array;
		}

		public static byte[] SerializeMesh(Vector3[] vectors)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = new byte[vectors.Length * 4 * 3];
			for (int i = 0; i < vectors.Length; i++)
			{
				int dstOffset = i * 4 * 3;
				byte[] src = vectors[i].ToBytes();
				Buffer.BlockCopy(src, 0, array, dstOffset, 12);
			}
			return array;
		}

		public static void MoveAndFacePlayer(GameObject obj)
		{
			//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_0018: 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_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_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_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_0050: 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)
			Transform head = ((Rig)Instances.Player_PhysicsRig).m_head;
			Vector3 position = head.position;
			Vector3 forward = head.forward;
			Vector3 val = position + ((Vector3)(ref forward)).normalized * 2f;
			Quaternion val2 = Quaternion.LookRotation(obj.transform.position - head.position, Vector3.up);
			obj.transform.SetPositionAndRotation(val, val2);
		}

		public static byte[] JoinBytes(byte[][] bytess)
		{
			byte b2 = (byte)bytess.Length;
			List<ushort> list = new List<ushort>(bytess.Length - 1);
			byte[] array = new byte[bytess.Length * 2 + 1 + bytess.Sum((byte[] b) => b.Length)];
			foreach (byte[] array2 in bytess)
			{
				list.Add((ushort)array2.Length);
			}
			array[0] = b2;
			for (int j = 0; j < list.Count; j++)
			{
				ushort value = list[j];
				BitConverter.GetBytes(value).CopyTo(array, j * 2 + 1);
			}
			ushort num = 0;
			int num2 = b2 * 2 + 1;
			for (int k = 0; k < b2; k++)
			{
				int num3 = list[k];
				Buffer.BlockCopy(bytess[k], 0, array, num2, num3);
				num = (ushort)num3;
				num2 += num3;
			}
			return array;
		}

		public static byte[][] SplitBytes(byte[] bytes)
		{
			int num = bytes[0];
			int[] array = new int[num];
			for (int i = 0; i < num; i++)
			{
				ushort num2 = BitConverter.ToUInt16(bytes, 1 + i * 2);
				array[i] = num2;
			}
			byte[][] array2 = new byte[num][];
			int num3 = num * 2 + 1;
			for (int j = 0; j < array2.Length; j++)
			{
				int num4 = array[j];
				byte[] array3 = new byte[num4];
				Buffer.BlockCopy(bytes, num3, array3, 0, num4);
				array2[j] = array3;
				num3 += num4;
			}
			return array2;
		}

		public static string GenerateFriendlyMemberName(string name)
		{
			StringBuilder stringBuilder = new StringBuilder(name.Length);
			int num = 0;
			if (name.StartsWith("m_"))
			{
				num += 2;
			}
			stringBuilder.Append(char.ToUpper(name[num]));
			for (int i = num + 1; i < name.Length; i++)
			{
				char c = name[i];
				if (char.IsUpper(c))
				{
					stringBuilder.Append(' ');
					stringBuilder.Append(char.ToUpper(c));
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}

		public static byte[] Flatten(params byte[][] arrays)
		{
			return arrays.Flatten();
		}

		public static byte[] SerializeInFrontFacingPlayer()
		{
			//IL_0010: 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_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_002b: 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_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_004c: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = new byte[24];
			Transform head = Player.Head;
			Vector3 vec = head.position + head.forward * 2f;
			vec.ToBytes().CopyTo(array, 0);
			Quaternion val = Quaternion.LookRotation(-head.forward);
			((Quaternion)(ref val)).eulerAngles.ToBytes().CopyTo(array, 12);
			return array;
		}

		public static (Vector3, Quaternion) DebytePosRot(byte[] bytes, int startIdx = 0)
		{
			//IL_00c6: 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)
			if (startIdx == 0 && bytes.Length != 24)
			{
				JeviLib.Warn($"Trying to debyte a posrot of length {bytes.Length}, this is not the expected {24} bytes!");
			}
			if (startIdx + 24 > bytes.Length)
			{
				JeviLib.Warn($"{bytes.Length} is too short for the given index of {startIdx}");
			}
			return (new Vector3(BitConverter.ToSingle(bytes, startIdx), BitConverter.ToSingle(bytes, startIdx + 4), BitConverter.ToSingle(bytes, startIdx + 8)), Quaternion.Euler(new Vector3(BitConverter.ToSingle(bytes, startIdx + 12), BitConverter.ToSingle(bytes, startIdx + 12 + 4), BitConverter.ToSingle(bytes, startIdx + 12 + 8))));
		}

		public static IEnumerable<Rigidbody> GetMuscleRigidbodies(PuppetMaster puppet)
		{
			return ((IEnumerable<Muscle>)puppet.muscles).Select((Muscle s) => s.marrowBody._rigidbody);
		}

		public static Type? GetTypeFromString(string namezpaze, string clazz)
		{
			if (!JeviLib.DoneMappingNamespacesToAssemblies)
			{
				JeviLib.Log("Not done mapping namespaces to assemblies! Getting type from string may falsely return null!");
			}
			if (JeviLib.namespaceAssemblies.TryGetValue(namezpaze, out ConcurrentBag<Assembly> value))
			{
				JeviLib.Log($"Found the namespace '{namezpaze}' in {value.Count} assemblies, attempting to find the type {clazz}");
				foreach (Assembly item in value)
				{
					if ((object)item != null)
					{
						Type type = item.GetType(namezpaze + "." + clazz);
						if (type != null)
						{
							return type;
						}
					}
				}
				JeviLib.Warn($"Unable to find a Type named '{clazz}' in the namespace '{namezpaze}' in any loaded Assemblies");
			}
			else
			{
				JeviLib.Warn("Unable to find the namespace '" + namezpaze + "' in any loaded assemblies (This is probably fine/expected behavior)");
			}
			return null;
		}

		public static MethodInfo AsInfo(Delegate method)
		{
			return method.Method;
		}

		public static HarmonyMethod ToHarmony(Delegate method)
		{
			return MelonUtils.ToNewHarmonyMethod(AsInfo(method));
		}

		public static HealthSettings CloneHealthSettings(HealthSettings hs)
		{
			//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_0013: 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_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0061: 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_007b: 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_0096: Expected O, but got Unknown
			return new HealthSettings
			{
				aggression = hs.aggression,
				irritability = hs.irritability,
				maxAppendageHp = hs.maxAppendageHp,
				maxHitPoints = hs.maxHitPoints,
				maxStunSeconds = hs.maxStunSeconds,
				minHeadImpact = hs.minHeadImpact,
				minLimbImpact = hs.minLimbImpact,
				minSpineImpact = hs.minSpineImpact,
				placability = hs.placability,
				stunRecovery = hs.stunRecovery,
				vengefulness = hs.vengefulness
			};
		}

		public static Thread StartBGThread(Action call)
		{
			Action call2 = call;
			Thread thread = new Thread((ThreadStart)delegate
			{
				call2();
			});
			thread.IsBackground = true;
			thread.Start();
			return thread;
		}

		public static Thread StartBGThread<T>(Action<T> call, T param)
		{
			Action<T> call2 = call;
			Thread thread = new Thread(delegate(object? obj)
			{
				call2((T)obj);
			});
			thread.IsBackground = true;
			thread.Start(param);
			return thread;
		}

		public static void InspectInUnityExplorer(object obj)
		{
			if ((object)inspectorManager == null)
			{
				inspectorManager = GetTypeFromString("UnityExplorer", "InspectorManager");
			}
			if ((object)inspectorManager == null)
			{
				JeviLib.Warn($"UnityExplorer is not installed, cannot inspect object {obj}.");
			}
			else
			{
				Type typeFromString = GetTypeFromString("UnityExplorer.CacheObject", "CacheObjectBase");
				(inspectorManager?.GetMethod("Inspect", new Type[2]
				{
					typeof(object),
					typeFromString
				}))?.Invoke(null, new object[2] { obj, null });
			}
		}

		public static void InspectInUnityExplorer(Type t)
		{
			if ((object)inspectorManager == null)
			{
				inspectorManager = GetTypeFromString("UnityExplorer", "InspectorManager");
			}
			(inspectorManager?.GetMethod("Inspect", new Type[1] { typeof(Type) }))?.Invoke(null, new object[1] { t });
		}

		public static MethodInfo? GetMethodFromString(string namezpaze, string clazz, string method, string[]? paramTypes = null)
		{
			string method2 = method;
			if (!JeviLib.DoneMappingNamespacesToAssemblies)
			{
				JeviLib.Warn("Unlikely to get successfully get method from string if namespace mapping is incomplete!");
			}
			Type typeFromString = GetTypeFromString(namezpaze, clazz);
			if (typeFromString == null)
			{
				JeviLib.Log("Unable to find the namespace '" + namezpaze + "' in any loaded Assemblies.");
				return null;
			}
			MethodInfo methodInfo = null;
			if (paramTypes == null)
			{
				methodInfo = typeFromString.GetMethodEasy(method2);
			}
			else
			{
				MethodInfo[] array = (from m in typeFromString.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
					where m.Name == method2
					select m).ToArray();
				MethodInfo[] array2 = array;
				foreach (MethodInfo methodInfo2 in array2)
				{
					string[] first = (from pi in methodInfo2.GetParameters()
						select pi.ParameterType.Name).ToArray();
					if (first.SequenceEqual(paramTypes))
					{
						methodInfo = methodInfo2;
						break;
					}
				}
			}
			if (methodInfo == null)
			{
				string value = ((paramTypes == null) ? "" : $"that matches the given {paramTypes.Length} parameter(s).");
				JeviLib.Log($"The type {namezpaze}.{clazz} (from assembly {typeFromString.Assembly.GetName().Name}) doesn't have a method named {method2} {value}");
			}
			return methodInfo;
		}

		public static bool IsPlatformQuest()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			return (int)MelonUtils.CurrentPlatform == 3;
		}

		public static bool UniTasksNeedPatch()
		{
			if (uniTasksNeedPatch.HasValue)
			{
				return uniTasksNeedPatch.Value;
			}
			Type[] interfaces = typeof(Awaiter).GetInterfaces();
			uniTasksNeedPatch = interfaces.Length == 0;
			JeviLib.Log($"UniTask Awaiter implements {interfaces.Length} interfaces. Fix needs application? {uniTasksNeedPatch}");
			return uniTasksNeedPatch.Value;
		}

		public static void RestartGame()
		{
			if (IsPlatformQuest())
			{
				Application.Quit();
				return;
			}
			Process currentProcess = Process.GetCurrentProcess();
			Process process = new Process();
			process.StartInfo = new ProcessStartInfo
			{
				FileName = Application.dataPath.Replace("_Data", ".exe"),
				WorkingDirectory = MelonEnvironment.MelonBaseDirectory
			};
			process.Start();
			Application.Quit();
		}

		public static string BuildJavaScriptLogStr(object obj, int maxRecurseDepth = 3)
		{
			if (obj == null)
			{
				return "<null>";
			}
			Object val = (Object)((obj is Object) ? obj : null);
			if (val != null && ((Il2CppObjectBase)val).WasCollected)
			{
				return "<Collected in the IL2CPP domain>";
			}
			StringBuilder stringBuilder = new StringBuilder();
			ObjectDumper.InternalDump(0, "Logged object", obj, stringBuilder, new ObjectIDGenerator(), maxRecurseDepth);
			return stringBuilder.ToString();
		}

		public static void ChangeStrength(PhysHand hand, float mult = 200f, float torque = 10f)
		{
			hand.xPosForce = 90f * mult;
			hand.yPosForce = 90f * mult;
			hand.zPosForce = 340f * mult;
			hand.xNegForce = 90f * mult;
			hand.yNegForce = 200f * mult;
			hand.zNegForce = 360f * mult;
			hand.newtonDamp = 80f * mult;
			hand.angDampening = torque;
			hand.dampening = 0.2f * mult;
			hand.maxTorque = 30f * torque;
		}

		public static bool IsFusionLoaded()
		{
			return fusionLoaded;
		}

		public static byte[] GetHierarchyIndices(Transform parent, Transform child)
		{
			int num = HierarchalDepth(parent);
			int num2 = HierarchalDepth(child);
			int num3 = num2 - num;
			if (!child.IsChildOf(parent))
			{
				throw new ArgumentException($"Given transform {((Object)child).name} is not a child of the given parent {((Object)parent).name}. Parent full path: {parent.GetFullPath()} Child full path: {child.GetFullPath()}");
			}
			byte[] array = new byte[num3];
			for (int num4 = num3 - 1; num4 >= 0; num4--)
			{
				array[num4] = (byte)child.GetSiblingIndex();
				child = child.parent;
			}
			return array;
		}

		public static int HierarchalDepth(Transform transform)
		{
			if ((Object)(object)transform == (Object)null)
			{
				return 0;
			}
			int num = 0;
			while ((Object)(object)transform.parent != (Object)null)
			{
				num++;
				transform = transform.parent;
			}
			return num;
		}

		public static Transform TraverseHierarchy(Transform transform, byte[] childIdxs)
		{
			if (((Object?)(object)transform).INOC())
			{
				throw new ArgumentNullException("transform");
			}
			Transform val = transform;
			foreach (byte b in childIdxs)
			{
				val = val.GetChild((int)b);
			}
			return val;
		}

		public static bool CreateDirectoryRecursive(string directory)
		{
			string directoryName = Path.GetDirectoryName(directory);
			if (directoryName == null)
			{
				return false;
			}
			if (!Directory.Exists(directoryName))
			{
				CreateDirectoryRecursive(directoryName);
			}
			Directory.CreateDirectory(directory);
			return true;
		}

		public unsafe static byte[] SerializePrimitives<T>(T[] primitives) where T : unmanaged
		{
			int num = sizeof(T);
			byte[] array = new byte[num * primitives.Length];
			fixed (byte* ptr = array)
			{
				for (int i = 0; i < primitives.Length; i++)
				{
					*(T*)(ptr + num * i) = primitives[i];
				}
			}
			return array;
		}

		public unsafe static void SerializeInPlace<T>(byte[] array, T value, int offset = 0) where T : unmanaged
		{
			if (array.Length < offset + sizeof(T))
			{
				JeviLib.Warn($"Trying to serialize a {sizeof(T)}-length value into an array of length {array.Length} with a {offset}-byte offset... This will not end well!");
			}
			fixed (byte* ptr = array)
			{
				T* ptr2 = (T*)(ptr + offset);
				*ptr2 = value;
			}
		}

		public unsafe static void SerializeInPlace(byte[] array, Vector3 value, int offset = 0)
		{
			//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_002f: Unknown result type (might be due to invalid IL or missing references)
			fixed (byte* ptr = array)
			{
				*(float*)ptr = value.x;
				*(float*)(ptr + 4) = value.y;
				*(float*)(ptr + 8) = value.z;
			}
		}

		public static void AttachIl2CppToThread()
		{
			IL2CPP.il2cpp_thread_attach(il2cppDomain);
		}

		public static bool IsOBSRunning()
		{
			return !IsPlatformQuest() && Process.GetProcessesByName("obs64").Length != 0;
		}

		public static Exception? Try(Action action)
		{
			try
			{
				action();
				return null;
			}
			catch (Exception result)
			{
				return result;
			}
		}

		public static Exception? Try<T1>(Action<T1> action, T1 param1)
		{
			try
			{
				action(param1);
				return null;
			}
			catch (Exception result)
			{
				return result;
			}
		}

		public static OneOf<TRes, Exception> Try<TRes>(Func<TRes> func)
		{
			try
			{
				return func();
			}
			catch (Exception ex)
			{
				return ex;
			}
		}

		public static OneOf<TRes, Exception> Try<TRes, T1>(Func<T1, TRes> func, T1 param1)
		{
			try
			{
				return func(param1);
			}
			catch (Exception ex)
			{
				return ex;
			}
		}

		public static Nullable<T> NulledNullable<T>() where T : new()
		{
			Nullable<T> val = new Nullable<T>(default(T));
			val.hasValue = false;
			return val;
		}
	}
}
namespace Jevil.Waiting
{
	public static class CallDelayed
	{
		public static CallToken CallAction(Action fun, float time, bool runAsync = false)
		{
			CallToken callToken = new CallToken(fun, runAsync);
			if (runAsync)
			{
				try
				{
					WaiterAsync(callToken, time);
				}
				catch (Exception ex)
				{
					JeviLib.Error("Exception occurred in async method call " + ex);
				}
			}
			else
			{
				MelonCoroutines.Start(WaiterUnity(callToken, time));
			}
			return callToken;
		}

		public static CallToken CallEvent(UnityEvent unityEvent, float time)
		{
			return CallAction((Action)unityEvent.Invoke, time, runAsync: false);
		}

		private static IEnumerator WaiterUnity(CallToken token, float time)
		{
			float elapsed = 0f;
			while (elapsed < time)
			{
				elapsed = ((!token.waitInRealtime) ? (elapsed + Time.deltaTime) : (elapsed + Time.unscaledDeltaTime));
				yield return null;
			}
			if (!token.doNotCall)
			{
				token.call();
			}
		}

		private static async Task 

Plugins/JevilPlugin.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using HarmonyLib;
using Il2CppInterop.Common.XrefScans;
using Il2CppInterop.Generator.Contexts;
using Il2CppInterop.Generator.Passes;
using Il2CppInterop.Runtime;
using Jevil.Il2CppInterop.Generator.Passes;
using JevilPlugin;
using MelonLoader;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("JevilPlugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany(null)]
[assembly: AssemblyProduct("JevilPlugin")]
[assembly: AssemblyCopyright("Created by extraes")]
[assembly: AssemblyTrademark(null)]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: MelonInfo(typeof(global::JevilPlugin.JevilPlugin), "JevilPlugin", "1.0.0", "extraes", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[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 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 JevilPlugin
{
	public static class BuildInfo
	{
		public const string Name = "JevilPlugin";

		public const string Author = "extraes";

		public const string Company = null;

		public const string Version = "1.0.0";

		public const string DownloadLink = null;
	}
	public class JevilPlugin : MelonPlugin
	{
		internal static JevilPlugin instance;

		public JevilPlugin()
		{
			instance = this;
		}

		public override void OnApplicationEarlyStart()
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			Type type = typeof(Pass60AddImplicitConversions).Assembly.GetType("Il2CppInterop.Generator.Passes.Pass61ImplementAwaiters");
			if (GetUniTaskInterfaceCount() == 0 || Il2CppAssemblyGenerator.ForceRegeneration)
			{
				if ((object)type == null)
				{
					Log("Patching assembly generation...");
					MethodInfo methodInfo = InfoOf(new Action<RewriteGlobalContext>(Pass60AddImplicitConversions.DoPass));
					HarmonyMethod val = new HarmonyMethod(InfoOf(new Action<RewriteGlobalContext>(Pass61ImplementAwaiters.DoPass)));
					((MelonBase)this).HarmonyInstance.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					Log("Assembly generation does not need to be patched.");
				}
				Log("Forcing assembly regeneration...");
				Type typeFromHandle = typeof(Il2CppAssemblyGenerator);
				PropertyInfo property = typeFromHandle.GetProperty("ForceRegeneration", BindingFlags.Static | BindingFlags.Public);
				property.SetValue(null, true);
			}
		}

		private MethodInfo InfoOf(Delegate d)
		{
			return d.Method;
		}

		private static int GetUniTaskInterfaceCount()
		{
			string text = Path.Combine(MelonEnvironment.Il2CppAssembliesDirectory, "Il2CppUniTask.dll");
			if (!File.Exists(text))
			{
				return 0;
			}
			AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text);
			try
			{
				TypeDefinition type = val.MainModule.GetType("Il2CppCysharp.Threading.Tasks.UniTask");
				TypeDefinition val2 = ((IEnumerable<TypeDefinition>)type.NestedTypes).FirstOrDefault((Func<TypeDefinition, bool>)((TypeDefinition t) => ((MemberReference)t).Name == "Awaiter"));
				Log($"UniTask awaiter implements {val2.Interfaces.Count} interfaces.");
				return val2.Interfaces.Count;
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		internal static void Log(string str)
		{
			((MelonBase)instance).LoggerInstance.Msg(str);
		}

		internal static void Log(object obj)
		{
			((MelonBase)instance).LoggerInstance.Msg(obj?.ToString() ?? "null");
		}

		internal static void Warn(string str)
		{
			((MelonBase)instance).LoggerInstance.Warning(str);
		}

		internal static void Warn(object obj)
		{
			((MelonBase)instance).LoggerInstance.Warning(obj?.ToString() ?? "null");
		}

		internal static void Error(string str)
		{
			((MelonBase)instance).LoggerInstance.Error(str);
		}

		internal static void Error(object obj)
		{
			((MelonBase)instance).LoggerInstance.Error(obj?.ToString() ?? "null");
		}
	}
}
namespace Jevil.Il2CppInterop.Generator.Passes
{
	internal static class Pass61ImplementAwaiters
	{
		public static void DoPass(RewriteGlobalContext context)
		{
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Unknown result type (might be due to invalid IL or missing references)
			//IL_031d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0324: Expected O, but got Unknown
			//IL_0337: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Expected O, but got Unknown
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Expected O, but got Unknown
			//IL_0385: Unknown result type (might be due to invalid IL or missing references)
			//IL_0392: 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_03ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_03dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: 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_027c: 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_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Expected O, but got Unknown
			//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)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Expected O, but got Unknown
			AssemblyRewriteContext assemblyByName = context.GetAssemblyByName("mscorlib");
			TypeRewriteContext actionUntyped = assemblyByName.GetTypeByName("System.Action");
			MethodDefinition actionConversionUntyped = ((IEnumerable<MethodDefinition>)actionUntyped.NewType.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "op_Implicit")) ?? throw new MissingMethodException("Untyped action conversion");
			foreach (AssemblyRewriteContext assemblyContext in context.Assemblies)
			{
				Lazy<TypeReference> lazy = new Lazy<TypeReference>((Func<TypeReference>)(() => assemblyContext.NewAssembly.MainModule.ImportReference((TypeReference)(object)actionUntyped.OriginalType)));
				Lazy<MethodReference> lazy2 = new Lazy<MethodReference>((Func<MethodReference>)(() => assemblyContext.NewAssembly.MainModule.ImportReference((MethodReference)(object)actionConversionUntyped)));
				Lazy<TypeReference> lazy3 = new Lazy<TypeReference>((Func<TypeReference>)(() => assemblyContext.NewAssembly.MainModule.ImportReference(typeof(INotifyCompletion))));
				Lazy<TypeReference> lazy4 = new Lazy<TypeReference>((Func<TypeReference>)(() => assemblyContext.NewAssembly.MainModule.ImportReference(typeof(void))));
				foreach (TypeRewriteContext type in assemblyContext.Types)
				{
					InterfaceImplementation val = ((IEnumerable<InterfaceImplementation>)type.OriginalType.Interfaces).FirstOrDefault((Func<InterfaceImplementation, bool>)((InterfaceImplementation InterfaceImplementation) => ((MemberReference)InterfaceImplementation.InterfaceType).Name == "INotifyCompletion"));
					if (val == null || type.OriginalType.IsInterface)
					{
						continue;
					}
					bool containsGenericParameter = ((MemberReference)type.OriginalType).ContainsGenericParameter;
					TypeDefinition originalType = type.OriginalType;
					MethodRewriteContext val2 = type.TryGetMethodByName("OnCompleted");
					MethodReference val3 = (MethodReference)(object)((IEnumerable<MethodDefinition>)type.NewType.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "OnCompleted"));
					if (val2 == null || val3 == null)
					{
						continue;
					}
					TypeDefinition declaringType = type.NewType.DeclaringType;
					if (declaringType != null && ((TypeReference)declaringType).HasGenericParameters)
					{
						TypeDefinition declaringType2 = type.NewType.DeclaringType;
						TypeReference[] arguments = (TypeReference[])(object)((TypeReference)type.NewType.DeclaringType).GenericParameters.ToArray();
						TypeReference val4 = ((TypeReference)(object)declaringType2).MakeGenericType(arguments);
						TypeDefinition newType = type.NewType;
						arguments = (TypeReference[])(object)((TypeReference)type.NewType.DeclaringType).GenericParameters.ToArray();
						TypeReference declaringType3 = ((TypeReference)(object)newType).MakeGenericType(arguments);
						Collection<ParameterDefinition> parameters = val3.Parameters;
						val3 = new MethodReference(((MemberReference)val2.NewMethod).Name, ((MethodReference)val2.NewMethod).ReturnType)
						{
							DeclaringType = declaringType3,
							CallingConvention = ((MethodReference)val2.NewMethod).CallingConvention,
							HasThis = ((MethodReference)val2.NewMethod).HasThis,
							ExplicitThis = ((MethodReference)val2.NewMethod).ExplicitThis
						};
						Enumerator<ParameterDefinition> enumerator3 = parameters.GetEnumerator();
						try
						{
							while (enumerator3.MoveNext())
							{
								ParameterDefinition current2 = enumerator3.Current;
								val3.Parameters.Add(new ParameterDefinition(((ParameterReference)current2).Name, current2.Attributes, ((ParameterReference)current2).ParameterType));
							}
						}
						finally
						{
							((IDisposable)enumerator3).Dispose();
						}
					}
					MethodAttributes val5 = (MethodAttributes)486;
					MethodDefinition val6 = new MethodDefinition("OnCompleted", val5, lazy4.Value);
					type.NewType.Interfaces.Add(new InterfaceImplementation(lazy3.Value));
					type.NewType.Methods.Add(val6);
					((MethodReference)val6).Parameters.Add(new ParameterDefinition("continuation", (ParameterAttributes)0, lazy.Value));
					ILProcessor iLProcessor = val6.Body.GetILProcessor();
					iLProcessor.Emit(OpCodes.Nop);
					iLProcessor.Emit(OpCodes.Ldarg_0);
					iLProcessor.Emit(OpCodes.Ldarg_1);
					iLProcessor.Emit(OpCodes.Call, lazy2.Value);
					iLProcessor.Emit(OpCodes.Call, val3);
					iLProcessor.Emit(OpCodes.Nop);
					iLProcessor.Emit(OpCodes.Ret);
				}
			}
		}

		private static TypeReference MakeGenericType(this TypeReference self, params TypeReference[] arguments)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			if (self.GenericParameters.Count != arguments.Length)
			{
				throw new ArgumentException();
			}
			GenericInstanceType val = new GenericInstanceType(self);
			foreach (TypeReference val2 in arguments)
			{
				val.GenericArguments.Add(val2);
			}
			return (TypeReference)(object)val;
		}
	}
}
namespace Jevil.Unsafe
{
	public static class GlobalGameManagers
	{
		public delegate IntPtr GetManagerFromContextDelegate(ManagerIndex index);

		public enum ManagerIndex
		{
			kPlayerSettings = 0,
			kInputManager = 1,
			kTagManager = 2,
			kAudioManager = 3,
			kShaderNameRegistry = 4,
			kMonoManager = 5,
			kGraphicsSettings = 6,
			kTimeManager = 7,
			kDelayedCallManager = 8,
			kPhysicsManager = 9,
			kBuildSettings = 10,
			kQualitySettings = 11,
			kResourceManager = 12,
			kNavMeshProjectSettings = 13,
			kPhysics2DSettings = 14,
			kClusterInputManager = 15,
			kRuntimeInitializeOnLoadManager = 16,
			kUnityConnectSettings = 17,
			kStreamingManager = 18,
			kVFXManager = 19,
			kGlobalManagerCount = 20,
			kFirstLevelManager = 20,
			kOcclusionCullingSettings = 20,
			kRenderSettings = 21,
			kLightmapSettings = 22,
			kNavMeshSettings = 23,
			kManagerCount = 24,
			kLevelGameManagerCount = 4
		}

		public static readonly GetManagerFromContextDelegate GetManagerFromContext;

		static GlobalGameManagers()
		{
			IntPtr intPtr = IL2CPP.il2cpp_resolve_icall("UnityEngine.LayerMask::LayerToName");
			IEnumerable<IntPtr> source = XrefScannerLowLevel.JumpTargets(intPtr, false);
			global::JevilPlugin.JevilPlugin.Log(string.Format("LayerToName targets {0} jump locations: {1}", source.Count(), string.Join(", ", source.Select((IntPtr ptr) => ptr.ToString("X")))));
			IntPtr intPtr2 = XrefScannerLowLevel.JumpTargets(intPtr, false).First();
			source = XrefScannerLowLevel.JumpTargets(intPtr2, false);
			global::JevilPlugin.JevilPlugin.Log(string.Format("GetTagManager(? i think) targets {0} jump locations: {1}", source.Count(), string.Join(", ", source.Select((IntPtr ptr) => ptr.ToString("X")))));
			IntPtr intPtr3 = XrefScannerLowLevel.JumpTargets(intPtr2, false).First();
			global::JevilPlugin.JevilPlugin.Log($"Found GetManagerFromContext @ ptr {intPtr3:X}");
			GetManagerFromContext = Marshal.GetDelegateForFunctionPointer<GetManagerFromContextDelegate>(intPtr3);
		}
	}
}