Decompiled source of WhiteKnuckleArchipelago v1.0.2

BepInEx/plugins/WKRando/ALINE.dll

Decompiled 3 hours ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using AOT;
using Drawing;
using Drawing.Text;
using Microsoft.CodeAnalysis;
using Unity.Burst;
using Unity.Burst.CompilerServices;
using Unity.Burst.Intrinsics;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Mathematics;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: StaticTypeReinit(typeof(CommandBuilder.JobWireMesh.WireMesh_000000FE$BurstDirectCall))]
[assembly: StaticTypeReinit(typeof(CommandBuilder.JobWireMesh.Execute_000000FF$BurstDirectCall))]
[assembly: StaticTypeReinit(typeof(DrawingData.BuilderData.AnyBuffersWrittenTo_000002F4$BurstDirectCall))]
[assembly: StaticTypeReinit(typeof(DrawingData.BuilderData.ResetAllBuffers_000002F5$BurstDirectCall))]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
}
[CompilerGenerated]
[EditorBrowsable(EditorBrowsableState.Never)]
[GeneratedCode("Unity.MonoScriptGenerator.MonoScriptInfoGenerator", null)]
internal class UnitySourceGeneratedAssemblyMonoScriptTypes_v1
{
	private struct MonoScriptData
	{
		public byte[] FilePathsData;

		public byte[] TypesData;

		public int TotalTypes;

		public int TotalFiles;

		public bool IsEditorOnly;
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private static MonoScriptData Get()
	{
		return new MonoScriptData
		{
			FilePathsData = new byte[728]
			{
				0, 0, 0, 22, 0, 0, 0, 40, 92, 65,
				115, 115, 101, 116, 115, 92, 69, 120, 116, 101,
				114, 110, 97, 108, 92, 65, 76, 73, 78, 69,
				92, 67, 111, 109, 109, 97, 110, 100, 66, 117,
				105, 108, 100, 101, 114, 46, 99, 115, 0, 0,
				0, 1, 0, 0, 0, 42, 92, 65, 115, 115,
				101, 116, 115, 92, 69, 120, 116, 101, 114, 110,
				97, 108, 92, 65, 76, 73, 78, 69, 92, 67,
				111, 109, 109, 97, 110, 100, 66, 117, 105, 108,
				100, 101, 114, 50, 68, 46, 99, 115, 0, 0,
				0, 1, 0, 0, 0, 52, 92, 65, 115, 115,
				101, 116, 115, 92, 69, 120, 116, 101, 114, 110,
				97, 108, 92, 65, 76, 73, 78, 69, 92, 67,
				111, 109, 109, 97, 110, 100, 66, 117, 105, 108,
				100, 101, 114, 50, 68, 69, 120, 116, 101, 110,
				115, 105, 111, 110, 115, 46, 99, 115, 0, 0,
				0, 1, 0, 0, 0, 50, 92, 65, 115, 115,
				101, 116, 115, 92, 69, 120, 116, 101, 114, 110,
				97, 108, 92, 65, 76, 73, 78, 69, 92, 67,
				111, 109, 109, 97, 110, 100, 66, 117, 105, 108,
				100, 101, 114, 69, 120, 116, 101, 110, 115, 105,
				111, 110, 115, 46, 99, 115, 0, 0, 0, 1,
				0, 0, 0, 30, 92, 65, 115, 115, 101, 116,
				115, 92, 69, 120, 116, 101, 114, 110, 97, 108,
				92, 65, 76, 73, 78, 69, 92, 68, 114, 97,
				119, 46, 99, 115, 0, 0, 0, 19, 0, 0,
				0, 37, 92, 65, 115, 115, 101, 116, 115, 92,
				69, 120, 116, 101, 114, 110, 97, 108, 92, 65,
				76, 73, 78, 69, 92, 68, 114, 97, 119, 105,
				110, 103, 68, 97, 116, 97, 46, 99, 115, 0,
				0, 0, 4, 0, 0, 0, 40, 92, 65, 115,
				115, 101, 116, 115, 92, 69, 120, 116, 101, 114,
				110, 97, 108, 92, 65, 76, 73, 78, 69, 92,
				68, 114, 97, 119, 105, 110, 103, 77, 97, 110,
				97, 103, 101, 114, 46, 99, 115, 0, 0, 0,
				2, 0, 0, 0, 41, 92, 65, 115, 115, 101,
				116, 115, 92, 69, 120, 116, 101, 114, 110, 97,
				108, 92, 65, 76, 73, 78, 69, 92, 68, 114,
				97, 119, 105, 110, 103, 83, 101, 116, 116, 105,
				110, 103, 115, 46, 99, 115, 0, 0, 0, 1,
				0, 0, 0, 42, 92, 65, 115, 115, 101, 116,
				115, 92, 69, 120, 116, 101, 114, 110, 97, 108,
				92, 65, 76, 73, 78, 69, 92, 68, 114, 97,
				119, 105, 110, 103, 85, 116, 105, 108, 105, 116,
				105, 101, 115, 46, 99, 115, 0, 0, 0, 6,
				0, 0, 0, 41, 92, 65, 115, 115, 101, 116,
				115, 92, 69, 120, 116, 101, 114, 110, 97, 108,
				92, 65, 76, 73, 78, 69, 92, 71, 101, 111,
				109, 101, 116, 114, 121, 66, 117, 105, 108, 100,
				101, 114, 46, 99, 115, 0, 0, 0, 1, 0,
				0, 0, 45, 92, 65, 115, 115, 101, 116, 115,
				92, 69, 120, 116, 101, 114, 110, 97, 108, 92,
				65, 76, 73, 78, 69, 92, 77, 111, 110, 111,
				66, 101, 104, 97, 118, 105, 111, 117, 114, 71,
				105, 122, 109, 111, 115, 46, 99, 115, 0, 0,
				0, 5, 0, 0, 0, 33, 92, 65, 115, 115,
				101, 116, 115, 92, 69, 120, 116, 101, 114, 110,
				97, 108, 92, 65, 76, 73, 78, 69, 92, 80,
				97, 108, 101, 116, 116, 101, 46, 99, 115, 0,
				0, 0, 1, 0, 0, 0, 42, 92, 65, 115,
				115, 101, 116, 115, 92, 69, 120, 116, 101, 114,
				110, 97, 108, 92, 65, 76, 73, 78, 69, 92,
				80, 101, 114, 115, 105, 115, 116, 101, 110, 116,
				70, 105, 108, 116, 101, 114, 46, 99, 115, 0,
				0, 0, 4, 0, 0, 0, 33, 92, 65, 115,
				115, 101, 116, 115, 92, 69, 120, 116, 101, 114,
				110, 97, 108, 92, 65, 76, 73, 78, 69, 92,
				83, 68, 70, 70, 111, 110, 116, 46, 99, 115,
				0, 0, 0, 1, 0, 0, 0, 40, 92, 65,
				115, 115, 101, 116, 115, 92, 69, 120, 116, 101,
				114, 110, 97, 108, 92, 65, 76, 73, 78, 69,
				92, 83, 116, 114, 101, 97, 109, 83, 112, 108,
				105, 116, 116, 101, 114, 46, 99, 115
			},
			TypesData = new byte[2124]
			{
				0, 0, 0, 0, 22, 68, 114, 97, 119, 105,
				110, 103, 124, 76, 97, 98, 101, 108, 65, 108,
				105, 103, 110, 109, 101, 110, 116, 0, 0, 0,
				0, 30, 68, 114, 97, 119, 105, 110, 103, 124,
				67, 111, 109, 109, 97, 110, 100, 66, 117, 105,
				108, 100, 101, 114, 83, 97, 109, 112, 108, 101,
				114, 115, 1, 0, 0, 0, 22, 68, 114, 97,
				119, 105, 110, 103, 124, 67, 111, 109, 109, 97,
				110, 100, 66, 117, 105, 108, 100, 101, 114, 0,
				0, 0, 0, 21, 68, 114, 97, 119, 105, 110,
				103, 46, 124, 84, 114, 105, 97, 110, 103, 108,
				101, 68, 97, 116, 97, 0, 0, 0, 0, 17,
				68, 114, 97, 119, 105, 110, 103, 46, 124, 76,
				105, 110, 101, 68, 97, 116, 97, 0, 0, 0,
				0, 19, 68, 114, 97, 119, 105, 110, 103, 46,
				124, 76, 105, 110, 101, 68, 97, 116, 97, 86,
				51, 0, 0, 0, 0, 21, 68, 114, 97, 119,
				105, 110, 103, 46, 124, 67, 105, 114, 99, 108,
				101, 88, 90, 68, 97, 116, 97, 0, 0, 0,
				0, 19, 68, 114, 97, 119, 105, 110, 103, 46,
				124, 67, 105, 114, 99, 108, 101, 68, 97, 116,
				97, 0, 0, 0, 0, 19, 68, 114, 97, 119,
				105, 110, 103, 46, 124, 83, 112, 104, 101, 114,
				101, 68, 97, 116, 97, 0, 0, 0, 0, 16,
				68, 114, 97, 119, 105, 110, 103, 46, 124, 66,
				111, 120, 68, 97, 116, 97, 0, 0, 0, 0,
				18, 68, 114, 97, 119, 105, 110, 103, 46, 124,
				80, 108, 97, 110, 101, 68, 97, 116, 97, 0,
				0, 0, 0, 20, 68, 114, 97, 119, 105, 110,
				103, 46, 124, 80, 101, 114, 115, 105, 115, 116,
				68, 97, 116, 97, 0, 0, 0, 0, 22, 68,
				114, 97, 119, 105, 110, 103, 46, 124, 76, 105,
				110, 101, 87, 105, 100, 116, 104, 68, 97, 116,
				97, 0, 0, 0, 0, 17, 68, 114, 97, 119,
				105, 110, 103, 46, 124, 84, 101, 120, 116, 68,
				97, 116, 97, 0, 0, 0, 0, 19, 68, 114,
				97, 119, 105, 110, 103, 46, 124, 84, 101, 120,
				116, 68, 97, 116, 97, 51, 68, 0, 0, 0,
				0, 20, 68, 114, 97, 119, 105, 110, 103, 46,
				124, 83, 99, 111, 112, 101, 77, 97, 116, 114,
				105, 120, 0, 0, 0, 0, 19, 68, 114, 97,
				119, 105, 110, 103, 46, 124, 83, 99, 111, 112,
				101, 67, 111, 108, 111, 114, 0, 0, 0, 0,
				21, 68, 114, 97, 119, 105, 110, 103, 46, 124,
				83, 99, 111, 112, 101, 80, 101, 114, 115, 105,
				115, 116, 0, 0, 0, 0, 19, 68, 114, 97,
				119, 105, 110, 103, 46, 124, 83, 99, 111, 112,
				101, 69, 109, 112, 116, 121, 0, 0, 0, 0,
				23, 68, 114, 97, 119, 105, 110, 103, 46, 124,
				83, 99, 111, 112, 101, 76, 105, 110, 101, 87,
				105, 100, 116, 104, 0, 0, 0, 0, 27, 68,
				114, 97, 119, 105, 110, 103, 46, 124, 80, 111,
				108, 121, 108, 105, 110, 101, 87, 105, 116, 104,
				83, 121, 109, 98, 111, 108, 0, 0, 0, 0,
				20, 68, 114, 97, 119, 105, 110, 103, 46, 124,
				74, 111, 98, 87, 105, 114, 101, 77, 101, 115,
				104, 1, 0, 0, 0, 24, 68, 114, 97, 119,
				105, 110, 103, 124, 67, 111, 109, 109, 97, 110,
				100, 66, 117, 105, 108, 100, 101, 114, 50, 68,
				1, 0, 0, 0, 24, 68, 114, 97, 119, 105,
				110, 103, 124, 67, 111, 109, 109, 97, 110, 100,
				66, 117, 105, 108, 100, 101, 114, 50, 68, 1,
				0, 0, 0, 22, 68, 114, 97, 119, 105, 110,
				103, 124, 67, 111, 109, 109, 97, 110, 100, 66,
				117, 105, 108, 100, 101, 114, 0, 0, 0, 0,
				12, 68, 114, 97, 119, 105, 110, 103, 124, 68,
				114, 97, 119, 0, 0, 0, 0, 25, 68, 114,
				97, 119, 105, 110, 103, 124, 83, 104, 97, 114,
				101, 100, 68, 114, 97, 119, 105, 110, 103, 68,
				97, 116, 97, 0, 0, 0, 0, 38, 68, 114,
				97, 119, 105, 110, 103, 46, 83, 104, 97, 114,
				101, 100, 68, 114, 97, 119, 105, 110, 103, 68,
				97, 116, 97, 124, 66, 117, 114, 115, 116, 84,
				105, 109, 101, 75, 101, 121, 0, 0, 0, 0,
				19, 68, 114, 97, 119, 105, 110, 103, 124, 82,
				101, 100, 114, 97, 119, 83, 99, 111, 112, 101,
				0, 0, 0, 0, 19, 68, 114, 97, 119, 105,
				110, 103, 124, 68, 114, 97, 119, 105, 110, 103,
				68, 97, 116, 97, 0, 0, 0, 0, 26, 68,
				114, 97, 119, 105, 110, 103, 46, 68, 114, 97,
				119, 105, 110, 103, 68, 97, 116, 97, 124, 72,
				97, 115, 104, 101, 114, 0, 0, 0, 0, 40,
				68, 114, 97, 119, 105, 110, 103, 46, 68, 114,
				97, 119, 105, 110, 103, 68, 97, 116, 97, 124,
				80, 114, 111, 99, 101, 115, 115, 101, 100, 66,
				117, 105, 108, 100, 101, 114, 68, 97, 116, 97,
				0, 0, 0, 0, 34, 68, 114, 97, 119, 105,
				110, 103, 46, 68, 114, 97, 119, 105, 110, 103,
				68, 97, 116, 97, 43, 124, 67, 97, 112, 116,
				117, 114, 101, 100, 83, 116, 97, 116, 101, 0,
				0, 0, 0, 32, 68, 114, 97, 119, 105, 110,
				103, 46, 68, 114, 97, 119, 105, 110, 103, 68,
				97, 116, 97, 43, 124, 77, 101, 115, 104, 66,
				117, 102, 102, 101, 114, 115, 0, 0, 0, 0,
				33, 68, 114, 97, 119, 105, 110, 103, 46, 68,
				114, 97, 119, 105, 110, 103, 68, 97, 116, 97,
				124, 83, 117, 98, 109, 105, 116, 116, 101, 100,
				77, 101, 115, 104, 0, 0, 0, 0, 31, 68,
				114, 97, 119, 105, 110, 103, 46, 68, 114, 97,
				119, 105, 110, 103, 68, 97, 116, 97, 124, 66,
				117, 105, 108, 100, 101, 114, 68, 97, 116, 97,
				0, 0, 0, 0, 25, 68, 114, 97, 119, 105,
				110, 103, 46, 68, 114, 97, 119, 105, 110, 103,
				68, 97, 116, 97, 43, 124, 77, 101, 116, 97,
				0, 0, 0, 0, 34, 68, 114, 97, 119, 105,
				110, 103, 46, 68, 114, 97, 119, 105, 110, 103,
				68, 97, 116, 97, 43, 124, 66, 105, 116, 80,
				97, 99, 107, 101, 100, 77, 101, 116, 97, 0,
				0, 0, 0, 40, 68, 114, 97, 119, 105, 110,
				103, 46, 68, 114, 97, 119, 105, 110, 103, 68,
				97, 116, 97, 124, 66, 117, 105, 108, 100, 101,
				114, 68, 97, 116, 97, 67, 111, 110, 116, 97,
				105, 110, 101, 114, 0, 0, 0, 0, 49, 68,
				114, 97, 119, 105, 110, 103, 46, 68, 114, 97,
				119, 105, 110, 103, 68, 97, 116, 97, 124, 80,
				114, 111, 99, 101, 115, 115, 101, 100, 66, 117,
				105, 108, 100, 101, 114, 68, 97, 116, 97, 67,
				111, 110, 116, 97, 105, 110, 101, 114, 0, 0,
				0, 0, 32, 68, 114, 97, 119, 105, 110, 103,
				46, 68, 114, 97, 119, 105, 110, 103, 68, 97,
				116, 97, 124, 77, 101, 115, 104, 87, 105, 116,
				104, 84, 121, 112, 101, 0, 0, 0, 0, 40,
				68, 114, 97, 119, 105, 110, 103, 46, 68, 114,
				97, 119, 105, 110, 103, 68, 97, 116, 97, 124,
				82, 101, 110, 100, 101, 114, 101, 100, 77, 101,
				115, 104, 87, 105, 116, 104, 84, 121, 112, 101,
				0, 0, 0, 0, 25, 68, 114, 97, 119, 105,
				110, 103, 46, 68, 114, 97, 119, 105, 110, 103,
				68, 97, 116, 97, 124, 82, 97, 110, 103, 101,
				0, 0, 0, 0, 45, 68, 114, 97, 119, 105,
				110, 103, 46, 68, 114, 97, 119, 105, 110, 103,
				68, 97, 116, 97, 124, 77, 101, 115, 104, 67,
				111, 109, 112, 97, 114, 101, 66, 121, 68, 114,
				97, 119, 105, 110, 103, 79, 114, 100, 101, 114,
				0, 0, 0, 0, 40, 68, 114, 97, 119, 105,
				110, 103, 46, 68, 114, 97, 119, 105, 110, 103,
				68, 97, 116, 97, 124, 67, 111, 109, 109, 97,
				110, 100, 66, 117, 102, 102, 101, 114, 87, 114,
				97, 112, 112, 101, 114, 0, 0, 0, 0, 20,
				68, 114, 97, 119, 105, 110, 103, 124, 71, 105,
				122, 109, 111, 67, 111, 110, 116, 101, 120, 116,
				0, 0, 0, 0, 19, 68, 114, 97, 119, 105,
				110, 103, 124, 73, 68, 114, 97, 119, 71, 105,
				122, 109, 111, 115, 0, 0, 0, 0, 22, 68,
				114, 97, 119, 105, 110, 103, 124, 68, 114, 97,
				119, 105, 110, 103, 77, 97, 110, 97, 103, 101,
				114, 0, 0, 0, 0, 39, 68, 114, 97, 119,
				105, 110, 103, 46, 68, 114, 97, 119, 105, 110,
				103, 77, 97, 110, 97, 103, 101, 114, 124, 71,
				105, 122, 109, 111, 68, 114, 97, 119, 101, 114,
				71, 114, 111, 117, 112, 0, 0, 0, 0, 23,
				68, 114, 97, 119, 105, 110, 103, 124, 68, 114,
				97, 119, 105, 110, 103, 83, 101, 116, 116, 105,
				110, 103, 115, 0, 0, 0, 0, 32, 68, 114,
				97, 119, 105, 110, 103, 46, 68, 114, 97, 119,
				105, 110, 103, 83, 101, 116, 116, 105, 110, 103,
				115, 124, 83, 101, 116, 116, 105, 110, 103, 115,
				0, 0, 0, 0, 24, 68, 114, 97, 119, 105,
				110, 103, 124, 68, 114, 97, 119, 105, 110, 103,
				85, 116, 105, 108, 105, 116, 105, 101, 115, 0,
				0, 0, 0, 23, 68, 114, 97, 119, 105, 110,
				103, 124, 71, 101, 111, 109, 101, 116, 114, 121,
				66, 117, 105, 108, 100, 101, 114, 0, 0, 0,
				0, 34, 68, 114, 97, 119, 105, 110, 103, 46,
				71, 101, 111, 109, 101, 116, 114, 121, 66, 117,
				105, 108, 100, 101, 114, 124, 67, 97, 109, 101,
				114, 97, 73, 110, 102, 111, 0, 0, 0, 0,
				19, 68, 114, 97, 119, 105, 110, 103, 124, 77,
				101, 115, 104, 76, 97, 121, 111, 117, 116, 115,
				0, 0, 0, 0, 26, 68, 114, 97, 119, 105,
				110, 103, 124, 71, 101, 111, 109, 101, 116, 114,
				121, 66, 117, 105, 108, 100, 101, 114, 74, 111,
				98, 0, 0, 0, 0, 15, 68, 114, 97, 119,
				105, 110, 103, 46, 124, 86, 101, 114, 116, 101,
				120, 0, 0, 0, 0, 19, 68, 114, 97, 119,
				105, 110, 103, 46, 124, 84, 101, 120, 116, 86,
				101, 114, 116, 101, 120, 0, 0, 0, 0, 27,
				68, 114, 97, 119, 105, 110, 103, 124, 77, 111,
				110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
				114, 71, 105, 122, 109, 111, 115, 0, 0, 0,
				0, 15, 68, 114, 97, 119, 105, 110, 103, 124,
				80, 97, 108, 101, 116, 116, 101, 0, 0, 0,
				0, 20, 68, 114, 97, 119, 105, 110, 103, 46,
				80, 97, 108, 101, 116, 116, 101, 124, 80, 117,
				114, 101, 0, 0, 0, 0, 27, 68, 114, 97,
				119, 105, 110, 103, 46, 80, 97, 108, 101, 116,
				116, 101, 124, 67, 111, 108, 111, 114, 98, 114,
				101, 119, 101, 114, 0, 0, 0, 0, 32, 68,
				114, 97, 119, 105, 110, 103, 46, 80, 97, 108,
				101, 116, 116, 101, 43, 67, 111, 108, 111, 114,
				98, 114, 101, 119, 101, 114, 124, 83, 101, 116,
				49, 0, 0, 0, 0, 33, 68, 114, 97, 119,
				105, 110, 103, 46, 80, 97, 108, 101, 116, 116,
				101, 43, 67, 111, 108, 111, 114, 98, 114, 101,
				119, 101, 114, 124, 66, 108, 117, 101, 115, 0,
				0, 0, 0, 27, 68, 114, 97, 119, 105, 110,
				103, 124, 80, 101, 114, 115, 105, 115, 116, 101,
				110, 116, 70, 105, 108, 116, 101, 114, 74, 111,
				98, 0, 0, 0, 0, 25, 68, 114, 97, 119,
				105, 110, 103, 46, 84, 101, 120, 116, 124, 83,
				68, 70, 67, 104, 97, 114, 97, 99, 116, 101,
				114, 0, 0, 0, 0, 20, 68, 114, 97, 119,
				105, 110, 103, 46, 84, 101, 120, 116, 124, 83,
				68, 70, 70, 111, 110, 116, 0, 0, 0, 0,
				26, 68, 114, 97, 119, 105, 110, 103, 46, 84,
				101, 120, 116, 124, 83, 68, 70, 76, 111, 111,
				107, 117, 112, 68, 97, 116, 97, 0, 0, 0,
				0, 25, 68, 114, 97, 119, 105, 110, 103, 46,
				84, 101, 120, 116, 124, 68, 101, 102, 97, 117,
				108, 116, 70, 111, 110, 116, 115, 0, 0, 0,
				0, 22, 68, 114, 97, 119, 105, 110, 103, 124,
				83, 116, 114, 101, 97, 109, 83, 112, 108, 105,
				116, 116, 101, 114
			},
			TotalFiles = 15,
			TotalTypes = 70,
			IsEditorOnly = false
		};
	}
}
namespace Drawing
{
	public struct LabelAlignment
	{
		public float2 relativePivot;

		public float2 pixelOffset;

		public static readonly LabelAlignment TopLeft = new LabelAlignment
		{
			relativePivot = new float2(0f, 1f),
			pixelOffset = new float2(0f, 0f)
		};

		public static readonly LabelAlignment MiddleLeft = new LabelAlignment
		{
			relativePivot = new float2(0f, 0.5f),
			pixelOffset = new float2(0f, 0f)
		};

		public static readonly LabelAlignment BottomLeft = new LabelAlignment
		{
			relativePivot = new float2(0f, 0f),
			pixelOffset = new float2(0f, 0f)
		};

		public static readonly LabelAlignment BottomCenter = new LabelAlignment
		{
			relativePivot = new float2(0.5f, 0f),
			pixelOffset = new float2(0f, 0f)
		};

		public static readonly LabelAlignment BottomRight = new LabelAlignment
		{
			relativePivot = new float2(1f, 0f),
			pixelOffset = new float2(0f, 0f)
		};

		public static readonly LabelAlignment MiddleRight = new LabelAlignment
		{
			relativePivot = new float2(1f, 0.5f),
			pixelOffset = new float2(0f, 0f)
		};

		public static readonly LabelAlignment TopRight = new LabelAlignment
		{
			relativePivot = new float2(1f, 1f),
			pixelOffset = new float2(0f, 0f)
		};

		public static readonly LabelAlignment TopCenter = new LabelAlignment
		{
			relativePivot = new float2(0.5f, 1f),
			pixelOffset = new float2(0f, 0f)
		};

		public static readonly LabelAlignment Center = new LabelAlignment
		{
			relativePivot = new float2(0.5f, 0.5f),
			pixelOffset = new float2(0f, 0f)
		};

		public LabelAlignment withPixelOffset(float x, float y)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			return new LabelAlignment
			{
				relativePivot = relativePivot,
				pixelOffset = new float2(x, y)
			};
		}
	}
	public enum AllowedDelay
	{
		EndOfFrame,
		Infinite
	}
	internal static class CommandBuilderSamplers
	{
		internal static readonly ProfilerMarker MarkerConvert = new ProfilerMarker("Convert");

		internal static readonly ProfilerMarker MarkerSetLayout = new ProfilerMarker("SetLayout");

		internal static readonly ProfilerMarker MarkerUpdateVertices = new ProfilerMarker("UpdateVertices");

		internal static readonly ProfilerMarker MarkerUpdateIndices = new ProfilerMarker("UpdateIndices");

		internal static readonly ProfilerMarker MarkerSubmesh = new ProfilerMarker("Submesh");

		internal static readonly ProfilerMarker MarkerUpdateBuffer = new ProfilerMarker("UpdateComputeBuffer");

		internal static readonly ProfilerMarker MarkerProcessCommands = new ProfilerMarker("Commands");

		internal static readonly ProfilerMarker MarkerCreateTriangles = new ProfilerMarker("CreateTriangles");
	}
	[BurstCompile]
	public struct CommandBuilder : IDisposable
	{
		[Flags]
		internal enum Command
		{
			PushColorInline = 0x100,
			PushColor = 0,
			PopColor = 1,
			PushMatrix = 2,
			PushSetMatrix = 3,
			PopMatrix = 4,
			Line = 5,
			Circle = 6,
			CircleXZ = 7,
			Disc = 8,
			DiscXZ = 9,
			SphereOutline = 0xA,
			Box = 0xB,
			WirePlane = 0xC,
			WireBox = 0xD,
			SolidTriangle = 0xE,
			PushPersist = 0xF,
			PopPersist = 0x10,
			Text = 0x11,
			Text3D = 0x12,
			PushLineWidth = 0x13,
			PopLineWidth = 0x14,
			CaptureState = 0x15
		}

		internal struct TriangleData
		{
			public float3 a;

			public float3 b;

			public float3 c;
		}

		internal struct LineData
		{
			public float3 a;

			public float3 b;
		}

		internal struct LineDataV3
		{
			public Vector3 a;

			public Vector3 b;
		}

		internal struct CircleXZData
		{
			public float3 center;

			public float radius;

			public float startAngle;

			public float endAngle;
		}

		internal struct CircleData
		{
			public float3 center;

			public float3 normal;

			public float radius;
		}

		internal struct SphereData
		{
			public float3 center;

			public float radius;
		}

		internal struct BoxData
		{
			public float3 center;

			public float3 size;
		}

		internal struct PlaneData
		{
			public float3 center;

			public quaternion rotation;

			public float2 size;
		}

		internal struct PersistData
		{
			public float endTime;
		}

		internal struct LineWidthData
		{
			public float pixels;

			public bool automaticJoins;
		}

		internal struct TextData
		{
			public float3 center;

			public LabelAlignment alignment;

			public float sizeInPixels;

			public int numCharacters;
		}

		internal struct TextData3D
		{
			public float3 center;

			public quaternion rotation;

			public LabelAlignment alignment;

			public float size;

			public int numCharacters;
		}

		public struct ScopeMatrix : IDisposable
		{
			internal CommandBuilder builder;

			public unsafe void Dispose()
			{
				builder.PopMatrix();
				builder.buffer = null;
			}
		}

		public struct ScopeColor : IDisposable
		{
			internal CommandBuilder builder;

			public unsafe void Dispose()
			{
				builder.PopColor();
				builder.buffer = null;
			}
		}

		public struct ScopePersist : IDisposable
		{
			internal CommandBuilder builder;

			public unsafe void Dispose()
			{
				builder.PopDuration();
				builder.buffer = null;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct ScopeEmpty : IDisposable
		{
			public void Dispose()
			{
			}
		}

		public struct ScopeLineWidth : IDisposable
		{
			internal CommandBuilder builder;

			public unsafe void Dispose()
			{
				builder.PopLineWidth();
				builder.buffer = null;
			}
		}

		public enum SymbolDecoration
		{
			None,
			ArrowHead,
			Circle
		}

		public struct PolylineWithSymbol
		{
			private float3 prev;

			private float offset;

			private readonly float symbolSize;

			private readonly float symbolSpacing;

			private readonly float symbolPadding;

			private readonly float symbolOffset;

			private readonly SymbolDecoration symbol;

			private readonly bool reverseSymbols;

			private bool odd;

			public PolylineWithSymbol(SymbolDecoration symbol, float symbolSize, float symbolPadding, float symbolSpacing, bool reverseSymbols = false)
			{
				//IL_004a: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				if (symbolSpacing <= 1.1754944E-38f)
				{
					throw new ArgumentOutOfRangeException("symbolSpacing", "Symbol spacing must be greater than zero");
				}
				if (symbolSize <= 1.1754944E-38f)
				{
					throw new ArgumentOutOfRangeException("symbolSize", "Symbol size must be greater than zero");
				}
				if (symbolPadding < 0f)
				{
					throw new ArgumentOutOfRangeException("symbolPadding", "Symbol padding must non-negative");
				}
				prev = float3.zero;
				this.symbol = symbol;
				this.symbolSize = symbolSize;
				this.symbolPadding = symbolPadding;
				this.symbolSpacing = math.max(0f, symbolSpacing - symbolPadding * 2f - symbolSize);
				this.reverseSymbols = reverseSymbols;
				symbolOffset = ((symbol == SymbolDecoration.ArrowHead) ? (-0.25f * symbolSize) : 0f);
				if (reverseSymbols)
				{
					symbolOffset = 0f - symbolOffset;
				}
				symbolOffset += 0.5f * symbolSize;
				offset = -1f;
				odd = false;
			}

			public void MoveTo(ref CommandBuilder draw, float3 next)
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_005d: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_006e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0085: Unknown result type (might be due to invalid IL or missing references)
				//IL_0087: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0093: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00be: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0223: Unknown result type (might be due to invalid IL or missing references)
				//IL_0224: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
				//IL_017f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0184: Unknown result type (might be due to invalid IL or missing references)
				//IL_0194: Unknown result type (might be due to invalid IL or missing references)
				//IL_0199: Unknown result type (might be due to invalid IL or missing references)
				//IL_0117: Unknown result type (might be due to invalid IL or missing references)
				//IL_011c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0125: Unknown result type (might be due to invalid IL or missing references)
				//IL_012a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0140: Unknown result type (might be due to invalid IL or missing references)
				//IL_0145: Unknown result type (might be due to invalid IL or missing references)
				//IL_0158: Unknown result type (might be due to invalid IL or missing references)
				//IL_015d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0160: Unknown result type (might be due to invalid IL or missing references)
				//IL_0162: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
				//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
				if (offset == -1f)
				{
					offset = symbolSpacing * 0.5f;
					prev = next;
					return;
				}
				float num = math.length(next - prev);
				float num2 = math.rcp(num);
				float3 val = next - prev;
				float3 val2 = default(float3);
				if (symbol != SymbolDecoration.None)
				{
					val2 = math.normalizesafe(math.cross(val, math.cross(val, new float3(0f, 1f, 0f))), default(float3));
					if (math.all(val2 == 0f))
					{
						((float3)(ref val2))..ctor(0f, 0f, 1f);
					}
				}
				if (reverseSymbols)
				{
					val = -val;
				}
				if (offset > 0f && !odd)
				{
					draw.Line(prev, math.lerp(prev, next, math.min(offset * num2, 1f)));
				}
				while (offset < num)
				{
					if (odd)
					{
						float3 a = math.lerp(prev, next, offset * num2);
						offset += symbolSpacing;
						float3 b = math.lerp(prev, next, math.min(offset * num2, 1f));
						draw.Line(a, b);
						offset += symbolPadding;
					}
					else
					{
						float3 center = math.lerp(prev, next, (offset + symbolOffset) * num2);
						switch (symbol)
						{
						case SymbolDecoration.ArrowHead:
							draw.Arrowhead(center, val, val2, symbolSize);
							break;
						default:
							draw.Circle(center, val2, symbolSize * 0.5f);
							break;
						case SymbolDecoration.None:
							break;
						}
						offset += symbolSize + symbolPadding;
					}
					odd = !odd;
				}
				offset -= num;
				prev = next;
			}
		}

		[BurstCompile]
		private class JobWireMesh
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public delegate void JobWireMeshDelegate(ref MeshData rawMeshData, ref CommandBuilder draw);

			internal unsafe delegate void WireMesh_000000FE$PostfixBurstDelegate(float3* verts, int* indices, int vertexCount, int indexCount, ref CommandBuilder draw);

			internal static class WireMesh_000000FE$BurstDirectCall
			{
				private static IntPtr Pointer;

				private static IntPtr DeferredCompilation;

				[BurstDiscard]
				private unsafe static void GetFunctionPointerDiscard(ref IntPtr P_0)
				{
					if (Pointer == (IntPtr)0)
					{
						Pointer = (nint)BurstCompiler.GetILPPMethodFunctionPointer2(DeferredCompilation, (RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/, typeof(WireMesh_000000FE$PostfixBurstDelegate).TypeHandle);
					}
					P_0 = Pointer;
				}

				private static IntPtr GetFunctionPointer()
				{
					nint result = 0;
					GetFunctionPointerDiscard(ref result);
					return result;
				}

				public static void Constructor()
				{
					DeferredCompilation = BurstCompiler.CompileILPPMethod2((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/);
				}

				public static void Initialize()
				{
				}

				static WireMesh_000000FE$BurstDirectCall()
				{
					Constructor();
				}

				public unsafe static void Invoke(float3* verts, int* indices, int vertexCount, int indexCount, ref CommandBuilder draw)
				{
					if (BurstCompiler.IsEnabled)
					{
						IntPtr functionPointer = GetFunctionPointer();
						if (functionPointer != (IntPtr)0)
						{
							((delegate* unmanaged[Cdecl]<float3*, int*, int, int, ref CommandBuilder, void>)functionPointer)(verts, indices, vertexCount, indexCount, ref draw);
							return;
						}
					}
					WireMesh$BurstManaged(verts, indices, vertexCount, indexCount, ref draw);
				}
			}

			internal delegate void Execute_000000FF$PostfixBurstDelegate(ref MeshData rawMeshData, ref CommandBuilder draw);

			internal static class Execute_000000FF$BurstDirectCall
			{
				private static IntPtr Pointer;

				private static IntPtr DeferredCompilation;

				[BurstDiscard]
				private unsafe static void GetFunctionPointerDiscard(ref IntPtr P_0)
				{
					if (Pointer == (IntPtr)0)
					{
						Pointer = (nint)BurstCompiler.GetILPPMethodFunctionPointer2(DeferredCompilation, (RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/, typeof(Execute_000000FF$PostfixBurstDelegate).TypeHandle);
					}
					P_0 = Pointer;
				}

				private static IntPtr GetFunctionPointer()
				{
					nint result = 0;
					GetFunctionPointerDiscard(ref result);
					return result;
				}

				public static void Constructor()
				{
					DeferredCompilation = BurstCompiler.CompileILPPMethod2((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/);
				}

				public static void Initialize()
				{
				}

				static Execute_000000FF$BurstDirectCall()
				{
					Constructor();
				}

				public unsafe static void Invoke(ref MeshData rawMeshData, ref CommandBuilder draw)
				{
					if (BurstCompiler.IsEnabled)
					{
						IntPtr functionPointer = GetFunctionPointer();
						if (functionPointer != (IntPtr)0)
						{
							((delegate* unmanaged[Cdecl]<ref MeshData, ref CommandBuilder, void>)functionPointer)(ref rawMeshData, ref draw);
							return;
						}
					}
					Execute$BurstManaged(ref rawMeshData, ref draw);
				}
			}

			public static readonly JobWireMeshDelegate JobWireMeshFunctionPointer = BurstCompiler.CompileFunctionPointer<JobWireMeshDelegate>((JobWireMeshDelegate)Execute).Invoke;

			[BurstCompile]
			public unsafe static void WireMesh(float3* verts, int* indices, int vertexCount, int indexCount, ref CommandBuilder draw)
			{
				WireMesh_000000FE$BurstDirectCall.Invoke(verts, indices, vertexCount, indexCount, ref draw);
			}

			[BurstCompile]
			[MonoPInvokeCallback(typeof(JobWireMeshDelegate))]
			private static void Execute(ref MeshData rawMeshData, ref CommandBuilder draw)
			{
				Execute_000000FF$BurstDirectCall.Invoke(ref rawMeshData, ref draw);
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			[BurstCompile]
			internal unsafe static void WireMesh$BurstManaged(float3* verts, int* indices, int vertexCount, int indexCount, ref CommandBuilder draw)
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00df: Unknown result type (might be due to invalid IL or missing references)
				//IL_0091: Unknown result type (might be due to invalid IL or missing references)
				//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
				//IL_013f: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_010a: Unknown result type (might be due to invalid IL or missing references)
				//IL_011b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0151: Unknown result type (might be due to invalid IL or missing references)
				//IL_016a: Unknown result type (might be due to invalid IL or missing references)
				//IL_017b: Unknown result type (might be due to invalid IL or missing references)
				if (indexCount % 3 != 0)
				{
					throw new ArgumentException("Invalid index count. Must be a multiple of 3");
				}
				NativeHashMap<int2, bool> val = default(NativeHashMap<int2, bool>);
				val..ctor(indexCount, AllocatorHandle.op_Implicit((Allocator)2));
				for (int i = 0; i < indexCount; i += 3)
				{
					int num = indices[i];
					int num2 = indices[i + 1];
					int num3 = indices[i + 2];
					if (num < 0 || num2 < 0 || num3 < 0 || num >= vertexCount || num2 >= vertexCount || num3 >= vertexCount)
					{
						throw new Exception("Invalid vertex index. Index out of bounds");
					}
					int num4 = math.min(num, num2);
					int num5 = math.max(num, num2);
					if (!val.ContainsKey(new int2(num4, num5)))
					{
						val.Add(new int2(num4, num5), true);
						draw.Line(((float3*)verts)[num4], ((float3*)verts)[num5]);
					}
					num4 = math.min(num2, num3);
					num5 = math.max(num2, num3);
					if (!val.ContainsKey(new int2(num4, num5)))
					{
						val.Add(new int2(num4, num5), true);
						draw.Line(((float3*)verts)[num4], ((float3*)verts)[num5]);
					}
					num4 = math.min(num3, num);
					num5 = math.max(num3, num);
					if (!val.ContainsKey(new int2(num4, num5)))
					{
						val.Add(new int2(num4, num5), true);
						draw.Line(((float3*)verts)[num4], ((float3*)verts)[num5]);
					}
				}
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			[BurstCompile]
			[MonoPInvokeCallback(typeof(JobWireMeshDelegate))]
			internal unsafe static void Execute$BurstManaged(ref MeshData rawMeshData, ref CommandBuilder draw)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Unknown result type (might be due to invalid IL or missing references)
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_0069: Unknown result type (might be due to invalid IL or missing references)
				int num = 0;
				for (int i = 0; i < ((MeshData)(ref rawMeshData)).subMeshCount; i++)
				{
					int num2 = num;
					SubMeshDescriptor subMesh = ((MeshData)(ref rawMeshData)).GetSubMesh(i);
					num = math.max(num2, ((SubMeshDescriptor)(ref subMesh)).indexCount);
				}
				NativeArray<int> val = default(NativeArray<int>);
				val..ctor(num, (Allocator)2, (NativeArrayOptions)0);
				NativeArray<Vector3> val2 = default(NativeArray<Vector3>);
				val2..ctor(((MeshData)(ref rawMeshData)).vertexCount, (Allocator)2, (NativeArrayOptions)0);
				((MeshData)(ref rawMeshData)).GetVertices(val2);
				for (int j = 0; j < ((MeshData)(ref rawMeshData)).subMeshCount; j++)
				{
					SubMeshDescriptor subMesh2 = ((MeshData)(ref rawMeshData)).GetSubMesh(j);
					((MeshData)(ref rawMeshData)).GetIndices(val, j, true);
					WireMesh((float3*)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr<Vector3>(val2), (int*)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr<int>(val), val2.Length, ((SubMeshDescriptor)(ref subMesh2)).indexCount, ref draw);
				}
			}
		}

		[NativeDisableUnsafePtrRestriction]
		internal unsafe UnsafeAppendBuffer* buffer;

		private GCHandle gizmos;

		[NativeSetThreadIndex]
		private int threadIndex;

		private DrawingData.BuilderData.BitPackedMeta uniqueID;

		private static readonly float3 DEFAULT_UP = new float3(0f, 1f, 0f);

		internal static readonly float4x4 XZtoXYPlaneMatrix = float4x4.RotateX(-MathF.PI / 2f);

		internal static readonly float4x4 XZtoYZPlaneMatrix = float4x4.RotateZ(MathF.PI / 2f);

		internal unsafe int BufferSize
		{
			get
			{
				return ((UnsafeAppendBuffer)buffer).Length;
			}
			set
			{
				((UnsafeAppendBuffer)buffer).Length = value;
			}
		}

		public CommandBuilder2D xy => new CommandBuilder2D(this, xy: true);

		public CommandBuilder2D xz => new CommandBuilder2D(this, xy: false);

		public Camera[] cameraTargets
		{
			get
			{
				if (gizmos.IsAllocated && gizmos.Target != null)
				{
					DrawingData drawingData = gizmos.Target as DrawingData;
					if (drawingData.data.StillExists(uniqueID))
					{
						return drawingData.data.Get(uniqueID).meta.cameraTargets;
					}
				}
				throw new Exception("Cannot get cameraTargets because the command builder has already been disposed or does not exist.");
			}
			set
			{
				if (uniqueID.isBuiltInCommandBuilder)
				{
					throw new Exception("You cannot set the camera targets for a built-in command builder. Create a custom command builder instead.");
				}
				if (gizmos.IsAllocated && gizmos.Target != null)
				{
					DrawingData obj = gizmos.Target as DrawingData;
					if (!obj.data.StillExists(uniqueID))
					{
						throw new Exception("Cannot set cameraTargets because the command builder has already been disposed or does not exist.");
					}
					obj.data.Get(uniqueID).meta.cameraTargets = value;
				}
			}
		}

		internal unsafe CommandBuilder(UnsafeAppendBuffer* buffer, GCHandle gizmos, int threadIndex, DrawingData.BuilderData.BitPackedMeta uniqueID)
		{
			this.buffer = buffer;
			this.gizmos = gizmos;
			this.threadIndex = threadIndex;
			this.uniqueID = uniqueID;
		}

		internal unsafe CommandBuilder(DrawingData gizmos, DrawingData.Hasher hasher, RedrawScope frameRedrawScope, RedrawScope customRedrawScope, bool isGizmos, bool isBuiltInCommandBuilder, int sceneModeVersion)
		{
			this.gizmos = GCHandle.Alloc(gizmos, GCHandleType.Normal);
			threadIndex = 0;
			uniqueID = gizmos.data.Reserve(isBuiltInCommandBuilder);
			gizmos.data.Get(uniqueID).Init(hasher, frameRedrawScope, customRedrawScope, isGizmos, gizmos.GetNextDrawOrderIndex(), sceneModeVersion);
			buffer = gizmos.data.Get(uniqueID).bufferPtr;
		}

		public void Dispose()
		{
			if (uniqueID.isBuiltInCommandBuilder)
			{
				throw new Exception("You cannot dispose a built-in command builder");
			}
			DisposeInternal();
		}

		public void DisposeAfter(JobHandle dependency, AllowedDelay allowedDelay = AllowedDelay.EndOfFrame)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			if (!gizmos.IsAllocated)
			{
				throw new Exception("You cannot dispose an invalid command builder. Are you trying to dispose it twice?");
			}
			try
			{
				if (gizmos.IsAllocated && gizmos.Target != null)
				{
					DrawingData obj = gizmos.Target as DrawingData;
					if (!obj.data.StillExists(uniqueID))
					{
						throw new Exception("Cannot dispose the command builder because the drawing manager has been destroyed");
					}
					obj.data.Get(uniqueID).SubmitWithDependency(gizmos, dependency, allowedDelay);
				}
			}
			finally
			{
				this = default(CommandBuilder);
			}
		}

		internal void DisposeInternal()
		{
			if (!gizmos.IsAllocated)
			{
				throw new Exception("You cannot dispose an invalid command builder. Are you trying to dispose it twice?");
			}
			try
			{
				if (gizmos.IsAllocated && gizmos.Target != null)
				{
					DrawingData obj = gizmos.Target as DrawingData;
					if (!obj.data.StillExists(uniqueID))
					{
						throw new Exception("Cannot dispose the command builder because the drawing manager has been destroyed");
					}
					obj.data.Get(uniqueID).Submit(gizmos.Target as DrawingData);
				}
			}
			finally
			{
				gizmos.Free();
				this = default(CommandBuilder);
			}
		}

		public void DiscardAndDispose()
		{
			if (uniqueID.isBuiltInCommandBuilder)
			{
				throw new Exception("You cannot dispose a built-in command builder");
			}
			DiscardAndDisposeInternal();
		}

		internal void DiscardAndDisposeInternal()
		{
			try
			{
				if (gizmos.IsAllocated && gizmos.Target != null)
				{
					DrawingData obj = gizmos.Target as DrawingData;
					if (!obj.data.StillExists(uniqueID))
					{
						throw new Exception("Cannot dispose the command builder because the drawing manager has been destroyed");
					}
					obj.data.Release(uniqueID);
				}
			}
			finally
			{
				if (gizmos.IsAllocated)
				{
					gizmos.Free();
				}
				this = default(CommandBuilder);
			}
		}

		public void Preallocate(int size)
		{
			Reserve(size);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe void Reserve(int additionalSpace)
		{
			if (Hint.Unlikely(threadIndex >= 0))
			{
				buffer = (UnsafeAppendBuffer*)((byte*)buffer + (nint)threadIndex * (nint)Unsafe.SizeOf<UnsafeAppendBuffer>());
				threadIndex = -1;
			}
			int num = ((UnsafeAppendBuffer)buffer).Length + additionalSpace;
			if (num > ((UnsafeAppendBuffer)buffer).Capacity)
			{
				((UnsafeAppendBuffer)buffer).SetCapacity(math.max(num, ((UnsafeAppendBuffer)buffer).Length * 2));
			}
		}

		[BurstDiscard]
		private void AssertBufferExists()
		{
			if (!gizmos.IsAllocated || gizmos.Target == null || !(gizmos.Target as DrawingData).data.StillExists(uniqueID))
			{
				this = default(CommandBuilder);
				throw new Exception("This command builder no longer exists. Are you trying to draw to a command builder which has already been disposed?");
			}
		}

		[BurstDiscard]
		private static void AssertNotRendering()
		{
			if (!GizmoContext.drawingGizmos && !JobsUtility.IsExecutingJob && (Time.renderedFrameCount & 0x7F) == 0 && StackTraceUtility.ExtractStackTrace().Contains("OnDrawGizmos"))
			{
				throw new Exception("You are trying to use Draw.* functions from within Unity's OnDrawGizmos function. Use this package's gizmo callbacks instead (see the documentation).");
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void Reserve<A>() where A : struct
		{
			Reserve(UnsafeUtility.SizeOf<Command>() + UnsafeUtility.SizeOf<A>());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void Reserve<A, B>() where A : struct where B : struct
		{
			Reserve(UnsafeUtility.SizeOf<Command>() * 2 + UnsafeUtility.SizeOf<A>() + UnsafeUtility.SizeOf<B>());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void Reserve<A, B, C>() where A : struct where B : struct where C : struct
		{
			Reserve(UnsafeUtility.SizeOf<Command>() * 3 + UnsafeUtility.SizeOf<A>() + UnsafeUtility.SizeOf<B>() + UnsafeUtility.SizeOf<C>());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static uint ConvertColor(Color color)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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_004a: 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_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			if (Sse2.IsSse2Supported)
			{
				int4 val = (int4)(255f * new float4(color.r, color.g, color.b, color.a) + 0.5f);
				v128 val2 = new v128(val.x, val.y, val.z, val.w);
				v128 val3 = Sse2.packs_epi32(val2, val2);
				return Sse2.packus_epi16(val3, val3).UInt0;
			}
			uint num = (uint)Mathf.Clamp((int)(color.r * 255f + 0.5f), 0, 255);
			uint num2 = (uint)Mathf.Clamp((int)(color.g * 255f + 0.5f), 0, 255);
			uint num3 = (uint)Mathf.Clamp((int)(color.b * 255f + 0.5f), 0, 255);
			return (uint)(Mathf.Clamp((int)(color.a * 255f + 0.5f), 0, 255) << 24) | (num3 << 16) | (num2 << 8) | num;
		}

		internal unsafe void Add<T>(T value) where T : struct
		{
			int num = UnsafeUtility.SizeOf<T>();
			UnsafeAppendBuffer* ptr = buffer;
			int length = ((UnsafeAppendBuffer)ptr).Length;
			Hint.Assume(((UnsafeAppendBuffer)ptr).Ptr != null);
			Hint.Assume(((UnsafeAppendBuffer)ptr).Ptr + length != null);
			UnsafeUtility.CopyStructureToPtr<T>(ref value, (void*)(((UnsafeAppendBuffer)ptr).Ptr + length));
			((UnsafeAppendBuffer)ptr).Length = length + num;
		}

		[BurstDiscard]
		public ScopeMatrix WithMatrix(Matrix4x4 matrix)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			PushMatrix(matrix);
			return new ScopeMatrix
			{
				builder = this
			};
		}

		[BurstDiscard]
		public ScopeMatrix WithMatrix(float3x3 matrix)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			this.PushMatrix(new float4x4(matrix, float3.zero));
			return new ScopeMatrix
			{
				builder = this
			};
		}

		[BurstDiscard]
		public ScopeColor WithColor(Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			PushColor(color);
			return new ScopeColor
			{
				builder = this
			};
		}

		[BurstDiscard]
		public ScopePersist WithDuration(float duration)
		{
			PushDuration(duration);
			return new ScopePersist
			{
				builder = this
			};
		}

		[BurstDiscard]
		public ScopeLineWidth WithLineWidth(float pixels, bool automaticJoins = true)
		{
			PushLineWidth(pixels, automaticJoins);
			return new ScopeLineWidth
			{
				builder = this
			};
		}

		[BurstDiscard]
		public ScopeMatrix InLocalSpace(Transform transform)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return WithMatrix(transform.localToWorldMatrix);
		}

		[BurstDiscard]
		public ScopeMatrix InScreenSpace(Camera camera)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			Matrix4x4 cameraToWorldMatrix = camera.cameraToWorldMatrix;
			Matrix4x4 nonJitteredProjectionMatrix = camera.nonJitteredProjectionMatrix;
			return WithMatrix(cameraToWorldMatrix * ((Matrix4x4)(ref nonJitteredProjectionMatrix)).inverse * Matrix4x4.TRS(new Vector3(-1f, -1f, 0f), Quaternion.identity, new Vector3(2f / (float)camera.pixelWidth, 2f / (float)camera.pixelHeight, 1f)));
		}

		public void PushMatrix(Matrix4x4 matrix)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			this.Reserve<float4x4>();
			Add(Command.PushMatrix);
			this.Add<Matrix4x4>(matrix);
		}

		public void PushMatrix(float4x4 matrix)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			this.Reserve<float4x4>();
			Add(Command.PushMatrix);
			this.Add<float4x4>(matrix);
		}

		public void PushSetMatrix(Matrix4x4 matrix)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			this.Reserve<float4x4>();
			Add(Command.PushSetMatrix);
			this.Add<float4x4>(float4x4.op_Implicit(matrix));
		}

		public void PushSetMatrix(float4x4 matrix)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			this.Reserve<float4x4>();
			Add(Command.PushSetMatrix);
			this.Add<float4x4>(matrix);
		}

		public void PopMatrix()
		{
			Reserve(4);
			Add(Command.PopMatrix);
		}

		public void PushColor(Color color)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			this.Reserve<Color32>();
			Add(Command.PushColor);
			Add(ConvertColor(color));
		}

		public void PopColor()
		{
			Reserve(4);
			Add(Command.PopColor);
		}

		public void PushDuration(float duration)
		{
			Reserve<PersistData>();
			Add(Command.PushPersist);
			Add(new PersistData
			{
				endTime = SharedDrawingData.BurstTime.Data + duration
			});
		}

		public void PopDuration()
		{
			Reserve(4);
			Add(Command.PopPersist);
		}

		[Obsolete("Renamed to PushDuration for consistency")]
		public void PushPersist(float duration)
		{
			PushDuration(duration);
		}

		[Obsolete("Renamed to PopDuration for consistency")]
		public void PopPersist()
		{
			PopDuration();
		}

		public void PushLineWidth(float pixels, bool automaticJoins = true)
		{
			if (pixels < 0f)
			{
				throw new ArgumentOutOfRangeException("pixels", "Line width must be positive");
			}
			Reserve<LineWidthData>();
			Add(Command.PushLineWidth);
			Add(new LineWidthData
			{
				pixels = pixels,
				automaticJoins = automaticJoins
			});
		}

		public void PopLineWidth()
		{
			Reserve(4);
			Add(Command.PopLineWidth);
		}

		public void Line(float3 a, float3 b)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			Reserve<LineData>();
			Add(Command.Line);
			Add(new LineData
			{
				a = a,
				b = b
			});
		}

		public unsafe void Line(Vector3 a, Vector3 b)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			Reserve<LineData>();
			int bufferSize = BufferSize;
			int length = bufferSize + 4 + 24;
			byte* num = ((UnsafeAppendBuffer)buffer).Ptr + bufferSize;
			*(int*)num = 5;
			LineDataV3* ptr = (LineDataV3*)(num + 4);
			Unsafe.Write(&ptr->a, a);
			Unsafe.Write(&ptr->b, b);
			((UnsafeAppendBuffer)buffer).Length = length;
		}

		public unsafe void Line(Vector3 a, Vector3 b, Color color)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			this.Reserve<Color32, LineData>();
			int bufferSize = BufferSize;
			int length = bufferSize + 4 + 24 + 4;
			byte* num = ((UnsafeAppendBuffer)buffer).Ptr + bufferSize;
			*(int*)num = 261;
			((int*)num)[1] = (int)ConvertColor(color);
			LineDataV3* ptr = (LineDataV3*)(num + 8);
			Unsafe.Write(&ptr->a, a);
			Unsafe.Write(&ptr->b, b);
			((UnsafeAppendBuffer)buffer).Length = length;
		}

		public void Ray(float3 origin, float3 direction)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			Line(origin, origin + direction);
		}

		public void Ray(Ray ray, float length)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			Line(((Ray)(ref ray)).origin, ((Ray)(ref ray)).origin + ((Ray)(ref ray)).direction * length);
		}

		public void Arc(float3 center, float3 start, float3 end)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			float3 val = start - center;
			float3 val2 = end - center;
			float3 val3 = math.cross(val2, val);
			if (math.any(val3 != 0f) && math.all(math.isfinite(val3)))
			{
				Matrix4x4 matrix = Matrix4x4.TRS(float3.op_Implicit(center), Quaternion.LookRotation(float3.op_Implicit(val), float3.op_Implicit(val3)), Vector3.one);
				float num = Vector3.SignedAngle(float3.op_Implicit(val), float3.op_Implicit(val2), float3.op_Implicit(val3)) * (MathF.PI / 180f);
				PushMatrix(matrix);
				CircleXZInternal(float3.zero, math.length(val), MathF.PI / 2f, MathF.PI / 2f - num);
				PopMatrix();
			}
		}

		[Obsolete("Use Draw.xz.Circle instead")]
		public void CircleXZ(float3 center, float radius, float startAngle = 0f, float endAngle = MathF.PI * 2f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			CircleXZInternal(center, radius, startAngle, endAngle);
		}

		internal void CircleXZInternal(float3 center, float radius, float startAngle = 0f, float endAngle = MathF.PI * 2f)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			Reserve<CircleXZData>();
			Add(Command.CircleXZ);
			Add(new CircleXZData
			{
				center = center,
				radius = radius,
				startAngle = startAngle,
				endAngle = endAngle
			});
		}

		internal void CircleXZInternal(float3 center, float radius, float startAngle, float endAngle, Color color)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			this.Reserve<Color32, CircleXZData>();
			Add(Command.CircleXZ | Command.PushColorInline);
			Add(ConvertColor(color));
			Add(new CircleXZData
			{
				center = center,
				radius = radius,
				startAngle = startAngle,
				endAngle = endAngle
			});
		}

		[Obsolete("Use Draw.xy.Circle instead")]
		public void CircleXY(float3 center, float radius, float startAngle = 0f, float endAngle = MathF.PI * 2f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			PushMatrix(XZtoXYPlaneMatrix);
			CircleXZ(new float3(center.x, 0f - center.z, center.y), radius, startAngle, endAngle);
			PopMatrix();
		}

		public void Circle(float3 center, float3 normal, float radius)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			Reserve<CircleData>();
			Add(Command.Circle);
			Add(new CircleData
			{
				center = center,
				normal = normal,
				radius = radius
			});
		}

		public void SolidArc(float3 center, float3 start, float3 end)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			float3 val = start - center;
			float3 val2 = end - center;
			float3 val3 = math.cross(val2, val);
			if (math.any(val3))
			{
				Matrix4x4 matrix = Matrix4x4.TRS(float3.op_Implicit(center), Quaternion.LookRotation(float3.op_Implicit(val), float3.op_Implicit(val3)), Vector3.one);
				float num = Vector3.SignedAngle(float3.op_Implicit(val), float3.op_Implicit(val2), float3.op_Implicit(val3)) * (MathF.PI / 180f);
				PushMatrix(matrix);
				SolidCircleXZInternal(float3.zero, math.length(val), MathF.PI / 2f, MathF.PI / 2f - num);
				PopMatrix();
			}
		}

		[Obsolete("Use Draw.xz.SolidCircle instead")]
		public void SolidCircleXZ(float3 center, float radius, float startAngle = 0f, float endAngle = MathF.PI * 2f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			SolidCircleXZInternal(center, radius, startAngle, endAngle);
		}

		internal void SolidCircleXZInternal(float3 center, float radius, float startAngle = 0f, float endAngle = MathF.PI * 2f)
		{
			//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)
			Reserve<CircleXZData>();
			Add(Command.DiscXZ);
			Add(new CircleXZData
			{
				center = center,
				radius = radius,
				startAngle = startAngle,
				endAngle = endAngle
			});
		}

		internal void SolidCircleXZInternal(float3 center, float radius, float startAngle, float endAngle, Color color)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			this.Reserve<Color32, CircleXZData>();
			Add(Command.DiscXZ | Command.PushColorInline);
			Add(ConvertColor(color));
			Add(new CircleXZData
			{
				center = center,
				radius = radius,
				startAngle = startAngle,
				endAngle = endAngle
			});
		}

		[Obsolete("Use Draw.xy.SolidCircle instead")]
		public void SolidCircleXY(float3 center, float radius, float startAngle = 0f, float endAngle = MathF.PI * 2f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			PushMatrix(XZtoXYPlaneMatrix);
			SolidCircleXZInternal(new float3(center.x, 0f - center.z, center.y), radius, startAngle, endAngle);
			PopMatrix();
		}

		public void SolidCircle(float3 center, float3 normal, float radius)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			Reserve<CircleData>();
			Add(Command.Disc);
			Add(new CircleData
			{
				center = center,
				normal = normal,
				radius = radius
			});
		}

		public void SphereOutline(float3 center, float radius)
		{
			//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)
			Reserve<SphereData>();
			Add(Command.SphereOutline);
			Add(new SphereData
			{
				center = center,
				radius = radius
			});
		}

		public void WireCylinder(float3 bottom, float3 top, float radius)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			WireCylinder(bottom, top - bottom, math.length(top - bottom), radius);
		}

		public void WireCylinder(float3 position, float3 up, float height, float radius)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			up = math.normalizesafe(up, default(float3));
			if (!math.all(up == 0f) && !math.any(math.isnan(up)) && !math.isnan(height) && !math.isnan(radius))
			{
				OrthonormalBasis(up, out var basis, out var basis2);
				this.PushMatrix(new float4x4(new float4(basis * radius, 0f), new float4(up * height, 0f), new float4(basis2 * radius, 0f), new float4(position, 1f)));
				CircleXZInternal(float3.zero, 1f);
				if (height > 0f)
				{
					CircleXZInternal(new float3(0f, 1f, 0f), 1f);
					this.Line(new float3(1f, 0f, 0f), new float3(1f, 1f, 0f));
					this.Line(new float3(-1f, 0f, 0f), new float3(-1f, 1f, 0f));
					this.Line(new float3(0f, 0f, 1f), new float3(0f, 1f, 1f));
					this.Line(new float3(0f, 0f, -1f), new float3(0f, 1f, -1f));
				}
				PopMatrix();
			}
		}

		private static void OrthonormalBasis(float3 normal, out float3 basis1, out float3 basis2)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0052: Unknown result type (might be due to invalid IL or missing references)
			basis1 = math.cross(normal, new float3(1f, 1f, 1f));
			if (math.all(basis1 == 0f))
			{
				basis1 = math.cross(normal, new float3(-1f, 1f, 1f));
			}
			basis1 = math.normalizesafe(basis1, default(float3));
			basis2 = math.cross(normal, basis1);
		}

		public void WireCapsule(float3 start, float3 end, float radius)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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)
			float3 val = end - start;
			float num = math.length(val);
			if ((double)num < 0.0001)
			{
				WireSphere(start, radius);
				return;
			}
			float3 val2 = val / num;
			WireCapsule(start - val2 * radius, val2, num + 2f * radius, radius);
		}

		public void WireCapsule(float3 position, float3 direction, float length, float radius)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			direction = math.normalizesafe(direction, default(float3));
			if (math.all(direction == 0f) || math.any(math.isnan(direction)) || math.isnan(length) || math.isnan(radius))
			{
				return;
			}
			if (radius <= 0f)
			{
				Line(position, position + direction * length);
				return;
			}
			length = math.max(length, radius * 2f);
			OrthonormalBasis(direction, out var basis, out var basis2);
			this.PushMatrix(new float4x4(new float4(basis, 0f), new float4(direction, 0f), new float4(basis2, 0f), new float4(position, 1f)));
			CircleXZInternal(new float3(0f, radius, 0f), radius);
			PushMatrix(XZtoXYPlaneMatrix);
			CircleXZInternal(new float3(0f, 0f, radius), radius, MathF.PI);
			PopMatrix();
			PushMatrix(XZtoYZPlaneMatrix);
			CircleXZInternal(new float3(radius, 0f, 0f), radius, MathF.PI / 2f, 4.712389f);
			PopMatrix();
			if (length > 0f)
			{
				float num = length - radius;
				CircleXZInternal(new float3(0f, num, 0f), radius);
				PushMatrix(XZtoXYPlaneMatrix);
				CircleXZInternal(new float3(0f, 0f, num), radius, 0f, MathF.PI);
				PopMatrix();
				PushMatrix(XZtoYZPlaneMatrix);
				CircleXZInternal(new float3(num, 0f, 0f), radius, -MathF.PI / 2f, MathF.PI / 2f);
				PopMatrix();
				this.Line(new float3(radius, radius, 0f), new float3(radius, num, 0f));
				this.Line(new float3(0f - radius, radius, 0f), new float3(0f - radius, num, 0f));
				this.Line(new float3(0f, radius, radius), new float3(0f, num, radius));
				this.Line(new float3(0f, radius, 0f - radius), new float3(0f, num, 0f - radius));
			}
			PopMatrix();
		}

		public void WireSphere(float3 position, float radius)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			SphereOutline(position, radius);
			Circle(position, new float3(1f, 0f, 0f), radius);
			Circle(position, new float3(0f, 1f, 0f), radius);
			Circle(position, new float3(0f, 0f, 1f), radius);
		}

		[BurstDiscard]
		public void Polyline(List<Vector3> points, bool cycle = false)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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)
			for (int i = 0; i < points.Count - 1; i++)
			{
				Line(points[i], points[i + 1]);
			}
			if (cycle && points.Count > 1)
			{
				Line(points[points.Count - 1], points[0]);
			}
		}

		public void Polyline<T>(T points, bool cycle = false) where T : IReadOnlyList<float3>
		{
			//IL_0008: 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_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < points.Count - 1; i++)
			{
				Line(points[i], points[i + 1]);
			}
			if (cycle && points.Count > 1)
			{
				int index = points.Count - 1;
				Line(points[index], points[0]);
			}
		}

		[BurstDiscard]
		public void Polyline(Vector3[] points, bool cycle = false)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < points.Length - 1; i++)
			{
				Line(points[i], points[i + 1]);
			}
			if (cycle && points.Length > 1)
			{
				Line(points[^1], points[0]);
			}
		}

		[BurstDiscard]
		public void Polyline(float3[] points, bool cycle = false)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < points.Length - 1; i++)
			{
				Line(points[i], points[i + 1]);
			}
			if (cycle && points.Length > 1)
			{
				Line(points[^1], points[0]);
			}
		}

		public void Polyline(NativeArray<float3> points, bool cycle = false)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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)
			for (int i = 0; i < points.Length - 1; i++)
			{
				Line(points[i], points[i + 1]);
			}
			if (cycle && points.Length > 1)
			{
				Line(points[points.Length - 1], points[0]);
			}
		}

		public void DashedLine(float3 a, float3 b, float dash, float gap)
		{
			//IL_0017: 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)
			PolylineWithSymbol polylineWithSymbol = new PolylineWithSymbol(SymbolDecoration.None, gap, 0f, dash + gap);
			polylineWithSymbol.MoveTo(ref this, a);
			polylineWithSymbol.MoveTo(ref this, b);
		}

		public void DashedPolyline(List<Vector3> points, float dash, float gap)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			PolylineWithSymbol polylineWithSymbol = new PolylineWithSymbol(SymbolDecoration.None, gap, 0f, dash + gap);
			for (int i = 0; i < points.Count; i++)
			{
				polylineWithSymbol.MoveTo(ref this, float3.op_Implicit(points[i]));
			}
		}

		public void WireBox(float3 center, float3 size)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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)
			Reserve<BoxData>();
			Add(Command.WireBox);
			Add(new BoxData
			{
				center = center,
				size = size
			});
		}

		public void WireBox(float3 center, quaternion rotation, float3 size)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			PushMatrix(float4x4.TRS(center, rotation, size));
			WireBox(float3.zero, new float3(1f, 1f, 1f));
			PopMatrix();
		}

		public void WireBox(Bounds bounds)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			WireBox(float3.op_Implicit(((Bounds)(ref bounds)).center), float3.op_Implicit(((Bounds)(ref bounds)).size));
		}

		public void WireMesh(Mesh mesh)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)mesh == (Object)null)
			{
				throw new ArgumentNullException();
			}
			MeshDataArray val = Mesh.AcquireReadOnlyMeshData(mesh);
			MeshData rawMeshData = ((MeshDataArray)(ref val))[0];
			JobWireMesh.JobWireMeshFunctionPointer(ref rawMeshData, ref this);
			((MeshDataArray)(ref val)).Dispose();
		}

		public unsafe void WireMesh(NativeArray<float3> vertices, NativeArray<int> triangles)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			JobWireMesh.WireMesh((float3*)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr<float3>(vertices), (int*)NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr<int>(triangles), vertices.Length, triangles.Length, ref this);
		}

		public void SolidMesh(Mesh mesh)
		{
			SolidMeshInternal(mesh, temporary: false);
		}

		private void SolidMeshInternal(Mesh mesh, bool temporary, Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			PushColor(color);
			SolidMeshInternal(mesh, temporary);
			PopColor();
		}

		private void SolidMeshInternal(Mesh mesh, bool temporary)
		{
			(gizmos.Target as DrawingData).data.Get(uniqueID).meshes.Add(new DrawingData.SubmittedMesh
			{
				mesh = mesh,
				temporary = temporary
			});
			Reserve(4);
			Add(Command.CaptureState);
		}

		[BurstDiscard]
		public void SolidMesh(List<Vector3> vertices, List<int> triangles, List<Color> colors)
		{
			if (vertices.Count != colors.Count)
			{
				throw new ArgumentException("Number of colors must be the same as the number of vertices");
			}
			Mesh mesh = (gizmos.Target as DrawingData).GetMesh(vertices.Count);
			mesh.Clear();
			mesh.SetVertices(vertices);
			mesh.SetTriangles(triangles, 0);
			mesh.SetColors(colors);
			mesh.UploadMeshData(false);
			SolidMeshInternal(mesh, temporary: true);
		}

		[BurstDiscard]
		public void SolidMesh(Vector3[] vertices, int[] triangles, Color[] colors, int vertexCount, int indexCount)
		{
			if (vertices.Length != colors.Length)
			{
				throw new ArgumentException("Number of colors must be the same as the number of vertices");
			}
			Mesh mesh = (gizmos.Target as DrawingData).GetMesh(vertices.Length);
			mesh.Clear();
			mesh.SetVertices(vertices, 0, vertexCount);
			mesh.SetTriangles(triangles, 0, indexCount, 0, true, 0);
			mesh.SetColors(colors, 0, vertexCount);
			mesh.UploadMeshData(false);
			SolidMeshInternal(mesh, temporary: true);
		}

		public void Cross(float3 position, float size = 1f)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			size *= 0.5f;
			Line(position - new float3(size, 0f, 0f), position + new float3(size, 0f, 0f));
			Line(position - new float3(0f, size, 0f), position + new float3(0f, size, 0f));
			Line(position - new float3(0f, 0f, size), position + new float3(0f, 0f, size));
		}

		[Obsolete("Use Draw.xz.Cross instead")]
		public void CrossXZ(float3 position, float size = 1f)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			size *= 0.5f;
			Line(position - new float3(size, 0f, 0f), position + new float3(size, 0f, 0f));
			Line(position - new float3(0f, 0f, size), position + new float3(0f, 0f, size));
		}

		[Obsolete("Use Draw.xy.Cross instead")]
		public void CrossXY(float3 position, float size = 1f)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			size *= 0.5f;
			Line(position - new float3(size, 0f, 0f), position + new float3(size, 0f, 0f));
			Line(position - new float3(0f, size, 0f), position + new float3(0f, size, 0f));
		}

		public static float3 EvaluateCubicBezier(float3 p0, float3 p1, float3 p2, float3 p3, float t)
		{
			//IL_0021: 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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			t = math.clamp(t, 0f, 1f);
			float num = 1f - t;
			return num * num * num * p0 + 3f * num * num * t * p1 + 3f * num * t * t * p2 + t * t * t * p3;
		}

		public void Bezier(float3 p0, float3 p1, float3 p2, float3 p3)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			float3 a = p0;
			for (int i = 1; i <= 20; i++)
			{
				float t = (float)i / 20f;
				float3 val = EvaluateCubicBezier(p0, p1, p2, p3, t);
				Line(a, val);
				a = val;
			}
		}

		public void CatmullRom(List<Vector3> points)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: 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_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			if (points.Count < 2)
			{
				return;
			}
			if (points.Count == 2)
			{
				Line(points[0], points[1]);
				return;
			}
			int count = points.Count;
			CatmullRom(float3.op_Implicit(points[0]), float3.op_Implicit(points[0]), float3.op_Implicit(points[1]), float3.op_Implicit(points[2]));
			for (int i = 0; i + 3 < count; i++)
			{
				CatmullRom(float3.op_Implicit(points[i]), float3.op_Implicit(points[i + 1]), float3.op_Implicit(points[i + 2]), float3.op_Implicit(points[i + 3]));
			}
			CatmullRom(float3.op_Implicit(points[count - 3]), float3.op_Implicit(points[count - 2]), float3.op_Implicit(points[count - 1]), float3.op_Implicit(points[count - 1]));
		}

		public void CatmullRom(float3 p0, float3 p1, float3 p2, float3 p3)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 

BepInEx/plugins/WKRando/Archipelago.MultiClient.Net.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Archipelago.MultiClient.Net.Colors;
using Archipelago.MultiClient.Net.ConcurrentCollection;
using Archipelago.MultiClient.Net.Converters;
using Archipelago.MultiClient.Net.DataPackage;
using Archipelago.MultiClient.Net.Enums;
using Archipelago.MultiClient.Net.Exceptions;
using Archipelago.MultiClient.Net.Extensions;
using Archipelago.MultiClient.Net.Helpers;
using Archipelago.MultiClient.Net.MessageLog.Messages;
using Archipelago.MultiClient.Net.MessageLog.Parts;
using Archipelago.MultiClient.Net.Models;
using Archipelago.MultiClient.Net.Packets;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: ComVisible(false)]
[assembly: Guid("35a803ad-85ed-42e9-b1e3-c6b72096f0c1")]
[assembly: InternalsVisibleTo("Archipelago.MultiClient.Net.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Jarno Westhof, Hussein Farran, Zach Parks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © 2026")]
[assembly: AssemblyDescription("A client library for use with .NET based prog-langs for interfacing with Archipelago hosts.")]
[assembly: AssemblyFileVersion("6.7.1.0")]
[assembly: AssemblyInformationalVersion("6.7.1+0c57591db30f2497b0b4fef87164aa2bbe2e51b2")]
[assembly: AssemblyProduct("Archipelago.MultiClient.Net")]
[assembly: AssemblyTitle("Archipelago.MultiClient.Net")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ArchipelagoMW/Archipelago.MultiClient.Net")]
[assembly: AssemblyVersion("6.7.1.0")]
internal interface IConcurrentHashSet<T>
{
	bool TryAdd(T item);

	bool Contains(T item);

	void UnionWith(T[] otherSet);

	T[] ToArray();

	ReadOnlyCollection<T> AsToReadOnlyCollection();

	ReadOnlyCollection<T> AsToReadOnlyCollectionExcept(IConcurrentHashSet<T> otherSet);
}
public class AttemptingStringEnumConverter : StringEnumConverter
{
	public AttemptingStringEnumConverter()
	{
	}

	public AttemptingStringEnumConverter(Type namingStrategyType)
		: base(namingStrategyType)
	{
	}

	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
	{
		try
		{
			return ((StringEnumConverter)this).ReadJson(reader, objectType, existingValue, serializer);
		}
		catch (JsonSerializationException)
		{
			return objectType.IsValueType ? Activator.CreateInstance(objectType) : null;
		}
	}
}
namespace Archipelago.MultiClient.Net
{
	[Serializable]
	public abstract class ArchipelagoPacketBase
	{
		[JsonIgnore]
		internal JObject jobject;

		[JsonProperty("cmd")]
		[JsonConverter(typeof(StringEnumConverter))]
		public abstract ArchipelagoPacketType PacketType { get; }

		public JObject ToJObject()
		{
			return jobject;
		}
	}
	public interface IArchipelagoSession : IArchipelagoSessionActions
	{
		IArchipelagoSocketHelper Socket { get; }

		IReceivedItemsHelper Items { get; }

		ILocationCheckHelper Locations { get; }

		IPlayerHelper Players { get; }

		IDataStorageHelper DataStorage { get; }

		IConnectionInfoProvider ConnectionInfo { get; }

		IRoomStateHelper RoomState { get; }

		IMessageLogHelper MessageLog { get; }

		IHintsHelper Hints { get; }

		Task<RoomInfoPacket> ConnectAsync();

		Task<LoginResult> LoginAsync(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true);

		LoginResult TryConnectAndLogin(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true);
	}
	public class ArchipelagoSession : IArchipelagoSession, IArchipelagoSessionActions
	{
		private const int ArchipelagoConnectionTimeoutInSeconds = 4;

		private ConnectionInfoHelper connectionInfo;

		private TaskCompletionSource<LoginResult> loginResultTask = new TaskCompletionSource<LoginResult>();

		private TaskCompletionSource<RoomInfoPacket> roomInfoPacketTask = new TaskCompletionSource<RoomInfoPacket>();

		public IArchipelagoSocketHelper Socket { get; }

		public IReceivedItemsHelper Items { get; }

		public ILocationCheckHelper Locations { get; }

		public IPlayerHelper Players { get; }

		public IDataStorageHelper DataStorage { get; }

		public IConnectionInfoProvider ConnectionInfo => connectionInfo;

		public IRoomStateHelper RoomState { get; }

		public IMessageLogHelper MessageLog { get; }

		public IHintsHelper Hints { get; }

		internal ArchipelagoSession(IArchipelagoSocketHelper socket, IReceivedItemsHelper items, ILocationCheckHelper locations, IPlayerHelper players, IRoomStateHelper roomState, ConnectionInfoHelper connectionInfoHelper, IDataStorageHelper dataStorage, IMessageLogHelper messageLog, IHintsHelper createHints)
		{
			Socket = socket;
			Items = items;
			Locations = locations;
			Players = players;
			RoomState = roomState;
			connectionInfo = connectionInfoHelper;
			DataStorage = dataStorage;
			MessageLog = messageLog;
			Hints = createHints;
			socket.PacketReceived += Socket_PacketReceived;
		}

		private void Socket_PacketReceived(ArchipelagoPacketBase packet)
		{
			if (!(packet is ConnectedPacket) && !(packet is ConnectionRefusedPacket))
			{
				if (packet is RoomInfoPacket result)
				{
					roomInfoPacketTask.TrySetResult(result);
				}
			}
			else
			{
				loginResultTask.TrySetResult(LoginResult.FromPacket(packet));
			}
		}

		public Task<RoomInfoPacket> ConnectAsync()
		{
			roomInfoPacketTask = new TaskCompletionSource<RoomInfoPacket>();
			Task.Factory.StartNew(delegate
			{
				try
				{
					Task task = Socket.ConnectAsync();
					task.Wait(TimeSpan.FromSeconds(4.0));
					if (!task.IsCompleted)
					{
						roomInfoPacketTask.TrySetCanceled();
					}
				}
				catch (AggregateException)
				{
					roomInfoPacketTask.TrySetCanceled();
				}
			});
			return roomInfoPacketTask.Task;
		}

		public Task<LoginResult> LoginAsync(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true)
		{
			loginResultTask = new TaskCompletionSource<LoginResult>();
			if (!roomInfoPacketTask.Task.IsCompleted)
			{
				loginResultTask.TrySetResult(new LoginFailure("You are not connected, run ConnectAsync() first"));
				return loginResultTask.Task;
			}
			connectionInfo.SetConnectionParameters(game, tags, itemsHandlingFlags, uuid);
			try
			{
				Socket.SendPacket(BuildConnectPacket(name, password, version, requestSlotData));
			}
			catch (ArchipelagoSocketClosedException)
			{
				loginResultTask.TrySetResult(new LoginFailure("You are not connected, run ConnectAsync() first"));
				return loginResultTask.Task;
			}
			SetResultAfterTimeout(loginResultTask, 4, new LoginFailure("Connection timed out."));
			return loginResultTask.Task;
		}

		private static void SetResultAfterTimeout<T>(TaskCompletionSource<T> task, int timeoutInSeconds, T result)
		{
			new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)).Token.Register(delegate
			{
				task.TrySetResult(result);
			});
		}

		public LoginResult TryConnectAndLogin(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true)
		{
			Task<RoomInfoPacket> task = ConnectAsync();
			try
			{
				task.Wait(TimeSpan.FromSeconds(4.0));
			}
			catch (AggregateException ex)
			{
				if (ex.GetBaseException() is OperationCanceledException)
				{
					return new LoginFailure("Connection timed out.");
				}
				return new LoginFailure(ex.GetBaseException().Message);
			}
			if (!task.IsCompleted)
			{
				return new LoginFailure("Connection timed out.");
			}
			return LoginAsync(game, name, itemsHandlingFlags, version, tags, uuid, password, requestSlotData).Result;
		}

		private ConnectPacket BuildConnectPacket(string name, string password, Version version, bool requestSlotData)
		{
			return new ConnectPacket
			{
				Game = ConnectionInfo.Game,
				Name = name,
				Password = password,
				Tags = ConnectionInfo.Tags,
				Uuid = ConnectionInfo.Uuid,
				Version = ((version != null) ? new NetworkVersion(version) : new NetworkVersion(0, 6, 0)),
				ItemsHandling = ConnectionInfo.ItemsHandlingFlags,
				RequestSlotData = requestSlotData
			};
		}

		public void Say(string message)
		{
			Socket.SendPacket(new SayPacket
			{
				Text = message
			});
		}

		public void SetClientState(ArchipelagoClientState state)
		{
			Socket.SendPacket(new StatusUpdatePacket
			{
				Status = state
			});
		}

		public void SetGoalAchieved()
		{
			SetClientState(ArchipelagoClientState.ClientGoal);
		}
	}
	public interface IArchipelagoSessionActions
	{
		void Say(string message);

		void SetClientState(ArchipelagoClientState state);

		void SetGoalAchieved();
	}
	public static class ArchipelagoSessionFactory
	{
		public static ArchipelagoSession CreateSession(Uri uri)
		{
			ArchipelagoSocketHelper socket = new ArchipelagoSocketHelper(uri);
			DataPackageCache cache = new DataPackageCache(socket);
			ConnectionInfoHelper connectionInfoHelper = new ConnectionInfoHelper(socket);
			PlayerHelper playerHelper = new PlayerHelper(socket, connectionInfoHelper);
			ItemInfoResolver itemInfoResolver = new ItemInfoResolver(cache, connectionInfoHelper);
			LocationCheckHelper locationCheckHelper = new LocationCheckHelper(socket, itemInfoResolver, connectionInfoHelper, playerHelper);
			ReceivedItemsHelper items = new ReceivedItemsHelper(socket, locationCheckHelper, itemInfoResolver, connectionInfoHelper, playerHelper);
			RoomStateHelper roomStateHelper = new RoomStateHelper(socket, locationCheckHelper);
			DataStorageHelper dataStorageHelper = new DataStorageHelper(socket, connectionInfoHelper);
			MessageLogHelper messageLog = new MessageLogHelper(socket, itemInfoResolver, playerHelper, connectionInfoHelper);
			HintsHelper createHints = new HintsHelper(socket, playerHelper, locationCheckHelper, roomStateHelper, dataStorageHelper);
			return new ArchipelagoSession(socket, items, locationCheckHelper, playerHelper, roomStateHelper, connectionInfoHelper, dataStorageHelper, messageLog, createHints);
		}

		public static ArchipelagoSession CreateSession(string hostname, int port = 38281)
		{
			return CreateSession(ParseUri(hostname, port));
		}

		internal static Uri ParseUri(string hostname, int port)
		{
			string text = hostname;
			if (!text.StartsWith("ws://") && !text.StartsWith("wss://"))
			{
				text = "unspecified://" + text;
			}
			if (!text.Substring(text.IndexOf("://", StringComparison.Ordinal) + 3).Contains(":"))
			{
				text += $":{port}";
			}
			if (text.EndsWith(":"))
			{
				text += port;
			}
			return new Uri(text);
		}
	}
	public abstract class LoginResult
	{
		public abstract bool Successful { get; }

		public static LoginResult FromPacket(ArchipelagoPacketBase packet)
		{
			if (!(packet is ConnectedPacket connectedPacket))
			{
				if (packet is ConnectionRefusedPacket connectionRefusedPacket)
				{
					return new LoginFailure(connectionRefusedPacket);
				}
				throw new ArgumentOutOfRangeException("packet", "packet is not a connection result packet");
			}
			return new LoginSuccessful(connectedPacket);
		}
	}
	public class LoginSuccessful : LoginResult
	{
		public override bool Successful => true;

		public int Team { get; }

		public int Slot { get; }

		public Dictionary<string, object> SlotData { get; }

		public LoginSuccessful(ConnectedPacket connectedPacket)
		{
			Team = connectedPacket.Team;
			Slot = connectedPacket.Slot;
			SlotData = connectedPacket.SlotData;
		}
	}
	public class LoginFailure : LoginResult
	{
		public override bool Successful => false;

		public ConnectionRefusedError[] ErrorCodes { get; }

		public string[] Errors { get; }

		public LoginFailure(ConnectionRefusedPacket connectionRefusedPacket)
		{
			if (connectionRefusedPacket.Errors != null)
			{
				ErrorCodes = connectionRefusedPacket.Errors.ToArray();
				Errors = ErrorCodes.Select(GetErrorMessage).ToArray();
			}
			else
			{
				ErrorCodes = new ConnectionRefusedError[0];
				Errors = new string[0];
			}
		}

		public LoginFailure(string message)
		{
			ErrorCodes = new ConnectionRefusedError[0];
			Errors = new string[1] { message };
		}

		private static string GetErrorMessage(ConnectionRefusedError errorCode)
		{
			return errorCode switch
			{
				ConnectionRefusedError.InvalidSlot => "The slot name did not match any slot on the server.", 
				ConnectionRefusedError.InvalidGame => "The slot is set to a different game on the server.", 
				ConnectionRefusedError.SlotAlreadyTaken => "The slot already has a connection with a different uuid established.", 
				ConnectionRefusedError.IncompatibleVersion => "The client and server version mismatch.", 
				ConnectionRefusedError.InvalidPassword => "The password is invalid.", 
				ConnectionRefusedError.InvalidItemsHandling => "The item handling flags provided are invalid.", 
				_ => $"Unknown error: {errorCode}.", 
			};
		}
	}
	internal class TwoWayLookup<TA, TB> : IEnumerable<KeyValuePair<TB, TA>>, IEnumerable
	{
		private readonly Dictionary<TA, TB> aToB = new Dictionary<TA, TB>();

		private readonly Dictionary<TB, TA> bToA = new Dictionary<TB, TA>();

		public TA this[TB b] => bToA[b];

		public TB this[TA a] => aToB[a];

		public void Add(TA a, TB b)
		{
			aToB[a] = b;
			bToA[b] = a;
		}

		public void Add(TB b, TA a)
		{
			Add(a, b);
		}

		public bool TryGetValue(TA a, out TB b)
		{
			return aToB.TryGetValue(a, out b);
		}

		public bool TryGetValue(TB b, out TA a)
		{
			return bToA.TryGetValue(b, out a);
		}

		public IEnumerator<KeyValuePair<TB, TA>> GetEnumerator()
		{
			return bToA.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
}
namespace Archipelago.MultiClient.Net.Packets
{
	public class BouncedPacket : BouncePacket
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Bounced;
	}
	public class BouncePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Bounce;

		[JsonProperty("games")]
		public List<string> Games { get; set; } = new List<string>();


		[JsonProperty("slots")]
		public List<int> Slots { get; set; } = new List<int>();


		[JsonProperty("tags")]
		public List<string> Tags { get; set; } = new List<string>();


		[JsonProperty("data")]
		public Dictionary<string, JToken> Data { get; set; }
	}
	public class ConnectedPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Connected;

		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("players")]
		public NetworkPlayer[] Players { get; set; }

		[JsonProperty("missing_locations")]
		public long[] MissingChecks { get; set; }

		[JsonProperty("checked_locations")]
		public long[] LocationsChecked { get; set; }

		[JsonProperty("slot_data")]
		public Dictionary<string, object> SlotData { get; set; }

		[JsonProperty("slot_info")]
		public Dictionary<int, NetworkSlot> SlotInfo { get; set; }

		[JsonProperty("hint_points")]
		public int? HintPoints { get; set; }
	}
	public class ConnectionRefusedPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.ConnectionRefused;

		[JsonProperty("errors", ItemConverterType = typeof(AttemptingStringEnumConverter))]
		public ConnectionRefusedError[] Errors { get; set; }
	}
	public class ConnectPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Connect;

		[JsonProperty("password")]
		public string Password { get; set; }

		[JsonProperty("game")]
		public string Game { get; set; }

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

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

		[JsonProperty("version")]
		public NetworkVersion Version { get; set; }

		[JsonProperty("tags")]
		public string[] Tags { get; set; }

		[JsonProperty("items_handling")]
		public ItemsHandlingFlags ItemsHandling { get; set; }

		[JsonProperty("slot_data")]
		public bool RequestSlotData { get; set; }
	}
	public class ConnectUpdatePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.ConnectUpdate;

		[JsonProperty("tags")]
		public string[] Tags { get; set; }

		[JsonProperty("items_handling")]
		public ItemsHandlingFlags? ItemsHandling { get; set; }
	}
	public class CreateHintsPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.CreateHints;

		[JsonProperty("locations")]
		public long[] Locations { get; set; }

		[JsonProperty("player")]
		public int Player { get; set; }

		[JsonProperty("status")]
		public HintStatus Status { get; set; }
	}
	public class DataPackagePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.DataPackage;

		[JsonProperty("data")]
		public Archipelago.MultiClient.Net.Models.DataPackage DataPackage { get; set; }
	}
	public class GetDataPackagePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.GetDataPackage;

		[JsonProperty("games")]
		public string[] Games { get; set; }
	}
	public class GetPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Get;

		[JsonProperty("keys")]
		public string[] Keys { get; set; }
	}
	public class InvalidPacketPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.InvalidPacket;

		[JsonProperty("type")]
		public InvalidPacketErrorType ErrorType { get; set; }

		[JsonProperty("text")]
		public string ErrorText { get; set; }

		[JsonProperty("original_cmd")]
		public ArchipelagoPacketType OriginalCmd { get; set; }
	}
	public class LocationChecksPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.LocationChecks;

		[JsonProperty("locations")]
		public long[] Locations { get; set; }
	}
	public class LocationInfoPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.LocationInfo;

		[JsonProperty("locations")]
		public NetworkItem[] Locations { get; set; }
	}
	public class LocationScoutsPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.LocationScouts;

		[JsonProperty("locations")]
		public long[] Locations { get; set; }

		[JsonProperty("create_as_hint")]
		public int CreateAsHint { get; set; }
	}
	public class PrintJsonPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.PrintJSON;

		[JsonProperty("data")]
		public JsonMessagePart[] Data { get; set; }

		[JsonProperty("type")]
		[JsonConverter(typeof(AttemptingStringEnumConverter))]
		public JsonMessageType? MessageType { get; set; }
	}
	public class ItemPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("receiving")]
		public int ReceivingPlayer { get; set; }

		[JsonProperty("item")]
		public NetworkItem Item { get; set; }
	}
	public class ItemCheatPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("receiving")]
		public int ReceivingPlayer { get; set; }

		[JsonProperty("item")]
		public NetworkItem Item { get; set; }

		[JsonProperty("team")]
		public int Team { get; set; }
	}
	public class HintPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("receiving")]
		public int ReceivingPlayer { get; set; }

		[JsonProperty("item")]
		public NetworkItem Item { get; set; }

		[JsonProperty("found")]
		public bool? Found { get; set; }
	}
	public class JoinPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("tags")]
		public string[] Tags { get; set; }
	}
	public class LeavePrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }
	}
	public class ChatPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("message")]
		public string Message { get; set; }
	}
	public class ServerChatPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("message")]
		public string Message { get; set; }
	}
	public class TutorialPrintJsonPacket : PrintJsonPacket
	{
	}
	public class TagsChangedPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("tags")]
		public string[] Tags { get; set; }
	}
	public class CommandResultPrintJsonPacket : PrintJsonPacket
	{
	}
	public class AdminCommandResultPrintJsonPacket : PrintJsonPacket
	{
	}
	public class GoalPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }
	}
	public class ReleasePrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }
	}
	public class CollectPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }
	}
	public class CountdownPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("countdown")]
		public int RemainingSeconds { get; set; }
	}
	public class ReceivedItemsPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.ReceivedItems;

		[JsonProperty("index")]
		public int Index { get; set; }

		[JsonProperty("items")]
		public NetworkItem[] Items { get; set; }
	}
	public class RetrievedPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Retrieved;

		[JsonProperty("keys")]
		public Dictionary<string, JToken> Data { get; set; }
	}
	public class RoomInfoPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.RoomInfo;

		[JsonProperty("version")]
		public NetworkVersion Version { get; set; }

		[JsonProperty("generator_version")]
		public NetworkVersion GeneratorVersion { get; set; }

		[JsonProperty("tags")]
		public string[] Tags { get; set; }

		[JsonProperty("password")]
		public bool Password { get; set; }

		[JsonProperty("permissions")]
		public Dictionary<string, Permissions> Permissions { get; set; }

		[JsonProperty("hint_cost")]
		public int HintCostPercentage { get; set; }

		[JsonProperty("location_check_points")]
		public int LocationCheckPoints { get; set; }

		[JsonProperty("players")]
		public NetworkPlayer[] Players { get; set; }

		[JsonProperty("games")]
		public string[] Games { get; set; }

		[JsonProperty("datapackage_checksums")]
		public Dictionary<string, string> DataPackageChecksums { get; set; }

		[JsonProperty("seed_name")]
		public string SeedName { get; set; }

		[JsonProperty("time")]
		public double Timestamp { get; set; }
	}
	public class RoomUpdatePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.RoomUpdate;

		[JsonProperty("tags")]
		public string[] Tags { get; set; }

		[JsonProperty("password")]
		public bool? Password { get; set; }

		[JsonProperty("permissions")]
		public Dictionary<string, Permissions> Permissions { get; set; } = new Dictionary<string, Permissions>();


		[JsonProperty("hint_cost")]
		public int? HintCostPercentage { get; set; }

		[JsonProperty("location_check_points")]
		public int? LocationCheckPoints { get; set; }

		[JsonProperty("players")]
		public NetworkPlayer[] Players { get; set; }

		[JsonProperty("hint_points")]
		public int? HintPoints { get; set; }

		[JsonProperty("checked_locations")]
		public long[] CheckedLocations { get; set; }
	}
	public class SayPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Say;

		[JsonProperty("text")]
		public string Text { get; set; }
	}
	public class SetNotifyPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.SetNotify;

		[JsonProperty("keys")]
		public string[] Keys { get; set; }
	}
	public class SetPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Set;

		[JsonProperty("key")]
		public string Key { get; set; }

		[JsonProperty("default")]
		public JToken DefaultValue { get; set; }

		[JsonProperty("operations")]
		public OperationSpecification[] Operations { get; set; }

		[JsonProperty("want_reply")]
		public bool WantReply { get; set; }

		[JsonExtensionData]
		public Dictionary<string, JToken> AdditionalArguments { get; set; }

		[OnDeserialized]
		internal void OnDeserializedMethod(StreamingContext context)
		{
			AdditionalArguments?.Remove("cmd");
		}
	}
	public class SetReplyPacket : SetPacket
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.SetReply;

		[JsonProperty("value")]
		public JToken Value { get; set; }

		[JsonProperty("original_value")]
		public JToken OriginalValue { get; set; }
	}
	public class StatusUpdatePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.StatusUpdate;

		[JsonProperty("status")]
		public ArchipelagoClientState Status { get; set; }
	}
	public class SyncPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Sync;
	}
	internal class UnknownPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Unknown;
	}
	public class UpdateHintPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.UpdateHint;

		[JsonProperty("player")]
		public int Player { get; set; }

		[JsonProperty("location")]
		public long Location { get; set; }

		[JsonProperty("status")]
		public HintStatus Status { get; set; }
	}
}
namespace Archipelago.MultiClient.Net.Models
{
	public struct Color : IEquatable<Color>
	{
		public static Color Red = new Color(byte.MaxValue, 0, 0);

		public static Color Green = new Color(0, 128, 0);

		public static Color Yellow = new Color(byte.MaxValue, byte.MaxValue, 0);

		public static Color Blue = new Color(0, 0, byte.MaxValue);

		public static Color Magenta = new Color(byte.MaxValue, 0, byte.MaxValue);

		public static Color Cyan = new Color(0, byte.MaxValue, byte.MaxValue);

		public static Color Black = new Color(0, 0, 0);

		public static Color White = new Color(byte.MaxValue, byte.MaxValue, byte.MaxValue);

		public static Color SlateBlue = new Color(106, 90, 205);

		public static Color Salmon = new Color(250, 128, 114);

		public static Color Plum = new Color(221, 160, 221);

		public byte R { get; set; }

		public byte G { get; set; }

		public byte B { get; set; }

		public Color(byte r, byte g, byte b)
		{
			R = r;
			G = g;
			B = b;
		}

		public override bool Equals(object obj)
		{
			if (obj is Color color && R == color.R && G == color.G)
			{
				return B == color.B;
			}
			return false;
		}

		public bool Equals(Color other)
		{
			if (R == other.R && G == other.G)
			{
				return B == other.B;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return ((-1520100960 * -1521134295 + R.GetHashCode()) * -1521134295 + G.GetHashCode()) * -1521134295 + B.GetHashCode();
		}

		public static bool operator ==(Color left, Color right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(Color left, Color right)
		{
			return !(left == right);
		}
	}
	public class DataPackage
	{
		[JsonProperty("games")]
		public Dictionary<string, GameData> Games { get; set; } = new Dictionary<string, GameData>();

	}
	public class DataStorageElement
	{
		internal DataStorageElementContext Context;

		internal List<OperationSpecification> Operations = new List<OperationSpecification>(0);

		internal DataStorageHelper.DataStorageUpdatedHandler Callbacks;

		internal Dictionary<string, JToken> AdditionalArguments = new Dictionary<string, JToken>(0);

		private JToken cachedValue;

		public event DataStorageHelper.DataStorageUpdatedHandler OnValueChanged
		{
			add
			{
				Context.AddHandler(Context.Key, value);
			}
			remove
			{
				Context.RemoveHandler(Context.Key, value);
			}
		}

		internal DataStorageElement(DataStorageElementContext context)
		{
			Context = context;
		}

		internal DataStorageElement(OperationType operationType, JToken value)
		{
			Operations = new List<OperationSpecification>(1)
			{
				new OperationSpecification
				{
					OperationType = operationType,
					Value = value
				}
			};
		}

		internal DataStorageElement(DataStorageElement source, OperationType operationType, JToken value)
			: this(source.Context)
		{
			Operations = source.Operations.ToList();
			Callbacks = source.Callbacks;
			AdditionalArguments = source.AdditionalArguments;
			Operations.Add(new OperationSpecification
			{
				OperationType = operationType,
				Value = value
			});
		}

		internal DataStorageElement(DataStorageElement source, Callback callback)
			: this(source.Context)
		{
			Operations = source.Operations.ToList();
			Callbacks = source.Callbacks;
			AdditionalArguments = source.AdditionalArguments;
			Callbacks = (DataStorageHelper.DataStorageUpdatedHandler)Delegate.Combine(Callbacks, callback.Method);
		}

		internal DataStorageElement(DataStorageElement source, AdditionalArgument additionalArgument)
			: this(source.Context)
		{
			Operations = source.Operations.ToList();
			Callbacks = source.Callbacks;
			AdditionalArguments = source.AdditionalArguments;
			AdditionalArguments[additionalArgument.Key] = additionalArgument.Value;
		}

		public static DataStorageElement operator ++(DataStorageElement a)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(1));
		}

		public static DataStorageElement operator --(DataStorageElement a)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(-1));
		}

		public static DataStorageElement operator +(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, string b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, JToken b)
		{
			return new DataStorageElement(a, OperationType.Add, b);
		}

		public static DataStorageElement operator +(DataStorageElement a, IEnumerable b)
		{
			return new DataStorageElement(a, OperationType.Add, (JToken)(object)JArray.FromObject((object)b));
		}

		public static DataStorageElement operator +(DataStorageElement a, OperationSpecification s)
		{
			return new DataStorageElement(a, s.OperationType, s.Value);
		}

		public static DataStorageElement operator +(DataStorageElement a, Callback c)
		{
			return new DataStorageElement(a, c);
		}

		public static DataStorageElement operator +(DataStorageElement a, AdditionalArgument arg)
		{
			return new DataStorageElement(a, arg);
		}

		public static DataStorageElement operator *(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator *(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator *(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator *(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator *(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator -(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(-b)));
		}

		public static DataStorageElement operator -(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(-b)));
		}

		public static DataStorageElement operator -(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(0f - b)));
		}

		public static DataStorageElement operator -(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(0.0 - b)));
		}

		public static DataStorageElement operator -(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(-b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1m / (decimal)b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1m / (decimal)b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1.0 / (double)b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1.0 / b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1m / b)));
		}

		public static implicit operator DataStorageElement(bool b)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(b));
		}

		public static implicit operator DataStorageElement(int i)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(i));
		}

		public static implicit operator DataStorageElement(long l)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(l));
		}

		public static implicit operator DataStorageElement(decimal m)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(m));
		}

		public static implicit operator DataStorageElement(double d)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(d));
		}

		public static implicit operator DataStorageElement(float f)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(f));
		}

		public static implicit operator DataStorageElement(string s)
		{
			if (s != null)
			{
				return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(s));
			}
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JValue.CreateNull());
		}

		public static implicit operator DataStorageElement(JToken o)
		{
			return new DataStorageElement(OperationType.Replace, o);
		}

		public static implicit operator DataStorageElement(Array a)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)a));
		}

		public static implicit operator DataStorageElement(List<bool> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<int> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<long> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<decimal> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<double> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<float> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<string> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<object> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator bool(DataStorageElement e)
		{
			return RetrieveAndReturnBoolValue<bool>(e);
		}

		public static implicit operator bool?(DataStorageElement e)
		{
			return RetrieveAndReturnBoolValue<bool?>(e);
		}

		public static implicit operator int(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<int>(e);
		}

		public static implicit operator int?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<int?>(e);
		}

		public static implicit operator long(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<long>(e);
		}

		public static implicit operator long?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<long?>(e);
		}

		public static implicit operator float(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<float>(e);
		}

		public static implicit operator float?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<float?>(e);
		}

		public static implicit operator double(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<double>(e);
		}

		public static implicit operator double?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<double?>(e);
		}

		public static implicit operator decimal(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<decimal>(e);
		}

		public static implicit operator decimal?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<decimal?>(e);
		}

		public static implicit operator string(DataStorageElement e)
		{
			return RetrieveAndReturnStringValue(e);
		}

		public static implicit operator bool[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<bool[]>(e);
		}

		public static implicit operator int[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<int[]>(e);
		}

		public static implicit operator long[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<long[]>(e);
		}

		public static implicit operator decimal[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<decimal[]>(e);
		}

		public static implicit operator double[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<double[]>(e);
		}

		public static implicit operator float[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<float[]>(e);
		}

		public static implicit operator string[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<string[]>(e);
		}

		public static implicit operator object[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<object[]>(e);
		}

		public static implicit operator List<bool>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<bool>>(e);
		}

		public static implicit operator List<int>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<int>>(e);
		}

		public static implicit operator List<long>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<long>>(e);
		}

		public static implicit operator List<decimal>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<decimal>>(e);
		}

		public static implicit operator List<double>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<double>>(e);
		}

		public static implicit operator List<float>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<float>>(e);
		}

		public static implicit operator List<string>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<string>>(e);
		}

		public static implicit operator List<object>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<object>>(e);
		}

		public static implicit operator Array(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<Array>(e);
		}

		public static implicit operator JArray(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<JArray>(e);
		}

		public static implicit operator JToken(DataStorageElement e)
		{
			return e.Context.GetData(e.Context.Key);
		}

		public static DataStorageElement operator +(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.Parse(b.ToString()));
		}

		public static DataStorageElement operator *(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.Parse(b.ToString()));
		}

		public static DataStorageElement operator %(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.Parse(b.ToString()));
		}

		public static DataStorageElement operator ^(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.Parse(b.ToString()));
		}

		public static DataStorageElement operator -(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.Parse((-b).ToString()));
		}

		public static DataStorageElement operator /(DataStorageElement a, BigInteger b)
		{
			throw new InvalidOperationException("DataStorage[Key] / BigInterger is not supported, due to loss of precision when using integer division");
		}

		public static implicit operator DataStorageElement(BigInteger bi)
		{
			return new DataStorageElement(OperationType.Replace, JToken.Parse(bi.ToString()));
		}

		public static implicit operator BigInteger(DataStorageElement e)
		{
			return RetrieveAndReturnBigIntegerValue<BigInteger>(e);
		}

		public static implicit operator BigInteger?(DataStorageElement e)
		{
			return RetrieveAndReturnBigIntegerValue<BigInteger?>(e);
		}

		private static T RetrieveAndReturnBigIntegerValue<T>(DataStorageElement e)
		{
			if (e.cachedValue != null)
			{
				if (!BigInteger.TryParse(((object)e.cachedValue).ToString(), out var result))
				{
					return default(T);
				}
				return (T)Convert.ChangeType(result, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T));
			}
			BigInteger result2;
			BigInteger? bigInteger = (BigInteger.TryParse(((object)e.Context.GetData(e.Context.Key)).ToString(), out result2) ? new BigInteger?(result2) : null);
			if (!bigInteger.HasValue && !IsNullable<T>())
			{
				bigInteger = Activator.CreateInstance<BigInteger>();
			}
			foreach (OperationSpecification operation in e.Operations)
			{
				if (operation.OperationType == OperationType.Floor || operation.OperationType == OperationType.Ceil)
				{
					continue;
				}
				if (!BigInteger.TryParse(((object)operation.Value).ToString(), NumberStyles.AllowLeadingSign, null, out var result3))
				{
					throw new InvalidOperationException($"DataStorage[Key] cannot be converted to BigInterger as its value its not an integer number, value: {operation.Value}");
				}
				switch (operation.OperationType)
				{
				case OperationType.Replace:
					bigInteger = result3;
					break;
				case OperationType.Add:
					bigInteger += result3;
					break;
				case OperationType.Mul:
					bigInteger *= result3;
					break;
				case OperationType.Mod:
					bigInteger %= result3;
					break;
				case OperationType.Pow:
					bigInteger = BigInteger.Pow(bigInteger.Value, (int)operation.Value);
					break;
				case OperationType.Max:
				{
					BigInteger value = result3;
					BigInteger? bigInteger2 = bigInteger;
					if (value > bigInteger2)
					{
						bigInteger = result3;
					}
					break;
				}
				case OperationType.Min:
				{
					BigInteger value = result3;
					BigInteger? bigInteger2 = bigInteger;
					if (value < bigInteger2)
					{
						bigInteger = result3;
					}
					break;
				}
				case OperationType.Xor:
					bigInteger ^= result3;
					break;
				case OperationType.Or:
					bigInteger |= result3;
					break;
				case OperationType.And:
					bigInteger &= result3;
					break;
				case OperationType.LeftShift:
					bigInteger <<= (int)operation.Value;
					break;
				case OperationType.RightShift:
					bigInteger >>= (int)operation.Value;
					break;
				}
			}
			e.cachedValue = JToken.Parse(bigInteger.ToString());
			if (!bigInteger.HasValue)
			{
				return default(T);
			}
			return (T)Convert.ChangeType(bigInteger.Value, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T));
		}

		public void Initialize(JToken value)
		{
			Context.Initialize(Context.Key, value);
		}

		public void Initialize(IEnumerable value)
		{
			Context.Initialize(Context.Key, (JToken)(object)JArray.FromObject((object)value));
		}

		public Task<T> GetAsync<T>()
		{
			return GetAsync().ContinueWith((Task<JToken> r) => r.Result.ToObject<T>());
		}

		public Task<JToken> GetAsync()
		{
			return Context.GetAsync(Context.Key);
		}

		private static T RetrieveAndReturnArrayValue<T>(DataStorageElement e)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Invalid comparison between Unknown and I4
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			if (e.cachedValue != null)
			{
				return ((JToken)(JArray)e.cachedValue).ToObject<T>();
			}
			JArray val = (JArray)(((object)e.Context.GetData(e.Context.Key).ToObject<JArray>()) ?? ((object)new JArray()));
			foreach (OperationSpecification operation in e.Operations)
			{
				switch (operation.OperationType)
				{
				case OperationType.Add:
					if ((int)operation.Value.Type != 2)
					{
						throw new InvalidOperationException($"Cannot perform operation {OperationType.Add} on Array value, with a non Array value: {operation.Value}");
					}
					((JContainer)val).Merge((object)operation.Value);
					break;
				case OperationType.Replace:
					if ((int)operation.Value.Type != 2)
					{
						throw new InvalidOperationException($"Cannot replace Array value, with a non Array value: {operation.Value}");
					}
					val = (JArray)(((object)operation.Value.ToObject<JArray>()) ?? ((object)new JArray()));
					break;
				default:
					throw new InvalidOperationException($"Cannot perform operation {operation.OperationType} on Array value");
				}
			}
			e.cachedValue = (JToken)(object)val;
			return ((JToken)val).ToObject<T>();
		}

		private static string RetrieveAndReturnStringValue(DataStorageElement e)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Invalid comparison between Unknown and I4
			if (e.cachedValue != null)
			{
				return (string)e.cachedValue;
			}
			JToken val = e.Context.GetData(e.Context.Key);
			string text = (((int)val.Type == 10) ? null : ((object)val).ToString());
			foreach (OperationSpecification operation in e.Operations)
			{
				switch (operation.OperationType)
				{
				case OperationType.Add:
					text += (string)operation.Value;
					break;
				case OperationType.Mul:
					if ((int)operation.Value.Type != 6)
					{
						throw new InvalidOperationException($"Cannot perform operation {OperationType.Mul} on string value, with a non interger value: {operation.Value}");
					}
					text = string.Concat(Enumerable.Repeat(text, (int)operation.Value));
					break;
				case OperationType.Replace:
					text = (string)operation.Value;
					break;
				default:
					throw new InvalidOperationException($"Cannot perform operation {operation.OperationType} on string value");
				}
			}
			if (text == null)
			{
				e.cachedValue = (JToken)(object)JValue.CreateNull();
			}
			else
			{
				e.cachedValue = JToken.op_Implicit(text);
			}
			return (string)e.cachedValue;
		}

		private static T RetrieveAndReturnBoolValue<T>(DataStorageElement e)
		{
			if (e.cachedValue != null)
			{
				return e.cachedValue.ToObject<T>();
			}
			bool? flag = e.Context.GetData(e.Context.Key).ToObject<bool?>() ?? ((bool?)Activator.CreateInstance(typeof(T)));
			foreach (OperationSpecification operation in e.Operations)
			{
				if (operation.OperationType == OperationType.Replace)
				{
					flag = (bool?)operation.Value;
					continue;
				}
				throw new InvalidOperationException($"Cannot perform operation {operation.OperationType} on boolean value");
			}
			e.cachedValue = JToken.op_Implicit(flag);
			if (!flag.HasValue)
			{
				return default(T);
			}
			return (T)Convert.ChangeType(flag.Value, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T));
		}

		private static T RetrieveAndReturnDecimalValue<T>(DataStorageElement e)
		{
			if (e.cachedValue != null)
			{
				return e.cachedValue.ToObject<T>();
			}
			decimal? num = e.Context.GetData(e.Context.Key).ToObject<decimal?>();
			if (!num.HasValue && !IsNullable<T>())
			{
				num = Activator.CreateInstance<decimal>();
			}
			foreach (OperationSpecification operation in e.Operations)
			{
				switch (operation.OperationType)
				{
				case OperationType.Replace:
					num = (decimal)operation.Value;
					break;
				case OperationType.Add:
					num += (decimal?)(decimal)operation.Value;
					break;
				case OperationType.Mul:
					num *= (decimal?)(decimal)operation.Value;
					break;
				case OperationType.Mod:
					num %= (decimal?)(decimal)operation.Value;
					break;
				case OperationType.Pow:
					num = (decimal)Math.Pow((double)num.Value, (double)operation.Value);
					break;
				case OperationType.Max:
					num = Math.Max(num.Value, (decimal)operation.Value);
					break;
				case OperationType.Min:
					num = Math.Min(num.Value, (decimal)operation.Value);
					break;
				case OperationType.Xor:
					num = (long)num.Value ^ (long)operation.Value;
					break;
				case OperationType.Or:
					num = (long)num.Value | (long)operation.Value;
					break;
				case OperationType.And:
					num = (long)num.Value & (long)operation.Value;
					break;
				case OperationType.LeftShift:
					num = (long)num.Value << (int)operation.Value;
					break;
				case OperationType.RightShift:
					num = (long)num.Value >> (int)operation.Value;
					break;
				case OperationType.Floor:
					num = Math.Floor(num.Value);
					break;
				case OperationType.Ceil:
					num = Math.Ceiling(num.Value);
					break;
				}
			}
			e.cachedValue = JToken.op_Implicit(num);
			if (!num.HasValue)
			{
				return default(T);
			}
			return (T)Convert.ChangeType(num.Value, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T));
		}

		private static bool IsNullable<T>()
		{
			if (typeof(T).IsGenericType)
			{
				return typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition();
			}
			return false;
		}

		public T To<T>()
		{
			if (Operations.Count != 0)
			{
				throw new InvalidOperationException("DataStorageElement.To<T>() cannot be used together with other operations on the DataStorageElement");
			}
			return Context.GetData(Context.Key).ToObject<T>();
		}

		public override string ToString()
		{
			return (Context?.ToString() ?? "(null)") + ", (" + ListOperations() + ")";
		}

		private string ListOperations()
		{
			if (Operations != null)
			{
				return string.Join(", ", Operations.Select((OperationSpecification o) => o.ToString()).ToArray());
			}
			return "none";
		}
	}
	internal class DataStorageElementContext
	{
		internal string Key { get; set; }

		internal Action<string, DataStorageHelper.DataStorageUpdatedHandler> AddHandler { get; set; }

		internal Action<string, DataStorageHelper.DataStorageUpdatedHandler> RemoveHandler { get; set; }

		internal Func<string, JToken> GetData { get; set; }

		internal Action<string, JToken> Initialize { get; set; }

		internal Func<string, Task<JToken>> GetAsync { get; set; }

		public override string ToString()
		{
			return "Key: " + Key;
		}
	}
	public class GameData
	{
		[JsonProperty("location_name_to_id")]
		public Dictionary<string, long> LocationLookup { get; set; } = new Dictionary<string, long>();


		[JsonProperty("item_name_to_id")]
		public Dictionary<string, long> ItemLookup { get; set; } = new Dictionary<string, long>();


		[Obsolete("use Checksum instead")]
		[JsonProperty("version")]
		public int Version { get; set; }

		[JsonProperty("checksum")]
		public string Checksum { get; set; }
	}
	public class Hint
	{
		[JsonProperty("receiving_player")]
		public int ReceivingPlayer { get; set; }

		[JsonProperty("finding_player")]
		public int FindingPlayer { get; set; }

		[JsonProperty("item")]
		public long ItemId { get; set; }

		[JsonProperty("location")]
		public long LocationId { get; set; }

		[JsonProperty("item_flags")]
		public ItemFlags ItemFlags { get; set; }

		[JsonProperty("found")]
		public bool Found { get; set; }

		[JsonProperty("entrance")]
		public string Entrance { get; set; }

		[JsonProperty("status")]
		public HintStatus Status { get; set; }
	}
	public class ItemInfo
	{
		private readonly IItemInfoResolver itemInfoResolver;

		public long ItemId { get; }

		public long LocationId { get; }

		public PlayerInfo Player { get; }

		public ItemFlags Flags { get; }

		public string ItemName => itemInfoResolver.GetItemName(ItemId, ItemGame);

		public string ItemDisplayName => ItemName ?? $"Item: {ItemId}";

		public string LocationName => itemInfoResolver.GetLocationName(LocationId, LocationGame);

		public string LocationDisplayName => LocationName ?? $"Location: {LocationId}";

		public string ItemGame { get; }

		public string LocationGame { get; }

		public ItemInfo(NetworkItem item, string receiverGame, string senderGame, IItemInfoResolver itemInfoResolver, PlayerInfo player)
		{
			this.itemInfoResolver = itemInfoResolver;
			ItemGame = receiverGame;
			LocationGame = senderGame;
			ItemId = item.Item;
			LocationId = item.Location;
			Flags = item.Flags;
			Player = player;
		}

		public SerializableItemInfo ToSerializable()
		{
			return new SerializableItemInfo
			{
				IsScout = (GetType() == typeof(ScoutedItemInfo)),
				ItemId = ItemId,
				LocationId = LocationId,
				PlayerSlot = Player,
				Player = Player,
				Flags = Flags,
				ItemGame = ItemGame,
				ItemName = ItemName,
				LocationGame = LocationGame,
				LocationName = LocationName
			};
		}
	}
	public class ScoutedItemInfo : ItemInfo
	{
		public new PlayerInfo Player => base.Player;

		public bool IsReceiverRelatedToActivePlayer { get; }

		public ScoutedItemInfo(NetworkItem item, string receiverGame, string senderGame, IItemInfoResolver itemInfoResolver, IPlayerHelper players, PlayerInfo player)
			: base(item, receiverGame, senderGame, itemInfoResolver, player)
		{
			IsReceiverRelatedToActivePlayer = (players.ActivePlayer ?? new PlayerInfo()).IsRelatedTo(player);
		}
	}
	public class JsonMessagePart
	{
		[JsonProperty("type")]
		[JsonConverter(typeof(AttemptingStringEnumConverter), new object[] { typeof(SnakeCaseNamingStrategy) })]
		public JsonMessagePartType? Type { get; set; }

		[JsonProperty("color")]
		[JsonConverter(typeof(AttemptingStringEnumConverter), new object[] { typeof(SnakeCaseNamingStrategy) })]
		public JsonMessagePartColor? Color { get; set; }

		[JsonProperty("text")]
		public string Text { get; set; }

		[JsonProperty("player")]
		public int? Player { get; set; }

		[JsonProperty("flags")]
		public ItemFlags? Flags { get; set; }

		[JsonProperty("hint_status")]
		public HintStatus? HintStatus { get; set; }
	}
	public struct NetworkItem
	{
		[JsonProperty("item")]
		public long Item { get; set; }

		[JsonProperty("location")]
		public long Location { get; set; }

		[JsonProperty("player")]
		public int Player { get; set; }

		[JsonProperty("flags")]
		public ItemFlags Flags { get; set; }
	}
	public struct NetworkPlayer
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("alias")]
		public string Alias { get; set; }

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

		[JsonProperty("game")]
		public string Game { get; set; }

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

		[JsonProperty("group_members")]
		public int[] GroupMembers { get; set; }
	}
	public class NetworkVersion
	{
		[JsonProperty("major")]
		public int Major { get; set; }

		[JsonProperty("minor")]
		public int Minor { get; set; }

		[JsonProperty("build")]
		public int Build { get; set; }

		[JsonProperty("class")]
		public string Class => "Version";

		public NetworkVersion()
		{
		}

		public NetworkVersion(int major, int minor, int build)
		{
			Major = major;
			Minor = minor;
			Build = build;
		}

		public NetworkVersion(Version version)
		{
			Major = version.Major;
			Minor = version.Minor;
			Build = version.Build;
		}

		public Version ToVersion()
		{
			return new Version(Major, Minor, Build);
		}
	}
	public class OperationSpecification
	{
		[JsonProperty("operation")]
		[JsonConverter(typeof(AttemptingStringEnumConverter), new object[] { typeof(SnakeCaseNamingStrategy) })]
		public OperationType OperationType;

		[JsonProperty("value")]
		public JToken Value { get; set; }

		public override string ToString()
		{
			return $"{OperationType}: {Value}";
		}
	}
	public static class Operation
	{
		public static OperationSpecification Min(int i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(float i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(double i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(decimal i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(JToken i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = i
			};
		}

		public static OperationSpecification Min(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification Max(int i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(float i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(double i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(decimal i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(JToken i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = i
			};
		}

		public static OperationSpecification Max(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification Remove(JToken value)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Remove,
				Value = value
			};
		}

		public static OperationSpecification Pop(int value)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Pop,
				Value = JToken.op_Implicit(value)
			};
		}

		public static OperationSpecification Pop(JToken value)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Pop,
				Value = value
			};
		}

		public static OperationSpecification Update(IDictionary dictionary)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Update,
				Value = (JToken)(object)JObject.FromObject((object)dictionary)
			};
		}

		public static OperationSpecification Floor()
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Floor,
				Value = null
			};
		}

		public static OperationSpecification Ceiling()
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Ceil,
				Value = null
			};
		}
	}
	public static class Bitwise
	{
		public static OperationSpecification Xor(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Xor,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Xor(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Xor,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification Or(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Or,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Or(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Or,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification And(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.And,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification And(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.And,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification LeftShift(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.LeftShift,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification RightShift(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.RightShift,
				Value = JToken.op_Implicit(i)
			};
		}
	}
	public class Callback
	{
		internal DataStorageHelper.DataStorageUpdatedHandler Method { get; set; }

		private Callback()
		{
		}

		public static Callback Add(DataStorageHelper.DataStorageUpdatedHandler callback)
		{
			return new Callback
			{
				Method = callback
			};
		}
	}
	public class AdditionalArgument
	{
		internal string Key { get; set; }

		internal JToken Value { get; set; }

		private AdditionalArgument()
		{
		}

		public static AdditionalArgument Add(string name, JToken value)
		{
			return new AdditionalArgument
			{
				Key = name,
				Value = value
			};
		}
	}
	public class MinimalSerializableItemInfo
	{
		public long ItemId { get; set; }

		public long LocationId { get; set; }

		public int PlayerSlot { get; set; }

		public ItemFlags Flags { get; set; }

		public string ItemGame { get; set; }

		public string LocationGame { get; set; }
	}
	public class SerializableItemInfo : MinimalSerializableItemInfo
	{
		public bool IsScout { get; set; }

		public PlayerInfo Player { get; set; }

		public string ItemName { get; set; }

		public string LocationName { get; set; }

		[JsonIgnore]
		public string ItemDisplayName => ItemName ?? $"Item: {base.ItemId}";

		[JsonIgnore]
		public string LocationDisplayName => LocationName ?? $"Location: {base.LocationId}";

		public string ToJson(bool full = false)
		{
			//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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			MinimalSerializableItemInfo minimalSerializableItemInfo = this;
			if (!full)
			{
				minimalSerializableItemInfo = new MinimalSerializableItemInfo
				{
					ItemId = base.ItemId,
					LocationId = base.LocationId,
					PlayerSlot = base.PlayerSlot,
					Flags = base.Flags
				};
				if (IsScout)
				{
					minimalSerializableItemInfo.ItemGame = base.ItemGame;
				}
				else
				{
					minimalSerializableItemInfo.LocationGame = base.LocationGame;
				}
			}
			JsonSerializerSettings val = new JsonSerializerSettings
			{
				NullValueHandling = (NullValueHandling)1,
				Formatting = (Formatting)0
			};
			return JsonConvert.SerializeObject((object)minimalSerializableItemInfo, val);
		}

		public static SerializableItemInfo FromJson(string json, IArchipelagoSession session = null)
		{
			//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_0050: Expected O, but got Unknown
			ItemInfoStreamingContext additional = ((session != null) ? new ItemInfoStreamingContext
			{
				Items = session.Items,
				Locations = session.Locations,
				PlayerHelper = session.Players,
				ConnectionInfo = session.ConnectionInfo
			} : null);
			JsonSerializerSettings val = new JsonSerializerSettings
			{
				Context = new StreamingContext(StreamingContextStates.Other, additional)
			};
			return JsonConvert.DeserializeObject<SerializableItemInfo>(json, val);
		}

		[OnDeserialized]
		internal void OnDeserializedMethod(StreamingContext streamingContext)
		{
			if (base.ItemGame == null && base.LocationGame != null)
			{
				IsScout = false;
			}
			else if (base.ItemGame != null && base.LocationGame == null)
			{
				IsScout = true;
			}
			if (streamingContext.Context is ItemInfoStreamingContext itemInfoStreamingContext)
			{
				if (IsScout && base.LocationGame == null)
				{
					base.LocationGame = itemInfoStreamingContext.ConnectionInfo.Game;
				}
				else if (!IsScout && base.ItemGame == null)
				{
					base.ItemGame = itemInfoStreamingContext.ConnectionInfo.Game;
				}
				if (ItemName == null)
				{
					ItemName = itemInfoStreamingContext.Items.GetItemName(base.ItemId, base.ItemGame);
				}
				if (LocationName == null)
				{
					LocationName = itemInfoStreamingContext.Locations.GetLocationNameFromId(base.LocationId, base.LocationGame);
				}
				if (Player == null)
				{
					Player = itemInfoStreamingContext.PlayerHelper.GetPlayerInfo(base.PlayerSlot);
				}
			}
		}
	}
	internal class ItemInfoStreamingContext
	{
		public IReceivedItemsHelper Items { get; set; }

		public ILocationCheckHelper Locations { get; set; }

		public IPlayerHelper PlayerHelper { get; set; }

		public IConnectionInfoProvider ConnectionInfo { get; set; }
	}
}
namespace Archipelago.MultiClient.Net.MessageLog.Parts
{
	public class EntranceMessagePart : MessagePart
	{
		internal EntranceMessagePart(JsonMessagePart messagePart)
			: base(MessagePartType.Entrance, messagePart, Archipelago.MultiClient.Net.Colors.PaletteColor.Blue)
		{
			base.Text = messagePart.Text;
		}
	}
	public class HintStatusMessagePart : MessagePart
	{
		internal HintStatusMessagePart(JsonMessagePart messagePart)
			: base(MessagePartType.HintStatus, messagePart)
		{
			base.Text = messagePart.Text;
			if (messagePart.HintStatus.HasValue)
			{
				base.PaletteColor = ColorUtils.GetColor(messagePart.HintStatus.Value);
			}
		}
	}
	public class ItemMessagePart : MessagePart
	{
		public ItemFlags Flags { get; }

		public long ItemId { get; }

		public int Player { get; }

		internal ItemMessagePart(IPlayerHelper players, IItemInfoResolver items, JsonMessagePart part)
			: base(MessagePartType.Item, part)
		{
			Flags = part.Flags.GetValueOrDefault();
			base.PaletteColor = ColorUtils.GetColor(Flags);
			Player = part.Player.GetValueOrDefault();
			string game = (players.GetPlayerInfo(Player) ?? new PlayerInfo()).Game;
			JsonMessagePartType? type = part.Type;
			if (type.HasValue)
			{
				switch (type.GetValueOrDefault())
				{
				case JsonMessagePartType.ItemId:
					ItemId = long.Parse(part.Text);
					base.Text = items.GetItemName(ItemId, game) ?? $"Item: {ItemId}";
					break;
				case JsonMessagePartType.ItemName:
					ItemId = 0L;
					base.Text = part.Text;
					break;
				}
			}
		}
	}
	public class LocationMessagePart : MessagePart
	{
		public long LocationId { get; }

		public int Player { get; }

		internal LocationMessagePart(IPlayerHelper players, IItemInfoResolver itemInfoResolver, JsonMessagePart part)
			: base(MessagePartType.Location, part, Archipelago.MultiClient.Net.Colors.PaletteColor.Green)
		{
			Player = part.Player.GetValueOrDefault();
			string game = (players.GetPlayerInfo(Player) ?? new PlayerInfo()).Game;
			JsonMessagePartType? type = part.Type;
			if (type.HasValue)
			{
				switch (type.GetValueOrDefault())
				{
				case JsonMessagePartType.LocationId:
					LocationId = long.Parse(part.Text);
					base.Text = itemInfoResolver.GetLocationName(LocationId, game) ?? $"Location: {LocationId}";
					break;
				case JsonMessagePartType.LocationName:
					LocationId = itemInfoResolver.GetLocationId(part.Text, game);
					base.Text = part.Text;
					break;
				}
			}
		}
	}
	public class MessagePart
	{
		public string Text { get; internal set; }

		public MessagePartType Type { get; internal set; }

		public Color Color => GetColor(BuiltInPalettes.Dark);

		public PaletteColor? PaletteColor { get; protected set; }

		public bool IsBackgroundColor { get; internal set; }

		internal MessagePart(MessagePartType type, JsonMessagePart messagePart, PaletteColor? color = null)
		{
			Type = type;
			Text = messagePart.Text;
			if (color.HasValue)
			{
				PaletteColor = color.Value;
			}
			else if (messagePart.Color.HasValue)
			{
				PaletteColor = ColorUtils.GetColor(messagePart.Color.Value);
				IsBackgroundColor = messagePart.Color.Value >= JsonMessagePartColor.BlackBg;
			}
			else
			{
				PaletteColor = null;
			}
		}

		public T GetColor<T>(Palette<T> palette)
		{
			return palette[PaletteColor];
		}

		public override string ToString()
		{
			return Text;
		}
	}
	public enum MessagePartType
	{
		Text,
		Player,
		Item,
		Location,
		Entrance,
		HintStatus
	}
	public class PlayerMessagePart : MessagePart
	{
		public bool IsActivePlayer { get; }

		public int SlotId { get; }

		internal PlayerMessagePart(IPlayerHelper players, IConnectionInfoProvider connectionInfo, JsonMessagePart part)
			: base(MessagePartType.Player, part)
		{
			switch (part.Type)
			{
			case JsonMessagePartType.PlayerId:
				SlotId = int.Parse(part.Text);
				IsActivePlayer = SlotId == connectionInfo.Slot;
				base.Text = players.GetPlayerAlias(SlotId) ?? $"Player {SlotId}";
				break;
			case JsonMessagePartType.PlayerName:
				SlotId = 0;
				IsActivePlayer = false;
				base.Text = part.Text;
				break;
			}
			base.PaletteColor = (IsActivePlayer ? Archipelago.MultiClient.Net.Colors.PaletteColor.Magenta : Archipelago.MultiClient.Net.Colors.PaletteColor.Yellow);
		}
	}
}
namespace Archipelago.MultiClient.Net.MessageLog.Messages
{
	public class AdminCommandResultLogMessage : LogMessage
	{
		internal AdminCommandResultLogMessage(MessagePart[] parts)
			: base(parts)
		{
		}
	}
	public class ChatLogMessage : PlayerSpecificLogMessage
	{
		public string Message { get; }

		internal ChatLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, string message)
			: base(parts, players, team, slot)
		{
			Message = message;
		}
	}
	public class CollectLogMessage : PlayerSpecificLogMessage
	{
		internal CollectLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts, players, team, slot)
		{
		}
	}
	public class CommandResultLogMessage : LogMessage
	{
		internal CommandResultLogMessage(MessagePart[] parts)
			: base(parts)
		{
		}
	}
	public class CountdownLogMessage : LogMessage
	{
		public int RemainingSeconds { get; }

		internal CountdownLogMessage(MessagePart[] parts, int remainingSeconds)
			: base(parts)
		{
			RemainingSeconds = remainingSeconds;
		}
	}
	public class GoalLogMessage : PlayerSpecificLogMessage
	{
		internal GoalLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts, players, team, slot)
		{
		}
	}
	public class HintItemSendLogMessage : ItemSendLogMessage
	{
		public bool IsFound { get; }

		internal HintItemSendLogMessage(MessagePart[] parts, IPlayerHelper players, int receiver, int sender, NetworkItem item, bool found, IItemInfoResolver itemInfoResolver)
			: base(parts, players, receiver, sender, item, itemInfoResolver)
		{
			IsFound = found;
		}
	}
	public class ItemCheatLogMessage : ItemSendLogMessage
	{
		internal ItemCheatLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, NetworkItem item, IItemInfoResolver itemInfoResolver)
			: base(parts, players, slot, 0, item, team, itemInfoResolver)
		{
		}
	}
	public class ItemSendLogMessage : LogMessage
	{
		private PlayerInfo ActivePlayer { get; }

		public PlayerInfo Receiver { get; }

		public PlayerInfo Sender { get; }

		public bool IsReceiverTheActivePlayer => Receiver == ActivePlayer;

		public bool IsSenderTheActivePlayer => Sender == ActivePlayer;

		public bool IsRelatedToActivePlayer
		{
			get
			{
				if (!ActivePlayer.IsRelatedTo(Receiver))
				{
					return ActivePlayer.IsRelatedTo(Sender);
				}
				return true;
			}
		}

		public ItemInfo Item { get; }

		internal ItemSendLogMessage(MessagePart[] parts, IPlayerHelper players, int receiver, int sender, NetworkItem item, IItemInfoResolver itemInfoResolver)
			: this(parts, players, receiver, sender, item, players.ActivePlayer.Team, itemInfoResolver)
		{
		}

		internal ItemSendLogMessage(MessagePart[] parts, IPlayerHelper players, int receiver, int sender, NetworkItem item, int team, IItemInfoResolver itemInfoResolver)
			: base(parts)
		{
			ActivePlayer = players.ActivePlayer ?? new PlayerInfo();
			Receiver = players.GetPlayerInfo(team, receiver) ?? new PlayerInfo();
			Sender = players.GetPlayerInfo(team, sender) ?? new PlayerInfo();
			PlayerInfo player = players.GetPlayerInfo(team, item.Player) ?? new PlayerInfo();
			Item = new ItemInfo(item, Receiver.Game, Sender.Game, itemInfoResolver, player);
		}
	}
	public class JoinLogMessage : PlayerSpecificLogMessage
	{
		public string[] Tags { get; }

		internal JoinLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, string[] tags)
			: base(parts, players, team, slot)
		{
			Tags = tags;
		}
	}
	public class LeaveLogMessage : PlayerSpecificLogMessage
	{
		internal LeaveLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts, players, team, slot)
		{
		}
	}
	public class LogMessage
	{
		public MessagePart[] Parts { get; }

		internal LogMessage(MessagePart[] parts)
		{
			Parts = parts;
		}

		public override string ToString()
		{
			if (Parts.Length == 1)
			{
				return Parts[0].Text;
			}
			StringBuilder stringBuilder = new StringBuilder();
			MessagePart[] parts = Parts;
			foreach (MessagePart messagePart in parts)
			{
				stringBuilder.Append(messagePart.Text);
			}
			return stringBuilder.ToString();
		}
	}
	public abstract class PlayerSpecificLogMessage : LogMessage
	{
		private PlayerInfo ActivePlayer { get; }

		public PlayerInfo Player { get; }

		public bool IsActivePlayer => Player == ActivePlayer;

		public bool IsRelatedToActivePlayer => ActivePlayer.IsRelatedTo(Player);

		internal PlayerSpecificLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts)
		{
			ActivePlayer = players.ActivePlayer ?? new PlayerInfo();
			Player = players.GetPlayerInfo(team, slot) ?? new PlayerInfo();
		}
	}
	public class ReleaseLogMessage : PlayerSpecificLogMessage
	{
		internal ReleaseLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts, players, team, slot)
		{
		}
	}
	public class ServerChatLogMessage : LogMessage
	{
		public string Message { get; }

		internal ServerChatLogMessage(MessagePart[] parts, string message)
			: base(parts)
		{
			Message = message;
		}
	}
	public class TagsChangedLogMessage : PlayerSpecificLogMessage
	{
		public string[] Tags { get; }

		internal TagsChangedLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, string[] tags)
			: base(parts, players, team, slot)
		{
			Tags = tags;
		}
	}
	public class TutorialLogMessage : LogMessage
	{
		internal TutorialLogMessage(MessagePart[] parts)
			: base(parts)
		{
		}
	}
}
namespace Archipelago.MultiClient.Net.Helpers
{
	public class ArchipelagoSocketHelper : BaseArchipelagoSocketHelper<ClientWebSocket>, IArchipelagoSocketHelper
	{
		public Uri Uri { get; }

		internal ArchipelagoSocketHelper(Uri hostUri)
			: base(CreateWebSocket(), 1024)
		{
			Uri = hostUri;
		}

		private static ClientWebSocket CreateWebSocket()
		{
			return new ClientWebSocket();
		}

		public async Task ConnectAsync()
		{
			await ConnectToProvidedUri(Uri);
			StartPolling();
		}

		private async Task ConnectToProvidedUri(Uri uri)
		{
			if (uri.Scheme != "unspecified")
			{
				try
				{
					await Socket.ConnectAsync(uri, CancellationToken.None);
					return;
				}
				catch (Exception e)
				{
					OnError(e);
					throw;
				}
			}
			List<Exception> errors = new List<Exception>(0);
			try
			{
				await Socket.ConnectAsync(uri.AsWss(), CancellationToken.None);
				if (Socket.State == WebSocketState.Open)
				{
					return;
				}
			}
			catch (Exception item)
			{
				errors.Add(item);
				Socket = CreateWebSocket();
			}
			try
			{
				await Socket.ConnectAsync(uri.AsWs(), CancellationToken.None);
			}
			catch (Exception item2)
			{
				errors.Add(item2);
				OnError(new AggregateException(errors));
				throw;
			}
		}
	}
	public class BaseArchipelagoSocketHelper<T> where T : WebSocket
	{
		private static readonly ArchipelagoPacketConverter Converter = new ArchipelagoPacketConverter();

		private readonly BlockingCollection<Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>>> sendQueue = new BlockingCollection<Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>>>();

		internal T Socket;

		private readonly int bufferSize;

		public bool Connected
		{
			get
			{
				if (Socket.State != WebSocketState.Open)
				{
					return Socket.State == WebSocketState.CloseReceived;
				}
				return true;
			}
		}

		public event ArchipelagoSocketHelperDelagates.PacketReceivedHandler PacketReceived;

		public event ArchipelagoSocketHelperDelagates.PacketsSentHandler PacketsSent;

		public event ArchipelagoSocketHelperDelagates.ErrorReceivedHandler ErrorReceived;

		public event ArchipelagoSocketHelperDelagates.SocketClosedHandler SocketClosed;

		public event ArchipelagoSocketHelperDelagates.SocketOpenedHandler SocketOpened;

		internal BaseArchipelagoSocketHelper(T socket, int bufferSize = 1024)
		{
			Socket = socket;
			this.bufferSize = bufferSize;
		}

		internal void StartPolling()
		{
			if (this.SocketOpened != null)
			{
				this.SocketOpened();
			}
			Task.Run((Func<Task?>)PollingLoop);
			Task.Run((Func<Task?>)SendLoop);
		}

		private async Task PollingLoop()
		{
			byte[] buffer = new byte[bufferSize];
			while (Socket.State == WebSocketState.Open)
			{
				string message = null;
				try
				{
					message = await ReadMessageAsync(buffer);
				}
				catch (Exception e)
				{
					OnError(e);
				}
				OnMessageReceived(message);
			}
		}

		private async Task SendLoop()
		{
			while (Socket.State == WebSocketState.Open)
			{
				try
				{
					await HandleSendBuffer();
				}
				catch (Exception e)
				{
					OnError(e);
				}
				await Task.Delay(20);
			}
		}

		private async Task<string> ReadMessageAsync(byte[] buffer)
		{
			using MemoryStream readStream = new MemoryStream(buffer.Length);
			WebSocketReceiveResult result;
			do
			{
				result = await Socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
				if (result.MessageType == WebSocketMessageType.Close)
				{
					try
					{
						await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
					}
					catch
					{
					}
					OnSocketClosed();
				}
				else
				{
					readStream.Write(buffer, 0, result.Count);
				}
			}
			while (!result.EndOfMessage);
			return Encoding.UTF8.GetString(readStream.ToArray());
		}

		public async Task DisconnectAsync()
		{
			await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closure requested by client", CancellationToken.None);
			OnSocketClosed();
		}

		public void SendPacket(ArchipelagoPacketBase packet)
		{
			SendMultiplePackets(new List<ArchipelagoPacketBase> { packet });
		}

		public void SendMultiplePackets(List<ArchipelagoPacketBase> packets)
		{
			SendMultiplePackets(packets.ToArray());
		}

		public void SendMultiplePackets(params ArchipelagoPacketBase[] packets)
		{
			SendMultiplePacketsAsync(packets).Wait();
		}

		public Task SendPacketAsync(ArchipelagoPacketBase packet)
		{
			return SendMultiplePacketsAsync(new List<ArchipelagoPacketBase> { packet });
		}

		public Task SendMultiplePacketsAsync(List<ArchipelagoPacketBase> packets)
		{
			return SendMultiplePacketsAsync(packets.ToArray());
		}

		public Task SendMultiplePacketsAsync(params ArchipelagoPacketBase[] packets)
		{
			TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
			foreach (ArchipelagoPacketBase item in packets)
			{
				sendQueue.Add(new Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>>(item, taskCompletionSource));
			}
			return taskCompletionSource.Task;
		}

		private async Task HandleSendBuffer()
		{
			List<ArchipelagoPacketBase> list = new List<ArchipelagoPacketBase>();
			List<TaskCompletionSource<bool>> tasks = new List<TaskCompletionSource<bool>>();
			Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>> tuple = sendQueue.Take();
			list.Add(tuple.Item1);
			tasks.Add(tuple.Item2);
			Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>> item;
			while (sendQueue.TryTake(out item))
			{
				list.Add(item.Item1);
				tasks.Add(item.Item2);
			}
			if (!list.Any())
			{
				return;
			}
			if (Socket.State != WebSocketState.Open)
			{
				throw new ArchipelagoSocketClosedException();
			}
			ArchipelagoPacketBase[] packets = list.ToArray();
			string s = JsonConvert.SerializeObject((object)packets);
			byte[] messageBuffer = Encoding.UTF8.GetBytes(s);
			int messagesCount = (int)Math.Ceiling((double)messageBuffer.Length / (double)bufferSize);
			for (int i = 0; i < messagesCount; i++)
			{
				int num = bufferSize * i;
				int num2 = bufferSize;
				bool endOfMessage = i + 1 == messagesCount;
				if (num2 * (i + 1) > messageBuffer.Length)
				{
					num2 = messageBuffer.Length - num;
				}
				await Socket.SendAsync(new ArraySegment<byte>(messageBuffer, num, num2), WebSocketMessageType.Text, endOfMessage, CancellationToken.None);
			}
			foreach (TaskCompletionSource<bool> item2 in tasks)
			{
				item2.TrySetResult(result: true);
			}
			OnPacketSend(packets);
		}

		private void OnPacketSend(ArchipelagoPacketBase[] packets)
		{
			try
			{
				if (this.PacketsSent != null)
				{
					this.PacketsSent(packets);
				}
			}
			catch (Exception e)
			{
				OnError(e);
			}
		}

		private void OnSocketClosed()
		{
			try
			{
				if (this.SocketClosed != null)
				{
					this.SocketClosed("");
				}
			}
			catch (Exception e)
			{
				OnError(e);
			}
		}

		private void OnMessageReceived(string message)
		{
			try
			{
				if (string.IsNullOrEmpty(message) || this.PacketReceived == null)
				{
					return;
				}
				List<ArchipelagoPacketBase> list = null;
				try
				{
					list = JsonConvert.DeserializeObject<List<ArchipelagoPacketBase>>(message, (JsonConverter[])(object)new JsonConverter[1] { Converter });
				}
				catch (Exception e)
				{
					OnError(e);
				}
				if (list == null)
				{
					return;
				}
				foreach (ArchipelagoPacketBase item in list)
				{
					this.PacketReceived(item);
				}
			}
			catch (Exception e2)
			{
				OnError(e2);
			}
		}

		protected void OnError(Exception e)
		{
			try
			{
				if (this.ErrorReceived != null)
				{
					this.ErrorReceived(e, e.Message);
				}
			}
			catch (Exception ex)
			{
				Console.Out.WriteLine("Error occured during reporting of errorOuter Errror: " + e.Message + " " + e.StackTrace + "Inner Errror: " + ex.Message + " " + ex.StackTrace);
			}
		}
	}
	public interface IConnectionInfoProvider
	{
		string Game { get; }

		int Team { get; }

		int Slot { get; }

		string[] Tags { get; }

		ItemsHandlingFlags ItemsHandlingFlags { get; }

		string Uuid { get; }

		void UpdateConnectionOptions(string[] tags);

		void UpdateConnectionOptions(ItemsHandlingFlags itemsHandlingFlags);

		void UpdateConnectionOptions(string[] tags, ItemsHandlingFlags itemsHandlingFlags);
	}
	public class ConnectionInfoHelper : IConnectionInfoProvider
	{
		private readonly IArchipelagoSocketHelper socket;

		public string Game { get; private set; }

		public int Team { get; private set; }

		public int Slot { get; private set; }

		public string[] Tags { get; internal set; }

		public ItemsHandlingFlags ItemsHandlingFlags { get; internal set; }

		public string Uuid { get; private set; }

		internal ConnectionInfoHelper(IArchipelagoSocketHelper socket)
		{
			this.socket = socket;
			Reset();
			socket.PacketReceived += PacketReceived;
		}

		private void PacketReceived(ArchipelagoPacketBase packet)
		{
			if (!(packet is ConnectedPacket connectedPacket))
			{
				if (packet is ConnectionRefusedPacket)
				{
					Reset();
				}
				return;
			}
			Team = connectedPacket.Team;
			Slot = connectedPacket.Slot;
			if (connectedPacket.SlotInfo != null && connectedPacket.SlotInfo.ContainsKey(Slot))
			{
				Game = connectedPacket.SlotInfo[Slot].Game;
			}
		}

		internal void SetConnectionParameters(string game, string[] tags, ItemsHandlingFlags itemsHandlingFlags, string uuid)
		{
			Game = game;
			Tags = tags ?? new string[0];
			ItemsHandlingFlags = itemsHandlingFlags;
			Uuid = uuid ?? Guid.NewGuid().ToString();
		}

		private void Reset()
		{
			Game = null;
			Team = -1;
			Slot = -1;
			Tags = new string[0];
			ItemsHandlingFlags = ItemsHandlingFlags.NoItems;
			Uuid = null;
		}

		public void UpdateConnectionOptions(string[] tags)
		{
			UpdateConnectionOptions(tags, ItemsHandlingFlags);
		}

		public void UpdateConnectionOptions(ItemsHandlingFlags itemsHandlingFlags)
		{
			UpdateConnectionOptions(Tags, itemsHandlingFlags);
		}

		public void UpdateConnectionOptions(string[] tags, ItemsHandlingFlags itemsHandlingFlags)
		{
			SetConnectionParameters(Game, tags, itemsHandlingFlags, Uuid);
			socket.SendPacket(new ConnectUpdatePacket
			{
				Tags = Tags,
				ItemsHandling = ItemsHandlingFlags
			});
		}
	}
	public interface IDataStorageHelper : IDataStorageWrapper
	{
		DataStorageElement this[Scope scope, string key] { get; set; }

		DataStorageElement this[string key] { get; set; }
	}
	public class DataStorageHelper : IDataStorageHelper, IDataStorageWrapper
	{
		public delegate void DataStorageUpdatedHandler(JToken originalValue, JToken newValue, Dictionary<string, JToken> additionalArguments);

		private readonly Dictionary<string, DataStorageUpdatedHandler> onValueChangedEventHandlers = new Dictionary<string, DataStorageUpdatedHandler>();

		private readonly Dictionary<Guid, DataStorageUpdatedHandler> operationSpecificCallbacks = new Dictionary<Guid, DataStorageUpdatedHandler>();

		private readonly Dictionary<string, TaskCompletionSource<JToken>> asyncRetrievalTasks = new Dictionary<string, TaskCompletionSource<JToken>>();

		private readonly IArchipelagoSocketHelper socket;

		private readonly IConnectionInfoProvider connectionInfoProvider;

		public DataStorageElement this[Scope scope, string key]
		{
			get
			{
				return this[AddScope(scope, key)];
			}
			set
			{
				this[AddScope(scope, key)] = value;
			}
		}

		public DataStorageElement this[string key]
		{
			get
			{
				return new DataStorageElement(GetContextForKey(key));
			}
			set
			{
				SetValue(key, value);
			}
		}

		internal DataStorageHelper(IArchipelagoSocketHelper socket, IConnectionInfoProvider connectionInfoProvider)
		{
			this.socket = socket;
			this.connectionInfoProvider = connectionInfoProvider;
			socket.PacketReceived += OnPacketReceived;
		}

		private void OnPacketReceived(ArchipelagoPacketBase packet)
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Invalid comparison between Unknown and I4
			if (!(packet is RetrievedPacket retrievedPacket))
			{
				if (packet is SetReplyPacket setReplyPacket)
				{
					if (setReplyPacket.AdditionalArguments != null && setReplyPacket.AdditionalArguments.ContainsKey("Reference") && (int)setReplyPacket.AdditionalArguments["Reference"].Type == 8 && ((string)setReplyPacket.AdditionalArguments["Reference"]).TryParseNGuid(out var g) && operationSpecificCallbacks.TryGetValue(g, out var value))
					{
						value(setReplyPacket.OriginalValue, setReplyPacket.Value, setReplyPacket.AdditionalArguments);
						operationSpecificCallbacks.Remove(g);
					}
					if (onValueChangedEventHandlers.TryGetValue(setReplyPacket.Key, out var value2))
					{
						value2(setReplyPacket.OriginalValue, setReplyPacket.Value, setReplyPacket.AdditionalArguments);
					}
				}
				return;
			}
			foreach (KeyValuePair<string, JToken> datum in retrievedPacket.Data)
			{
				if (asyncRetrievalTasks.TryGetValue(datum.Key, out var value3))
				{
					value3.TrySetResult(datum.Value);
					asyncRetrievalTasks.Remove(datum.Key);
				}
			}
		}

		private Task<JToken> GetAsync(string key)
		{
			if (asyncRetrievalTasks.TryGetValue(key, out var value))
			{
				return value.Task;
			}
			TaskCompletionSource<JToken> taskCompletionSource = new TaskCompletionSource<JToken>();
			asyncRetrievalTasks[key] = taskCompletionSource;
			socket.SendPacketAsync(new GetPacket
			{
				Keys = new string[1] { key }
			});
			return taskCompletionSource.Task;
		}

		private void Initialize(string key, JToken value)
		{
			socket.SendPacketAsync(new SetPacket
			{
				Key = key,
				DefaultValue = value,
				Operations = new OperationSpecification[1]
				{
					new OperationSpecification
					{
						OperationType = OperationType.Default
					}
				}
			});
		}

		private JToken GetValue(string key)
		{
			Task<JToken> async = GetAsync(key);
			if (!async.Wait(TimeSpan.FromSeconds(2.0)))
			{
				throw new TimeoutException("Timed out retrieving data for key `" + key + "`. This may be due to an attempt to retrieve a value from the DataStorageHelper in a synchronous fashion from within a PacketReceived handler. When using the DataStorageHelper from within code which runs on the websocket thread then use the asynchronous getters. Ex: `DataStorageHelper[\"" + key + "\"].GetAsync().ContinueWith(x => {});`Be aware that DataStorageHelper calls tend to cause packet responses, so making a call from within a PacketReceived handler may cause an infinite loop.");
			}
			return async.Result;
		}

		private void SetValue(string key, DataStorageElement e)
		{
			if (key.StartsWith("_read_"))
			{
				throw new InvalidOperationException("DataStorage write operation on readonly key '" + key + "' is not allowed");
			}
			if (e == null)
			{
				e = new DataStorageElement(OperationType.Replace, (JToken)(object)JValue.CreateNull());
			}
			if (e.Context == null)
			{
				e.Context = GetContextForKey(key);
			}
			else if (e.Context.Key != key)
			{
				e.Operations.Insert(0, new OperationSpecification
				{
					OperationType = OperationType.Replace,
					Value = GetValue(e.Context.Key)
				});
			}
			Dictionary<string, JToken> dictionary = e.AdditionalArguments ?? new Dictionary<string, JToken>(0);
			if (e.Callbacks != null)
			{
				Guid key2 = Guid.NewGuid();
				operationSpecificCallbacks[key2] = e.Callbacks;
				dictionary["Reference"] = JToken.op_Implicit(key2.ToString("N"));
				socket.SendPacketAsync(new SetPacket
				{
					Key = key,
					Operations = e.Operations.ToArray(),
					WantReply = true,
					AdditionalArguments = dictionary
				});
			}
			else
			{
				socket.SendPacketAsync(new SetPacket
				{
					Key = key,
					Operations = e.Operations.ToArray(),
					AdditionalArguments = dictionary
				});
			}
		}

		private DataStorageElementContext GetContextForKey(string key)
		{
			return new DataStorageElementContext
			{
				Key = key,
				GetData = GetValue,
				GetAsync = GetAsync,
				Initialize = Initialize,
				AddHandler = AddHandler,
				RemoveHandler = RemoveHandler
			};
		}

		private void AddHandler(string key, DataStorageUpdatedHandler handler)
		{
			if (onValueChangedEventHandlers.ContainsKey(key))
			{
				Dictionary<string, DataStorageUpdatedHandler> dictionary = onValueChangedEventHandlers;
				dictionary[key] = (DataStorageUpdatedHandler)Delegate.Combine(dictionary[key], handler);
			}
			else
			{
				onValueChangedEventHandlers[key] = handler;
			}
			socket.SendPacketAsync(new SetNotifyPacket
			{
				Keys = new string[1] { key }
			});
		}

		private void RemoveHandler(string key, DataStorageUpdatedHandler handler)
		{
			if (onValueChangedEventHandlers.ContainsKey(key))
			{
				Dictionary<string, DataStorageUpdatedHandler> dictionary = onValueChangedEventHandlers;
				dictionary[key] = (DataStorageUpdatedHandler)Delegate.Remove(dictionary[key], handler);
				if (onValueChangedEventHandlers[key] == null)
				{
					onValueChangedEventHandlers.Remove(key);
				}
			}
		}

		private string AddScope(Scope scope, string key)
		{
			return scope switch
			{
				Scope.Global => key, 
				Scope.Game => $"{scope}:{connectionInfoProvider.Game}:{key}", 
				Scope.Team => $"{scope}:{connectionInfoProvider.Team}:{key}", 
				Scope.Slot => $"{scope}:{connectionInfoProvider.Slot}:{key}", 
				Scope.ReadOnly => "_read_" + key, 
				_ => throw new ArgumentOutOfRangeException("scope", scope, "Invalid scope for key " + key), 
			};
		}

		private DataStorageElement GetHintsElement(int? slot = null, int? team = null)
		{
			return this[Scope.ReadOnly, $"hints_{team ?? connectionInfoProvider.Team}_{slot ?? connectionInfoProvider.Slot}"];
		}

		private DataStorageElement GetSlotDataElement(int? slot = null)
		{
			return this[Scope.ReadOnly, $"slot_data_{slot ?? connectionInfoProvider.Slot}"];
		}

		private DataStorageElement GetItemNameGroupsElement(string game = null)
		{
			return this[Scope.ReadOnly, "item_name_groups_" + (game ?? connectionInfoProvider.Game)];
		}

		private DataStorageElement GetLocationNameGroupsElement(string game = null)
		{
			return this[Scope.ReadOnly, "location_name_groups_" + (game ?? connectionInfoProvider.Game)];
		}

		private DataStorageElement GetClientStatusElement(int? slot = null, int? team = null)
		{
			return this[Scope.ReadOnly, $"client_status_{team ?? connectionInfoProvider.Team}_{slot ?? connectionInfoProvider.Slot}"];
		}

		private DataStorageElement GetRaceModeElement()
		{
			return this[Scope.ReadOnly, "race_mode"];
		}

		public Hint[] GetHints(int? slot = null, int? team = null)
		{
			return GetHintsElement(slot, team).To<Hint[]>();
		}

		public Task<Hint[]> GetHintsAsync(int? slot = null, int? team = null)
		{
			return GetHintsElement(slot, team).GetAsync<Hint[]>();
		}

		public void TrackHints(Action<Hint[]> onHintsUpdated, bool retrieveCurrentlyUnlockedHints = true, int? slot = null, int? team = null)
		{
			GetHintsElement(slot, team).OnValueChanged += delegate(JToken _, JToken newValue, Dictionary<string, JToken> x)
			{
				onHintsUpdated(newValue.ToObject<Hint[]>());
			};
			if (retrieveCurrentlyUnlockedHints)
			{
				GetHintsAsync(slot, team).ContinueWith(delegate(Task<Hint[]> t)
				{
					onHintsUpdated(t.Result);
				});
			}
		}

		public Dictionary<string, object> GetSlotData(int? slot = null)
		{
			return GetSlotData<Dictionary<string, object>>(slot);
		}

		public T GetSlotData<T>(int? slot = null) where T : class
		{
			return GetSlotDataElement(slot).To<T>();
		}

		public Task<Dictionary<string, object>> GetSlotDataAsync(int? slot = null)
		{
			return GetSlotDataAsync<Dictionary<string, object>>(slot);
		}

		public Task<T> GetSlotDataAsync<T>(int? slot = null) where T : class
		{
			return GetSlotDataElement(slot).GetAsync<T>();
		}

		public Dictionary<string, string[]> GetItemNameGroups(string game = null)
		{
			return GetItemNameGroupsElement(game).To<Dictionary<string, string[]>>();
		}

		public Task<Dictionary<string, string[]>> GetItemNameGroupsAsync(string game = null)
		{
			return GetItemNameGroupsElement(game).GetAsync<Dictionary<string, string[]>>();
		}

		public Dictionary<string, string[]> GetLocationNameGroups(string game = null)
		{
			return GetLocationNameGroupsElement(game).To<Dictionary<string, string[]>>();
		}

		public Task<Dictionary<string, string[]>> GetLocationNameGroupsAsync(string game = null)
		{
			return GetLocationNameGroupsElement(game).GetAsync<Dictionary<string, string[]>>();
		}

		public ArchipelagoClientState GetClientStatus(int? slot = null, int? team = null)
		{
			return GetClientStatusElement(slot, team).To<ArchipelagoClientState?>().GetValueOrDefault();
		}

		public Task<ArchipelagoClientState> GetClientStatusAsync(int? slot = null, int? team = null)
		{
			return GetClientStatusElement(slot, team).GetAsync<ArchipelagoClientState?>().ContinueWith((Task<ArchipelagoClientState?> r) => r.Result.GetValueOrDefault());
		}

		public void TrackClientStatus(Action<ArchipelagoClientState> onStatusUpdated, bool retrieveCurrentClientStatus = true, int? slot = null, int? team = null)
		{
			GetClientStatusElement(slot, team).OnValueChanged += delegate(JToken _, JToken newValue, Dictionary<string, JToken> x)
			{
				onStatusUpdated(newValue.ToObject<ArchipelagoClientState>());
	

BepInEx/plugins/WKRando/MonoMod.Backports.dll

Decompiled 3 hours ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("0x0ade, DaNike")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2024 0x0ade, DaNike")]
[assembly: AssemblyDescription("A set of backports of new BCL features to all frameworks which MonoMod supports.")]
[assembly: AssemblyFileVersion("1.1.2.0")]
[assembly: AssemblyInformationalVersion("1.1.2+a1b82852b")]
[assembly: AssemblyProduct("MonoMod.Backports")]
[assembly: AssemblyTitle("MonoMod.Backports")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/MonoMod/MonoMod.git")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.2.0")]
[assembly: TypeForwardedTo(typeof(ArrayPool<>))]
[assembly: TypeForwardedTo(typeof(BuffersExtensions))]
[assembly: TypeForwardedTo(typeof(IBufferWriter<>))]
[assembly: TypeForwardedTo(typeof(IMemoryOwner<>))]
[assembly: TypeForwardedTo(typeof(IPinnable))]
[assembly: TypeForwardedTo(typeof(MemoryHandle))]
[assembly: TypeForwardedTo(typeof(MemoryManager<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySequence<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySequenceSegment<>))]
[assembly: TypeForwardedTo(typeof(StandardFormat))]
[assembly: TypeForwardedTo(typeof(ConcurrentBag<>))]
[assembly: TypeForwardedTo(typeof(ConcurrentDictionary<, >))]
[assembly: TypeForwardedTo(typeof(ConcurrentQueue<>))]
[assembly: TypeForwardedTo(typeof(ConcurrentStack<>))]
[assembly: TypeForwardedTo(typeof(EnumerablePartitionerOptions))]
[assembly: TypeForwardedTo(typeof(IProducerConsumerCollection<>))]
[assembly: TypeForwardedTo(typeof(OrderablePartitioner<>))]
[assembly: TypeForwardedTo(typeof(Partitioner))]
[assembly: TypeForwardedTo(typeof(Partitioner<>))]
[assembly: TypeForwardedTo(typeof(IReadOnlyCollection<>))]
[assembly: TypeForwardedTo(typeof(IReadOnlyList<>))]
[assembly: TypeForwardedTo(typeof(IStructuralComparable))]
[assembly: TypeForwardedTo(typeof(IStructuralEquatable))]
[assembly: TypeForwardedTo(typeof(HashCode))]
[assembly: TypeForwardedTo(typeof(Memory<>))]
[assembly: TypeForwardedTo(typeof(MemoryExtensions))]
[assembly: TypeForwardedTo(typeof(ReadOnlyMemory<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySpan<>))]
[assembly: TypeForwardedTo(typeof(IntrospectionExtensions))]
[assembly: TypeForwardedTo(typeof(IReflectableType))]
[assembly: TypeForwardedTo(typeof(TypeDelegator))]
[assembly: TypeForwardedTo(typeof(TypeInfo))]
[assembly: TypeForwardedTo(typeof(CallerFilePathAttribute))]
[assembly: TypeForwardedTo(typeof(CallerLineNumberAttribute))]
[assembly: TypeForwardedTo(typeof(CallerMemberNameAttribute))]
[assembly: TypeForwardedTo(typeof(ConditionalWeakTable<, >))]
[assembly: TypeForwardedTo(typeof(TupleElementNamesAttribute))]
[assembly: TypeForwardedTo(typeof(Unsafe))]
[assembly: TypeForwardedTo(typeof(DefaultDllImportSearchPathsAttribute))]
[assembly: TypeForwardedTo(typeof(DllImportSearchPath))]
[assembly: TypeForwardedTo(typeof(MemoryMarshal))]
[assembly: TypeForwardedTo(typeof(SequenceMarshal))]
[assembly: TypeForwardedTo(typeof(SequencePosition))]
[assembly: TypeForwardedTo(typeof(Span<>))]
[assembly: TypeForwardedTo(typeof(SpinLock))]
[assembly: TypeForwardedTo(typeof(SpinWait))]
[assembly: TypeForwardedTo(typeof(ThreadLocal<>))]
[assembly: TypeForwardedTo(typeof(Volatile))]
[assembly: TypeForwardedTo(typeof(Tuple))]
[assembly: TypeForwardedTo(typeof(Tuple<>))]
[assembly: TypeForwardedTo(typeof(Tuple<, >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , , , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , , , , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , , , , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple))]
[assembly: TypeForwardedTo(typeof(ValueTuple<>))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , , >))]
[assembly: TypeForwardedTo(typeof(WeakReference<>))]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal static class AssemblyInfo
{
	public const string AssemblyName = "MonoMod.Backports";

	public const string AssemblyVersion = "1.1.2";
}
namespace MonoMod.SourceGen.Attributes
{
	[AttributeUsage(AttributeTargets.Class)]
	internal sealed class EmitILOverloadsAttribute : Attribute
	{
		public EmitILOverloadsAttribute(string filename, string kind)
		{
		}
	}
	internal static class ILOverloadKind
	{
		public const string Cursor = "ILCursor";

		public const string Matcher = "ILMatcher";
	}
}
namespace MonoMod.Backports
{
	public static class MethodImplOptionsEx
	{
		public const MethodImplOptions Unmanaged = MethodImplOptions.Unmanaged;

		public const MethodImplOptions NoInlining = MethodImplOptions.NoInlining;

		public const MethodImplOptions ForwardRef = MethodImplOptions.ForwardRef;

		public const MethodImplOptions Synchronized = MethodImplOptions.Synchronized;

		public const MethodImplOptions NoOptimization = MethodImplOptions.NoOptimization;

		public const MethodImplOptions PreserveSig = MethodImplOptions.PreserveSig;

		public const MethodImplOptions AggressiveInlining = MethodImplOptions.AggressiveInlining;

		public const MethodImplOptions AggressiveOptimization = MethodImplOptions.AggressiveOptimization;

		public const MethodImplOptions InternalCall = MethodImplOptions.InternalCall;
	}
}
namespace MonoMod.Backports.ILHelpers
{
	[CLSCompliant(false)]
	public static class UnsafeRaw
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static T Read<T>(void* source)
		{
			return Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static T ReadUnaligned<T>(void* source)
		{
			return Unsafe.ReadUnaligned<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static T ReadUnaligned<T>(ref byte source)
		{
			return Unsafe.ReadUnaligned<T>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void Write<T>(void* destination, T value)
		{
			Unsafe.Write(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void WriteUnaligned<T>(void* destination, T value)
		{
			Unsafe.WriteUnaligned(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void WriteUnaligned<T>(ref byte destination, T value)
		{
			Unsafe.WriteUnaligned(ref destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void Copy<T>(void* destination, ref T source)
		{
			Unsafe.Copy(destination, ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void Copy<T>(ref T destination, void* source)
		{
			Unsafe.Copy(ref destination, source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void* AsPointer<T>(ref T value)
		{
			return Unsafe.AsPointer(ref value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void SkipInit<T>(out T value)
		{
			Unsafe.SkipInit<T>(out value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void CopyBlock(void* destination, void* source, uint byteCount)
		{
			Unsafe.CopyBlock(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void CopyBlock(ref byte destination, ref byte source, uint byteCount)
		{
			Unsafe.CopyBlock(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount)
		{
			Unsafe.CopyBlockUnaligned(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount)
		{
			Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount)
		{
			Unsafe.InitBlock(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void InitBlock(ref byte startAddress, byte value, uint byteCount)
		{
			Unsafe.InitBlock(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount)
		{
			Unsafe.InitBlockUnaligned(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
		{
			Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static T As<T>(object o) where T : class
		{
			return Unsafe.As<T>(o);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static ref T AsRef<T>(void* source)
		{
			return ref Unsafe.AsRef<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T AsRef<T>(in T source)
		{
			return ref Unsafe.AsRef(in source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref TTo As<TFrom, TTo>(ref TFrom source)
		{
			return ref Unsafe.As<TFrom, TTo>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Unbox<T>(object box) where T : struct
		{
			return ref Unsafe.Unbox<T>(box);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, nint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, nuint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, nint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, nuint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static nint ByteOffset<T>(ref T origin, ref T target)
		{
			return Unsafe.ByteOffset(ref origin, ref target);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static bool AreSame<T>(ref T left, ref T right)
		{
			return Unsafe.AreSame(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressGreaterThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static bool IsAddressLessThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressLessThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static bool IsNullRef<T>(ref T source)
		{
			return Unsafe.IsNullRef(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T NullRef<T>()
		{
			return ref Unsafe.NullRef<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static int SizeOf<T>()
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Add<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void* Add<T>(void* source, int elementOffset)
		{
			return Unsafe.Add<T>(source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Add<T>(ref T source, nint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Add<T>(ref T source, nuint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Subtract<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void* Subtract<T>(void* source, int elementOffset)
		{
			return Unsafe.Subtract<T>(source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Subtract<T>(ref T source, nint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Subtract<T>(ref T source, nuint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}
	}
}
namespace System
{
	public static class ArrayEx
	{
		public static int MaxLength => 1879048191;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static T[] Empty<T>()
		{
			return Array.Empty<T>();
		}
	}
	public static class EnvironmentEx
	{
		public static int CurrentManagedThreadId => Environment.CurrentManagedThreadId;
	}
	public sealed class Gen2GcCallback : CriticalFinalizerObject
	{
		private readonly Func<bool>? _callback0;

		private readonly Func<object, bool>? _callback1;

		private GCHandle _weakTargetObj;

		private Gen2GcCallback(Func<bool> callback)
		{
			_callback0 = callback;
		}

		private Gen2GcCallback(Func<object, bool> callback, object targetObj)
		{
			_callback1 = callback;
			_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak);
		}

		public static void Register(Func<bool> callback)
		{
			new Gen2GcCallback(callback);
		}

		public static void Register(Func<object, bool> callback, object targetObj)
		{
			new Gen2GcCallback(callback, targetObj);
		}

		~Gen2GcCallback()
		{
			if (_weakTargetObj.IsAllocated)
			{
				object target = _weakTargetObj.Target;
				if (target == null)
				{
					_weakTargetObj.Free();
					return;
				}
				try
				{
					if (!_callback1(target))
					{
						_weakTargetObj.Free();
						return;
					}
				}
				catch
				{
				}
			}
			else
			{
				try
				{
					if (!_callback0())
					{
						return;
					}
				}
				catch
				{
				}
			}
			GC.ReRegisterForFinalize(this);
		}
	}
	public static class MathEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static byte Clamp(byte value, byte min, byte max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static decimal Clamp(decimal value, decimal min, decimal max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static double Clamp(double value, double min, double max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static short Clamp(short value, short min, short max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int Clamp(int value, int min, int max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static long Clamp(long value, long min, long max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static nint Clamp(nint value, nint min, nint max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static sbyte Clamp(sbyte value, sbyte min, sbyte max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Clamp(float value, float min, float max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ushort Clamp(ushort value, ushort min, ushort max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint Clamp(uint value, uint min, uint max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong Clamp(ulong value, ulong min, ulong max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static nuint Clamp(nuint value, nuint min, nuint max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[DoesNotReturn]
		private static void ThrowMinMaxException<T>(T min, T max)
		{
			throw new ArgumentException($"Minimum {min} is less than maximum {max}");
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
	public static class StringComparerEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static StringComparer FromComparison(StringComparison comparisonType)
		{
			return StringComparer.FromComparison(comparisonType);
		}
	}
	public static class StringExtensions
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			System.ThrowHelper.ThrowIfArgumentNull(oldValue, System.ExceptionArgument.oldValue);
			System.ThrowHelper.ThrowIfArgumentNull(newValue, System.ExceptionArgument.newValue);
			return self.Replace(oldValue, newValue, comparison);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Contains(this string self, string value, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			System.ThrowHelper.ThrowIfArgumentNull(value, System.ExceptionArgument.value);
			return self.Contains(value, comparison);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Contains(this string self, char value, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			return self.Contains(value, comparison);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetHashCode(this string self, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			return self.GetHashCode(comparison);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf(this string self, char value, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			return self.IndexOf(value, comparison);
		}
	}
	internal static class ThrowHelper
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static void ThrowIfArgumentNull([NotNull] object? obj, System.ExceptionArgument argument)
		{
			if (obj == null)
			{
				ThrowArgumentNullException(argument);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static void ThrowIfArgumentNull([NotNull] object? obj, string argument, string? message = null)
		{
			if (obj == null)
			{
				ThrowArgumentNullException(argument, message);
			}
		}

		[DoesNotReturn]
		internal static void ThrowArgumentNullException(System.ExceptionArgument argument)
		{
			throw CreateArgumentNullException(argument);
		}

		[DoesNotReturn]
		internal static void ThrowArgumentNullException(string argument, string? message = null)
		{
			throw CreateArgumentNullException(argument, message);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentNullException(System.ExceptionArgument argument)
		{
			return CreateArgumentNullException(argument.ToString());
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentNullException(string argument, string? message = null)
		{
			return new ArgumentNullException(argument, message);
		}

		[DoesNotReturn]
		internal static void ThrowArrayTypeMismatchException()
		{
			throw CreateArrayTypeMismatchException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArrayTypeMismatchException()
		{
			return new ArrayTypeMismatchException();
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type)
		{
			throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type)
		{
			return new ArgumentException($"Type {type} with managed pointers cannot be used in a Span");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_DestinationTooShort()
		{
			throw CreateArgumentException_DestinationTooShort();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_DestinationTooShort()
		{
			return new ArgumentException("Destination too short");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException(string message, string? argument = null)
		{
			throw CreateArgumentException(message, argument);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException(string message, string? argument)
		{
			return new ArgumentException(message, argument ?? "");
		}

		[DoesNotReturn]
		internal static void ThrowIndexOutOfRangeException()
		{
			throw CreateIndexOutOfRangeException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateIndexOutOfRangeException()
		{
			return new IndexOutOfRangeException();
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException()
		{
			throw CreateArgumentOutOfRangeException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException()
		{
			return new ArgumentOutOfRangeException();
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			throw CreateArgumentOutOfRangeException(argument);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			return new ArgumentOutOfRangeException(argument.ToString());
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge()
		{
			throw CreateArgumentOutOfRangeException_PrecisionTooLarge();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge()
		{
			return new ArgumentOutOfRangeException("precision", $"Precision too large (max: {99})");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit()
		{
			throw CreateArgumentOutOfRangeException_SymbolDoesNotFit();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit()
		{
			return new ArgumentOutOfRangeException("symbol", "Bad format specifier");
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException()
		{
			throw CreateInvalidOperationException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException()
		{
			return new InvalidOperationException();
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException_OutstandingReferences()
		{
			throw CreateInvalidOperationException_OutstandingReferences();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_OutstandingReferences()
		{
			return new InvalidOperationException("Outstanding references");
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException_UnexpectedSegmentType()
		{
			throw CreateInvalidOperationException_UnexpectedSegmentType();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_UnexpectedSegmentType()
		{
			return new InvalidOperationException("Unexpected segment type");
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException_EndPositionNotReached()
		{
			throw CreateInvalidOperationException_EndPositionNotReached();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_EndPositionNotReached()
		{
			return new InvalidOperationException("End position not reached");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange()
		{
			throw CreateArgumentOutOfRangeException_PositionOutOfRange();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange()
		{
			return new ArgumentOutOfRangeException("position");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange()
		{
			throw CreateArgumentOutOfRangeException_OffsetOutOfRange();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange()
		{
			return new ArgumentOutOfRangeException("offset");
		}

		[DoesNotReturn]
		internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer()
		{
			throw CreateObjectDisposedException_ArrayMemoryPoolBuffer();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer()
		{
			return new ObjectDisposedException("ArrayMemoryPoolBuffer");
		}

		[DoesNotReturn]
		internal static void ThrowFormatException_BadFormatSpecifier()
		{
			throw CreateFormatException_BadFormatSpecifier();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateFormatException_BadFormatSpecifier()
		{
			return new FormatException("Bad format specifier");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_OverlapAlignmentMismatch()
		{
			throw CreateArgumentException_OverlapAlignmentMismatch();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_OverlapAlignmentMismatch()
		{
			return new ArgumentException("Overlap alignment mismatch");
		}

		[DoesNotReturn]
		internal static void ThrowNotSupportedException(string? msg = null)
		{
			throw CreateThrowNotSupportedException(msg);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateThrowNotSupportedException(string? msg)
		{
			return new NotSupportedException();
		}

		[DoesNotReturn]
		internal static void ThrowKeyNullException()
		{
			ThrowArgumentNullException(System.ExceptionArgument.key);
		}

		[DoesNotReturn]
		internal static void ThrowValueNullException()
		{
			throw CreateThrowValueNullException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateThrowValueNullException()
		{
			return new ArgumentException("Value is null");
		}

		[DoesNotReturn]
		internal static void ThrowOutOfMemoryException()
		{
			throw CreateOutOfMemoryException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateOutOfMemoryException()
		{
			return new OutOfMemoryException();
		}

		public static bool TryFormatThrowFormatException(out int bytesWritten)
		{
			bytesWritten = 0;
			ThrowFormatException_BadFormatSpecifier();
			return false;
		}

		public static bool TryParseThrowFormatException<T>(out T value, out int bytesConsumed)
		{
			value = default(T);
			bytesConsumed = 0;
			ThrowFormatException_BadFormatSpecifier();
			return false;
		}

		[DoesNotReturn]
		public static void ThrowArgumentValidationException<T>(ReadOnlySequenceSegment<T>? startSegment, int startIndex, ReadOnlySequenceSegment<T>? endSegment)
		{
			throw CreateArgumentValidationException(startSegment, startIndex, endSegment);
		}

		private static Exception CreateArgumentValidationException<T>(ReadOnlySequenceSegment<T>? startSegment, int startIndex, ReadOnlySequenceSegment<T>? endSegment)
		{
			if (startSegment == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.startSegment);
			}
			if (endSegment == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.endSegment);
			}
			if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.endSegment);
			}
			if ((uint)startSegment.Memory.Length < (uint)startIndex)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.startIndex);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.endIndex);
		}

		[DoesNotReturn]
		public static void ThrowArgumentValidationException(Array? array, int start)
		{
			throw CreateArgumentValidationException(array, start);
		}

		private static Exception CreateArgumentValidationException(Array? array, int start)
		{
			if (array == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.array);
			}
			if ((uint)start > (uint)array.Length)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.length);
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_TupleIncorrectType(object other)
		{
			throw new ArgumentException($"Value tuple of incorrect type (found {other.GetType()})", "other");
		}

		[DoesNotReturn]
		public static void ThrowStartOrEndArgumentValidationException(long start)
		{
			throw CreateStartOrEndArgumentValidationException(start);
		}

		private static Exception CreateStartOrEndArgumentValidationException(long start)
		{
			if (start < 0)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.length);
		}
	}
	internal enum ExceptionArgument
	{
		length,
		start,
		bufferSize,
		minimumBufferSize,
		elementIndex,
		comparable,
		comparer,
		destination,
		offset,
		startSegment,
		endSegment,
		startIndex,
		endIndex,
		array,
		culture,
		manager,
		key,
		collection,
		index,
		type,
		self,
		value,
		oldValue,
		newValue
	}
	public static class TypeExtensions
	{
		public static bool IsByRefLike(this Type type)
		{
			System.ThrowHelper.ThrowIfArgumentNull(type, System.ExceptionArgument.type);
			if ((object)type == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.type);
			}
			return type.IsByRefLike;
		}
	}
}
namespace System.Threading
{
	public static class MonitorEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Enter(object obj, ref bool lockTaken)
		{
			Monitor.Enter(obj, ref lockTaken);
		}
	}
}
namespace System.Text
{
	public static class StringBuilderExtensions
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static StringBuilder Clear(this StringBuilder builder)
		{
			System.ThrowHelper.ThrowIfArgumentNull(builder, "builder");
			return builder.Clear();
		}
	}
}
namespace System.Numerics
{
	public static class BitOperations
	{
		private static ReadOnlySpan<byte> TrailingZeroCountDeBruijn => new byte[32]
		{
			0, 1, 28, 2, 29, 14, 24, 3, 30, 22,
			20, 15, 25, 17, 4, 8, 31, 27, 13, 23,
			21, 19, 16, 7, 26, 12, 18, 6, 11, 5,
			10, 9
		};

		private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32]
		{
			0, 9, 1, 10, 13, 21, 2, 29, 11, 14,
			16, 18, 22, 25, 3, 30, 8, 12, 20, 28,
			15, 17, 24, 7, 19, 27, 23, 6, 26, 5,
			4, 31
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(uint value)
		{
			if (value == 0)
			{
				return 32;
			}
			return 0x1F ^ Log2SoftwareFallback(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(ulong value)
		{
			uint num = (uint)(value >> 32);
			if (num == 0)
			{
				return 32 + LeadingZeroCount((uint)value);
			}
			return LeadingZeroCount(num);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(uint value)
		{
			value |= 1u;
			return Log2SoftwareFallback(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(ulong value)
		{
			value |= 1;
			uint num = (uint)(value >> 32);
			if (num == 0)
			{
				return Log2((uint)value);
			}
			return 32 + Log2(num);
		}

		private static int Log2SoftwareFallback(uint value)
		{
			value |= value >> 1;
			value |= value >> 2;
			value |= value >> 4;
			value |= value >> 8;
			value |= value >> 16;
			return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (IntPtr)(int)(value * 130329821 >> 27));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int Log2Ceiling(uint value)
		{
			int num = Log2(value);
			if (PopCount(value) != 1)
			{
				num++;
			}
			return num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int Log2Ceiling(ulong value)
		{
			int num = Log2(value);
			if (PopCount(value) != 1)
			{
				num++;
			}
			return num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(uint value)
		{
			return SoftwareFallback(value);
			static int SoftwareFallback(uint value)
			{
				value -= (value >> 1) & 0x55555555;
				value = (value & 0x33333333) + ((value >> 2) & 0x33333333);
				value = ((value + (value >> 4)) & 0xF0F0F0F) * 16843009 >> 24;
				return (int)value;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(ulong value)
		{
			if (IntPtr.Size == 8)
			{
				return PopCount((uint)value) + PopCount((uint)(value >> 32));
			}
			return SoftwareFallback(value);
			static int SoftwareFallback(ulong value)
			{
				value -= (value >> 1) & 0x5555555555555555L;
				value = (value & 0x3333333333333333L) + ((value >> 2) & 0x3333333333333333L);
				value = ((value + (value >> 4)) & 0xF0F0F0F0F0F0F0FL) * 72340172838076673L >> 56;
				return (int)value;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(int value)
		{
			return TrailingZeroCount((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(uint value)
		{
			if (value == 0)
			{
				return 32;
			}
			return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(TrailingZeroCountDeBruijn), (IntPtr)(int)((value & (0 - value)) * 125613361 >> 27));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(long value)
		{
			return TrailingZeroCount((ulong)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(ulong value)
		{
			uint num = (uint)value;
			if (num == 0)
			{
				return 32 + TrailingZeroCount((uint)(value >> 32));
			}
			return TrailingZeroCount(num);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RotateLeft(uint value, int offset)
		{
			return (value << offset) | (value >> 32 - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RotateLeft(ulong value, int offset)
		{
			return (value << offset) | (value >> 64 - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RotateRight(uint value, int offset)
		{
			return (value >> offset) | (value << 32 - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RotateRight(ulong value, int offset)
		{
			return (value >> offset) | (value << 64 - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static uint ResetLowestSetBit(uint value)
		{
			return value & (value - 1);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static uint ResetBit(uint value, int bitPos)
		{
			return value & (uint)(~(1 << bitPos));
		}
	}
	public static class BitOperationsEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsPow2(int value)
		{
			if ((value & (value - 1)) == 0)
			{
				return value > 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static bool IsPow2(uint value)
		{
			if ((value & (value - 1)) == 0)
			{
				return value != 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsPow2(long value)
		{
			if ((value & (value - 1)) == 0L)
			{
				return value > 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static bool IsPow2(ulong value)
		{
			if ((value & (value - 1)) == 0L)
			{
				return value != 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsPow2(nint value)
		{
			if ((value & (value - 1)) == 0)
			{
				return value > 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static bool IsPow2(nuint value)
		{
			if ((value & (value - 1)) == 0)
			{
				return value != 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RoundUpToPowerOf2(uint value)
		{
			value--;
			value |= value >> 1;
			value |= value >> 2;
			value |= value >> 4;
			value |= value >> 8;
			value |= value >> 16;
			return value + 1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RoundUpToPowerOf2(ulong value)
		{
			value--;
			value |= value >> 1;
			value |= value >> 2;
			value |= value >> 4;
			value |= value >> 8;
			value |= value >> 16;
			value |= value >> 32;
			return value + 1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static nuint RoundUpToPowerOf2(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return (nuint)RoundUpToPowerOf2((ulong)value);
			}
			return RoundUpToPowerOf2((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(uint value)
		{
			return BitOperations.LeadingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(ulong value)
		{
			return BitOperations.LeadingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return LeadingZeroCount((ulong)value);
			}
			return LeadingZeroCount((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(uint value)
		{
			return BitOperations.Log2(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(ulong value)
		{
			return BitOperations.Log2(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return Log2((ulong)value);
			}
			return Log2((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(uint value)
		{
			return BitOperations.PopCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(ulong value)
		{
			return BitOperations.PopCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return PopCount((ulong)value);
			}
			return PopCount((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(int value)
		{
			return BitOperations.TrailingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(uint value)
		{
			return BitOperations.TrailingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(long value)
		{
			return BitOperations.TrailingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(ulong value)
		{
			return BitOperations.TrailingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(nint value)
		{
			if (IntPtr.Size == 8)
			{
				return TrailingZeroCount((long)value);
			}
			return TrailingZeroCount((int)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return TrailingZeroCount((ulong)value);
			}
			return TrailingZeroCount((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RotateLeft(uint value, int offset)
		{
			return BitOperations.RotateLeft(value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RotateLeft(ulong value, int offset)
		{
			return BitOperations.RotateLeft(value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static nuint RotateLeft(nuint value, int offset)
		{
			if (IntPtr.Size == 8)
			{
				return (nuint)RotateLeft((ulong)value, offset);
			}
			return RotateLeft((uint)value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RotateRight(uint value, int offset)
		{
			return BitOperations.RotateRight(value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RotateRight(ulong value, int offset)
		{
			return BitOperations.RotateRight(value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static nuint RotateRight(nuint value, int offset)
		{
			if (IntPtr.Size == 8)
			{
				return (nuint)RotateRight((ulong)value, offset);
			}
			return RotateRight((uint)value, offset);
		}
	}
}
namespace System.IO
{
	public static class StreamExtensions
	{
		public static void CopyTo(this Stream src, Stream destination)
		{
			System.ThrowHelper.ThrowIfArgumentNull(src, "src");
			src.CopyTo(destination);
		}

		public static void CopyTo(this Stream src, Stream destination, int bufferSize)
		{
			System.ThrowHelper.ThrowIfArgumentNull(src, "src");
			src.CopyTo(destination, bufferSize);
		}
	}
}
namespace System.Collections
{
	internal static class HashHelpers
	{
		public const uint HashCollisionThreshold = 100u;

		public const int MaxPrimeArrayLength = 2147483587;

		public const int HashPrime = 101;

		private static readonly int[] s_primes = new int[72]
		{
			3, 7, 11, 17, 23, 29, 37, 47, 59, 71,
			89, 107, 131, 163, 197, 239, 293, 353, 431, 521,
			631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371,
			4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023,
			25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363,
			156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403,
			968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559,
			5999471, 7199369
		};

		public static bool IsPrime(int candidate)
		{
			if (((uint)candidate & (true ? 1u : 0u)) != 0)
			{
				int num = (int)Math.Sqrt(candidate);
				for (int i = 3; i <= num; i += 2)
				{
					if (candidate % i == 0)
					{
						return false;
					}
				}
				return true;
			}
			return candidate == 2;
		}

		public static int GetPrime(int min)
		{
			if (min < 0)
			{
				throw new ArgumentException("Prime minimum cannot be less than zero");
			}
			int[] array = s_primes;
			foreach (int num in array)
			{
				if (num >= min)
				{
					return num;
				}
			}
			for (int j = min | 1; j < int.MaxValue; j += 2)
			{
				if (IsPrime(j) && (j - 1) % 101 != 0)
				{
					return j;
				}
			}
			return min;
		}

		public static int ExpandPrime(int oldSize)
		{
			int num = 2 * oldSize;
			if ((uint)num > 2147483587u && 2147483587 > oldSize)
			{
				return 2147483587;
			}
			return GetPrime(num);
		}

		public static ulong GetFastModMultiplier(uint divisor)
		{
			return ulong.MaxValue / (ulong)divisor + 1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint FastMod(uint value, uint divisor, ulong multiplier)
		{
			return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32);
		}
	}
}
namespace System.Collections.Concurrent
{
	public static class ConcurrentExtensions
	{
		public static void Clear<T>(this ConcurrentBag<T> bag)
		{
			System.ThrowHelper.ThrowIfArgumentNull(bag, "bag");
			bag.Clear();
		}

		public static void Clear<T>(this ConcurrentQueue<T> queue)
		{
			System.ThrowHelper.ThrowIfArgumentNull(queue, "queue");
			queue.Clear();
		}

		public static TValue AddOrUpdate<TKey, TValue, TArg>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TKey, TArg, TValue> addValueFactory, Func<TKey, TValue, TArg, TValue> updateValueFactory, TArg factoryArgument) where TKey : notnull
		{
			System.ThrowHelper.ThrowIfArgumentNull(dict, "dict");
			return dict.AddOrUpdate(key, addValueFactory, updateValueFactory, factoryArgument);
		}

		public static TValue GetOrAdd<TKey, TValue, TArg>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument) where TKey : notnull
		{
			System.ThrowHelper.ThrowIfArgumentNull(dict, "dict");
			return dict.GetOrAdd(key, valueFactory, factoryArgument);
		}

		public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, KeyValuePair<TKey, TValue> item) where TKey : notnull
		{
			System.ThrowHelper.ThrowIfArgumentNull(dict, "dict");
			if (dict.TryRemove(item.Key, out TValue value))
			{
				if (EqualityComparer<TValue>.Default.Equals(item.Value, value))
				{
					return true;
				}
				dict.AddOrUpdate(item.Key, (TKey _) => value, (TKey _, TValue _) => value);
				return false;
			}
			return false;
		}
	}
}
namespace System.Runtime
{
	public struct DependentHandle : IDisposable
	{
		private sealed class DependentHolder : CriticalFinalizerObject
		{
			public GCHandle TargetHandle;

			private IntPtr dependent;

			public object? Dependent
			{
				get
				{
					return GCHandle.FromIntPtr(dependent).Target;
				}
				set
				{
					IntPtr value2 = GCHandle.ToIntPtr(GCHandle.Alloc(value, GCHandleType.Normal));
					IntPtr intPtr;
					do
					{
						intPtr = dependent;
					}
					while (Interlocked.CompareExchange(ref dependent, value2, intPtr) == intPtr);
					GCHandle.FromIntPtr(intPtr).Free();
				}
			}

			public DependentHolder(GCHandle targetHandle, object dependent)
			{
				TargetHandle = targetHandle;
				this.dependent = GCHandle.ToIntPtr(GCHandle.Alloc(dependent, GCHandleType.Normal));
			}

			~DependentHolder()
			{
				if (!AppDomain.CurrentDomain.IsFinalizingForUnload() && (!Environment.HasShutdownStarted && (TargetHandle.IsAllocated && TargetHandle.Target != null)))
				{
					GC.ReRegisterForFinalize(this);
				}
				else
				{
					GCHandle.FromIntPtr(dependent).Free();
				}
			}
		}

		private GCHandle dependentHandle;

		private volatile bool allocated;

		public bool IsAllocated => allocated;

		public object? Target
		{
			get
			{
				if (!allocated)
				{
					throw new InvalidOperationException();
				}
				return UnsafeGetTarget();
			}
			set
			{
				if (!allocated || value != null)
				{
					throw new InvalidOperationException();
				}
				UnsafeSetTargetToNull();
			}
		}

		public object? Dependent
		{
			get
			{
				if (!allocated)
				{
					throw new InvalidOperationException();
				}
				return UnsafeGetHolder()?.Dependent;
			}
			set
			{
				if (!allocated)
				{
					throw new InvalidOperationException();
				}
				UnsafeSetDependent(value);
			}
		}

		public (object? Target, object? Dependent) TargetAndDependent
		{
			get
			{
				if (!allocated)
				{
					throw new InvalidOperationException();
				}
				return (UnsafeGetTarget(), Dependent);
			}
		}

		public DependentHandle(object? target, object? dependent)
		{
			GCHandle targetHandle = GCHandle.Alloc(target, GCHandleType.WeakTrackResurrection);
			dependentHandle = AllocDepHolder(targetHandle, dependent);
			GC.KeepAlive(target);
			allocated = true;
		}

		private static GCHandle AllocDepHolder(GCHandle targetHandle, object? dependent)
		{
			return GCHandle.Alloc((dependent != null) ? new DependentHolder(targetHandle, dependent) : null, GCHandleType.WeakTrackResurrection);
		}

		private DependentHolder? UnsafeGetHolder()
		{
			return Unsafe.As<DependentHolder>(dependentHandle.Target);
		}

		internal object? UnsafeGetTarget()
		{
			return UnsafeGetHolder()?.TargetHandle.Target;
		}

		internal object? UnsafeGetTargetAndDependent(out object? dependent)
		{
			dependent = null;
			DependentHolder dependentHolder = UnsafeGetHolder();
			if (dependentHolder == null)
			{
				return null;
			}
			object target = dependentHolder.TargetHandle.Target;
			if (target == null)
			{
				return null;
			}
			dependent = dependentHolder.Dependent;
			return target;
		}

		internal void UnsafeSetTargetToNull()
		{
			Free();
		}

		internal void UnsafeSetDependent(object? value)
		{
			DependentHolder dependentHolder = UnsafeGetHolder();
			if (dependentHolder != null)
			{
				if (!dependentHolder.TargetHandle.IsAllocated)
				{
					Free();
				}
				else
				{
					dependentHolder.Dependent = value;
				}
			}
		}

		private void FreeDependentHandle()
		{
			if (allocated)
			{
				UnsafeGetHolder()?.TargetHandle.Free();
				dependentHandle.Free();
			}
			allocated = false;
		}

		private void Free()
		{
			FreeDependentHandle();
		}

		public void Dispose()
		{
			Free();
			allocated = false;
		}
	}
}
namespace System.Runtime.InteropServices
{
	public static class MarshalEx
	{
		private static readonly MethodInfo? Marshal_SetLastWin32Error_Meth = typeof(Marshal).GetMethod("SetLastPInvokeError", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(Marshal).GetMethod("SetLastWin32Error", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly Action<int>? Marshal_SetLastWin32Error = (((object)Marshal_SetLastWin32Error_Meth == null) ? null : ((Action<int>)Delegate.CreateDelegate(typeof(Action<int>), Marshal_SetLastWin32Error_Meth)));

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetLastPInvokeError()
		{
			return Marshal.GetLastWin32Error();
		}

		public static void SetLastPInvokeError(int error)
		{
			(Marshal_SetLastWin32Error ?? throw new PlatformNotSupportedException("Cannot set last P/Invoke error (no method Marshal.SetLastWin32Error or Marshal.SetLastPInvokeError)"))(error);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal static class IsExternalInit
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	internal interface ICWTEnumerable<T>
	{
		IEnumerable<T> SelfEnumerable { get; }

		IEnumerator<T> GetEnumerator();
	}
	internal sealed class CWTEnumerable<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable where TKey : class where TValue : class?
	{
		private readonly ConditionalWeakTable<TKey, TValue> cwt;

		public CWTEnumerable(ConditionalWeakTable<TKey, TValue> table)
		{
			cwt = table;
		}

		public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
		{
			return cwt.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public static class ConditionalWeakTableExtensions
	{
		public static IEnumerable<KeyValuePair<TKey, TValue>> AsEnumerable<TKey, TValue>(this ConditionalWeakTable<TKey, TValue> self) where TKey : class where TValue : class?
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, "self");
			if (self != null)
			{
				return self;
			}
			if (self is ICWTEnumerable<KeyValuePair<TKey, TValue>> iCWTEnumerable)
			{
				return iCWTEnumerable.SelfEnumerable;
			}
			return new CWTEnumerable<TKey, TValue>(self);
		}

		public static IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator<TKey, TValue>(this ConditionalWeakTable<TKey, TValue> self) where TKey : class where TValue : class?
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, "self");
			if (self != null)
			{
				return ((IEnumerable<KeyValuePair<TKey, TValue>>)self).GetEnumerator();
			}
			if (self is ICWTEnumerable<KeyValuePair<TKey, TValue>> iCWTEnumerable)
			{
				return iCWTEnumerable.GetEnumerator();
			}
			throw new PlatformNotSupportedException("This version of MonoMod.Backports was built targeting a version of the framework where ConditionalWeakTable is enumerable, but it isn't!");
		}

		public static void Clear<TKey, TValue>(this ConditionalWeakTable<TKey, TValue> self) where TKey : class where TValue : class?
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, "self");
			self.Clear();
		}

		public static bool TryAdd<TKey, TValue>(this ConditionalWeakTable<TKey, TValue> self, TKey key, TValue value) where TKey : class where TValue : class?
		{
			TValue value2 = value;
			System.ThrowHelper.ThrowIfArgumentNull(self, "self");
			bool didAdd = false;
			self.GetValue(key, delegate
			{
				didAdd = true;
				return value2;
			});
			return didAdd;
		}
	}
	[InterpolatedStringHandler]
	public ref struct DefaultInterpolatedStringHandler
	{
		private const int GuessedLengthPerHole = 11;

		private const int MinimumArrayPoolLength = 256;

		private readonly IFormatProvider? _provider;

		private char[]? _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		private readonly bool _hasCustomFormatter;

		internal ReadOnlySpan<char> Text => _chars.Slice(0, _pos);

		public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
		{
			_provider = null;
			_chars = (_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(GetDefaultLength(literalLength, formattedCount)));
			_pos = 0;
			_hasCustomFormatter = false;
		}

		public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider)
		{
			_provider = provider;
			_chars = (_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(GetDefaultLength(literalLength, formattedCount)));
			_pos = 0;
			_hasCustomFormatter = provider != null && HasCustomFormatter(provider);
		}

		public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span<char> initialBuffer)
		{
			_provider = provider;
			_chars = initialBuffer;
			_arrayToReturnToPool = null;
			_pos = 0;
			_hasCustomFormatter = provider != null && HasCustomFormatter(provider);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int GetDefaultLength(int literalLength, int formattedCount)
		{
			return Math.Max(256, literalLength + formattedCount * 11);
		}

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

		public string ToStringAndClear()
		{
			string result = Text.ToString();
			Clear();
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void Clear()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(DefaultInterpolatedStringHandler);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void AppendLiteral(string value)
		{
			if (value.Length == 1)
			{
				Span<char> chars = _chars;
				int pos = _pos;
				if ((uint)pos < (uint)chars.Length)
				{
					chars[pos] = value[0];
					_pos = pos + 1;
				}
				else
				{
					GrowThenCopyString(value);
				}
			}
			else if (value.Length == 2)
			{
				Span<char> chars2 = _chars;
				int pos2 = _pos;
				if ((uint)pos2 < chars2.Length - 1)
				{
					value.AsSpan().CopyTo(chars2.Slice(pos2));
					_pos = pos2 + 2;
				}
				else
				{
					GrowThenCopyString(value);
				}
			}
			else
			{
				AppendStringDirect(value);
			}
		}

		private void AppendStringDirect(string value)
		{
			if (value.AsSpan().TryCopyTo(_chars.Slice(_pos)))
			{
				_pos += value.Length;
			}
			else
			{
				GrowThenCopyString(value);
			}
		}

		public void AppendFormatted<T>(T value)
		{
			if (_hasCustomFormatter)
			{
				AppendCustomFormatter(value, null);
				return;
			}
			if (typeof(T) == typeof(IntPtr))
			{
				AppendFormatted(Unsafe.As<T, IntPtr>(ref value));
				return;
			}
			if (typeof(T) == typeof(UIntPtr))
			{
				AppendFormatted(Unsafe.As<T, UIntPtr>(ref value));
				return;
			}
			string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(null, _provider));
			if (text != null)
			{
				AppendStringDirect(text);
			}
		}

		public void AppendFormatted<T>(T value, string? format)
		{
			if (_hasCustomFormatter)
			{
				AppendCustomFormatter(value, format);
				return;
			}
			if (typeof(T) == typeof(IntPtr))
			{
				AppendFormatted(Unsafe.As<T, IntPtr>(ref value), format);
				return;
			}
			if (typeof(T) == typeof(UIntPtr))
			{
				AppendFormatted(Unsafe.As<T, UIntPtr>(ref value), format);
				return;
			}
			string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(format, _provider));
			if (text != null)
			{
				AppendStringDirect(text);
			}
		}

		public void AppendFormatted<T>(T value, int alignment)
		{
			int pos = _pos;
			AppendFormatted(value);
			if (alignment != 0)
			{
				AppendOrInsertAlignmentIfNeeded(pos, alignment);
			}
		}

		public void AppendFormatted<T>(T value, int alignment, string? format)
		{
			int pos = _pos;
			AppendFormatted(value, format);
			if (alignment != 0)
			{
				AppendOrInsertAlignmentIfNeeded(pos, alignment);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AppendFormatted(IntPtr value)
		{
			if (IntPtr.Size == 4)
			{
				AppendFormatted((int)value);
			}
			else
			{
				AppendFormatted((long)value);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AppendFormatted(IntPtr value, string? format)
		{
			if (IntPtr.Size == 4)
			{
				AppendFormatted((int)value, format);
			}
			else
			{
				AppendFormatted((long)value, format);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AppendFormatted(UIntPtr value)
		{
			if (UIntPtr.Size == 4)
			{
				AppendFormatted((uint)value);
			}
			else
			{
				AppendFormatted((ulong)value);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AppendFormatted(UIntPtr value, string? format)
		{
			if (UIntPtr.Size == 4)
			{
				AppendFormatted((uint)value, format);
			}
			else
			{
				AppendFormatted((ulong)value, format);
			}
		}

		public void AppendFormatted(ReadOnlySpan<char> value)
		{
			if (value.TryCopyTo(_chars.Slice(_pos)))
			{
				_pos += value.Length;
			}
			else
			{
				GrowThenCopySpan(value);
			}
		}

		public void AppendFormatted(ReadOnlySpan<char> value, int alignment = 0, string? format = null)
		{
			bool flag = false;
			if (alignment < 0)
			{
				flag = true;
				alignment = -alignment;
			}
			int num = alignment - value.Length;
			if (num <= 0)
			{
				AppendFormatted(value);
				return;
			}
			EnsureCapacityForAdditionalChars(value.Length + num);
			if (flag)
			{
				value.CopyTo(_chars.Slice(_pos));
				_pos += value.Length;
				_chars.Slice(_pos, num).Fill(' ');
				_pos += num;
			}
			else
			{
				_chars.Slice(_pos, num).Fill(' ');
				_pos += num;
				value.CopyTo(_chars.Slice(_pos));
				_pos += value.Length;
			}
		}

		public void AppendFormatted(string? value)
		{
			if (!_hasCustomFormatter && value != null && value.AsSpan().TryCopyTo(_chars.Slice(_pos)))
			{
				_pos += value.Length;
			}
			else
			{
				AppendFormattedSlow(value);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void AppendFormattedSlow(string? value)
		{
			if (_hasCustomFormatter)
			{
				AppendCustomFormatter(value, null);
			}
			else if (value != null)
			{
				EnsureCapacityForAdditionalChars(value.Length);
				value.AsSpan().CopyTo(_chars.Slice(_pos));
				_pos += value.Length;
			}
		}

		public void AppendFormatted(string? value, int alignment = 0, string? format = null)
		{
			this.AppendFormatted<string>(value, alignment, format);
		}

		public void AppendFormatted(object? value, int alignment = 0, string? format = null)
		{
			this.AppendFormatted<object>(value, alignment, format);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static bool HasCustomFormatter(IFormatProvider provider)
		{
			if (provider.GetType() != typeof(CultureInfo))
			{
				return provider.GetFormat(typeof(ICustomFormatter)) != null;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void AppendCustomFormatter<T>(T value, string? format)
		{
			ICustomFormatter customFormatter = (ICustomFormatter)_provider.GetFormat(typeof(ICustomFormatter));
			if (customFormatter != null)
			{
				string text = customFormatter.Format(format, value, _provider);
				if (text != null)
				{
					AppendStringDirect(text);
				}
			}
		}

		private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)
		{
			int num = _pos - startingPos;
			bool flag = false;
			if (alignment < 0)
			{
				flag = true;
				alignment = -alignment;
			}
			int num2 = alignment - num;
			if (num2 > 0)
			{
				EnsureCapacityForAdditionalChars(num2);
				if (flag)
				{
					_chars.Slice(_pos, num2).Fill(' ');
				}
				else
				{
					_chars.Slice(startingPos, num).CopyTo(_chars.Slice(startingPos + num2));
					_chars.Slice(startingPos, num2).Fill(' ');
				}
				_pos += num2;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void EnsureCapacityForAdditionalChars(int additionalChars)
		{
			if (_chars.Length - _pos < additionalChars)
			{
				Grow(additionalChars);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowThenCopyString(string value)
		{
			Grow(value.Length);
			value.AsSpan().CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowThenCopySpan(ReadOnlySpan<char> value)
		{
			Grow(value.Length);
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalChars)
		{
			GrowCore((uint)(_pos + additionalChars));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow()
		{
			GrowCore((uint)(_chars.Length + 1));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void GrowCore(uint requiredMinCapacity)
		{
			int minimumLength = (int)MathEx.Clamp(Math.Max(requiredMinCapacity, Math.Min((uint)(_chars.Length * 2), uint.MaxValue)), 256u, 2147483647u);
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
	public sealed class DisableRuntimeMarshallingAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
	public sealed class InterpolatedStringHandlerAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public sealed class InterpolatedStringHandlerArgumentAttribute : Attribute
	{
		public string[] Arguments { get; }

		public InterpolatedStringHandlerArgumentAttribute(string argument)
		{
			Arguments = new string[1] { argument };
		}

		public InterpolatedStringHandlerArgumentAttribute(params string[] arguments)
		{
			Arguments = arguments;
		}
	}
	internal interface ITuple
	{
		int Length { get; }

		object? this[int index] { get; }
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	public sealed class ModuleInitializerAttribute : Attribute
	{
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
	public static class ExtraDynamicallyAccessedMemberTypes
	{
		public const DynamicallyAccessedMemberTypes Interfaces = (DynamicallyAccessedMemberTypes)8192;
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	public sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	public enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public sealed class UnscopedRefAttribute : Attribute
	{
	}
}

BepInEx/plugins/WKRando/MonoMod.ILHelpers.dll

Decompiled 3 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;
using MonoMod.Backports.ILHelpers;

[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCopyright("Copyright 2024 0x0ade, DaNike")]
[assembly: CLSCompliant(false)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyTitle("MonoMod.ILHelpers")]
[assembly: AssemblyCompany("0x0ade, DaNike")]
[assembly: AssemblyDescription("Package Description")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: TypeForwardedTo(typeof(UnsafeRaw))]
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] A_0)
		{
			TransformFlags = A_0;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte A_0)
		{
			Flag = A_0;
		}
	}
}
namespace MonoMod
{
	public static class ILHelpers
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static T TailCallDelegatePtr<T>(IntPtr source)
		{
			return ((delegate*<T>)source)();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static T TailCallFunc<T>(Func<T> func)
		{
			return func();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static ref T ObjectAsRef<T>(object obj)
		{
			fixed (object obj2 = obj)
			{
				T** ptr = (T**)(&obj2);
				return ref *(*ptr);
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	public static class Unsafe
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T Read<T>(void* source)
		{
			return Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T ReadUnaligned<T>(void* source)
		{
			return Unsafe.ReadUnaligned<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T ReadUnaligned<T>(ref byte source)
		{
			return Unsafe.ReadUnaligned<T>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Write<T>(void* destination, T value)
		{
			Unsafe.Write(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void WriteUnaligned<T>(void* destination, T value)
		{
			Unsafe.WriteUnaligned(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void WriteUnaligned<T>(ref byte destination, T value)
		{
			Unsafe.WriteUnaligned(ref destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(void* destination, ref T source)
		{
			Unsafe.Write(destination, source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(ref T destination, void* source)
		{
			destination = Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* AsPointer<T>(ref T value)
		{
			return Unsafe.AsPointer(ref value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void SkipInit<T>(out T value)
		{
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static int SizeOf<T>()
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlock(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlock(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlock(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T As<T>(object o) where T : class
		{
			return (T)o;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T AsRef<T>(void* source)
		{
			return ref *(T*)source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AsRef<T>(in T source)
		{
			return ref source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref TTo As<TFrom, TTo>(ref TFrom source)
		{
			return ref Unsafe.As<TFrom, TTo>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Unbox<T>(object box) where T : struct
		{
			return ref (T)box;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Add<T>(void* source, int elementOffset)
		{
			return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, nint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, nuint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, nint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, nuint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Subtract<T>(void* source, int elementOffset)
		{
			return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, nint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, nuint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, nint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, nuint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static nint ByteOffset<T>(ref T origin, ref T target)
		{
			return Unsafe.ByteOffset(target: ref target, origin: ref origin);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool AreSame<T>(ref T left, ref T right)
		{
			return Unsafe.AreSame(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressGreaterThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressLessThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressLessThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static bool IsNullRef<T>(ref T source)
		{
			return Unsafe.AsPointer(ref source) == null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T NullRef<T>()
		{
			return ref *(T*)null;
		}
	}
}

BepInEx/plugins/WKRando/WKRando.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading.Tasks;
using Archipelago.MultiClient.Net;
using Archipelago.MultiClient.Net.BounceFeatures.DeathLink;
using Archipelago.MultiClient.Net.Enums;
using Archipelago.MultiClient.Net.Exceptions;
using Archipelago.MultiClient.Net.Helpers;
using Archipelago.MultiClient.Net.MessageLog.Messages;
using Archipelago.MultiClient.Net.Models;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using HarmonyLib.Tools;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Linq;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("WKRando")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+2522077aa1a7568571b193ab8b0be4ef927e6f12")]
[assembly: AssemblyProduct("My first plugin")]
[assembly: AssemblyTitle("WKRando")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[CompilerGenerated]
internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>
{
	int ICollection.Count => _items.Length;

	bool ICollection.IsSynchronized => false;

	object ICollection.SyncRoot => this;

	object IList.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	bool IList.IsFixedSize => true;

	bool IList.IsReadOnly => true;

	int IReadOnlyCollection<T>.Count => _items.Length;

	T IReadOnlyList<T>.this[int index] => _items[index];

	int ICollection<T>.Count => _items.Length;

	bool ICollection<T>.IsReadOnly => true;

	T IList<T>.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	public <>z__ReadOnlyArray(T[] items)
	{
		_items = items;
	}

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

	void ICollection.CopyTo(Array array, int index)
	{
		((ICollection)_items).CopyTo(array, index);
	}

	int IList.Add(object value)
	{
		throw new NotSupportedException();
	}

	void IList.Clear()
	{
		throw new NotSupportedException();
	}

	bool IList.Contains(object value)
	{
		return ((IList)_items).Contains(value);
	}

	int IList.IndexOf(object value)
	{
		return ((IList)_items).IndexOf(value);
	}

	void IList.Insert(int index, object value)
	{
		throw new NotSupportedException();
	}

	void IList.Remove(object value)
	{
		throw new NotSupportedException();
	}

	void IList.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}

	IEnumerator<T> IEnumerable<T>.GetEnumerator()
	{
		return ((IEnumerable<T>)_items).GetEnumerator();
	}

	void ICollection<T>.Add(T item)
	{
		throw new NotSupportedException();
	}

	void ICollection<T>.Clear()
	{
		throw new NotSupportedException();
	}

	bool ICollection<T>.Contains(T item)
	{
		return ((ICollection<T>)_items).Contains(item);
	}

	void ICollection<T>.CopyTo(T[] array, int arrayIndex)
	{
		((ICollection<T>)_items).CopyTo(array, arrayIndex);
	}

	bool ICollection<T>.Remove(T item)
	{
		throw new NotSupportedException();
	}

	int IList<T>.IndexOf(T item)
	{
		return ((IList<T>)_items).IndexOf(item);
	}

	void IList<T>.Insert(int index, T item)
	{
		throw new NotSupportedException();
	}

	void IList<T>.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace WKRando
{
	public class APItems
	{
		public static int ProgressiveRegions;

		public static int ProgressivePerkUnlocks;

		public static int TargetAPDebuffCount = 10;

		public static int TrinketSlots = 3;

		public static int TotalRoachesReceived;

		public static int TotalCreditsReceived;

		public static Dictionary<string, Dictionary<string, bool>> FacilityDict = new Dictionary<string, Dictionary<string, bool>>
		{
			["GLOBAL"] = new Dictionary<string, bool>
			{
				["UPG_Global_Bazaar_I2"] = false,
				["UPG_Global_PerkRefresh"] = false
			},
			["CAMPAIGN_INTERLUDE_01"] = new Dictionary<string, bool>
			{
				["UPG_Recycler"] = false,
				["UPG_ItemLocker_01"] = false,
				["UPG_ItemLocker_02"] = false,
				["UPG_SectorMaintenance"] = false,
				["UPG_Ration_T1"] = false,
				["UPG_Ration_T2"] = false,
				["UPG_ATM"] = false,
				["UPG_Vendor_T1_01"] = false,
				["UPG_Vendor_T2_01"] = false
			},
			["CAMPAIGN_INTERLUDE_02"] = new Dictionary<string, bool>
			{
				["UPG_Recycler"] = false,
				["UPG_ItemLocker_01"] = false,
				["UPG_ItemLocker_02"] = false,
				["UPG_Ration_T1"] = false,
				["UPG_Ration_T2"] = false,
				["UPG_Vendor_T1_01"] = false,
				["UPG_Vendor_T2_01"] = false
			},
			["CAMPAIGN_INTERLUDE_03"] = new Dictionary<string, bool>
			{
				["UPG_Recycler"] = false,
				["UPG_ItemLocker_01"] = false,
				["UPG_ItemLocker_02"] = false,
				["UPG_ATM"] = false,
				["UPG_Vendor_T2_01"] = false,
				["UPG_Rho_Altar_Repair"] = false
			},
			["CAMPAIGN_INTERLUDE_04"] = new Dictionary<string, bool>
			{
				["UPG_Recycler"] = false,
				["UPG_ItemLocker_01"] = false,
				["UPG_ItemLocker_02"] = false,
				["UPG_Ration_T1"] = false,
				["UPG_Ration_T2"] = false,
				["UPG_Wine_T1"] = false,
				["UPG_ATM"] = false,
				["UPG_Vendor_T2_01"] = false
			}
		};

		public static List<long> SentLocations = new List<long>();

		public static Dictionary<long, string> APtoFullFacilityUpgrade = new Dictionary<long, string>
		{
			[178323456L] = "GLOBAL UPG_Global_Bazaar_I2",
			[178323457L] = "GLOBAL UPG_Global_StartingRoaches_T1",
			[178323458L] = "GLOBAL UPG_Global_StartingRoaches_T2",
			[178323459L] = "GLOBAL UPG_Global_StartingRoaches_T3",
			[178323460L] = "GLOBAL UPG_Global_Buddy_T1",
			[178323461L] = "GLOBAL UPG_Global_Pouch_T1",
			[178323462L] = "GLOBAL UPG_Global_OrnamentalHammer",
			[178323463L] = "GLOBAL UPG_Global_Cosmetic_WorkGloves",
			[178323464L] = "GLOBAL UPG_Global_Cosmetic_SpecialtyGloves",
			[178323465L] = "GLOBAL UPG_Global_PerkRefresh",
			[178327552L] = "CAMPAIGN_INTERLUDE_01 UPG_Recycler",
			[178327553L] = "CAMPAIGN_INTERLUDE_01 UPG_SectorMaintenance",
			[178327554L] = "CAMPAIGN_INTERLUDE_01 UPG_ItemLocker_01",
			[178327555L] = "CAMPAIGN_INTERLUDE_01 UPG_ItemLocker_02",
			[178327556L] = "CAMPAIGN_INTERLUDE_01 UPG_Ration_T1",
			[178327557L] = "CAMPAIGN_INTERLUDE_01 UPG_Ration_T2",
			[178327558L] = "CAMPAIGN_INTERLUDE_01 UPG_ATM",
			[178327559L] = "CAMPAIGN_INTERLUDE_01 UPG_Vendor_T1_01",
			[178327560L] = "CAMPAIGN_INTERLUDE_01 UPG_Vendor_T2_02",
			[178331648L] = "CAMPAIGN_INTERLUDE_02 UPG_Recycler",
			[178331649L] = "CAMPAIGN_INTERLUDE_02 UPG_ItemLocker_01",
			[178331650L] = "CAMPAIGN_INTERLUDE_02 UPG_ItemLocker_02",
			[178331651L] = "CAMPAIGN_INTERLUDE_02 UPG_Ration_T1",
			[178331652L] = "CAMPAIGN_INTERLUDE_02 UPG_Ration_T2",
			[178331653L] = "CAMPAIGN_INTERLUDE_02 UPG_Vendor_T1_01",
			[178331654L] = "CAMPAIGN_INTERLUDE_02 UPG_Vendor_T2_01",
			[178335744L] = "CAMPAIGN_INTERLUDE_03 UPG_Recycler",
			[178335745L] = "CAMPAIGN_INTERLUDE_03 UPG_ItemLocker_01",
			[178335746L] = "CAMPAIGN_INTERLUDE_03 UPG_ItemLocker_02",
			[178335747L] = "CAMPAIGN_INTERLUDE_03 UPG_ATM",
			[178335748L] = "CAMPAIGN_INTERLUDE_03 UPG_Vendor_T2_01",
			[178335749L] = "CAMPAIGN_INTERLUDE_03 UPG_Rho_Altar_Repair",
			[178339840L] = "CAMPAIGN_INTERLUDE_04 UPG_Recycler",
			[178339841L] = "CAMPAIGN_INTERLUDE_04 UPG_ItemLocker_01",
			[178339842L] = "CAMPAIGN_INTERLUDE_04 UPG_ItemLocker_02",
			[178339843L] = "CAMPAIGN_INTERLUDE_04 UPG_Ration_T1",
			[178339844L] = "CAMPAIGN_INTERLUDE_04 UPG_Ration_T2",
			[178339845L] = "CAMPAIGN_INTERLUDE_04 UPG_Wine_T1",
			[178339846L] = "CAMPAIGN_INTERLUDE_04 UPG_ATM",
			[178339847L] = "CAMPAIGN_INTERLUDE_04 UPG_Vendor_T2_01"
		};

		public static Dictionary<string, long> FullFacilityUpgradetoAP = new Dictionary<string, long>
		{
			["GLOBAL UPG_Global_Bazaar_I2"] = 178323456L,
			["GLOBAL UPG_Global_StartingRoaches_T1"] = 178323457L,
			["GLOBAL UPG_Global_StartingRoaches_T2"] = 178323458L,
			["GLOBAL UPG_Global_StartingRoaches_T3"] = 178323459L,
			["GLOBAL UPG_Global_Buddy_T1"] = 178323460L,
			["GLOBAL UPG_Global_Pouch_T1"] = 178323461L,
			["GLOBAL UPG_Global_OrnamentalHammer"] = 178323462L,
			["GLOBAL UPG_Global_Cosmetic_WorkGloves"] = 178323463L,
			["GLOBAL UPG_Global_Cosmetic_SpecialtyGloves"] = 178323464L,
			["GLOBAL UPG_Global_PerkRefresh"] = 178323465L,
			["CAMPAIGN_INTERLUDE_01 UPG_Recycler"] = 178327552L,
			["CAMPAIGN_INTERLUDE_01 UPG_SectorMaintenance"] = 178327553L,
			["CAMPAIGN_INTERLUDE_01 UPG_ItemLocker_01"] = 178327554L,
			["CAMPAIGN_INTERLUDE_01 UPG_ItemLocker_02"] = 178327555L,
			["CAMPAIGN_INTERLUDE_01 UPG_Ration_T1"] = 178327556L,
			["CAMPAIGN_INTERLUDE_01 UPG_Ration_T2"] = 178327557L,
			["CAMPAIGN_INTERLUDE_01 UPG_ATM"] = 178327558L,
			["CAMPAIGN_INTERLUDE_01 UPG_Vendor_T1_01"] = 178327559L,
			["CAMPAIGN_INTERLUDE_01 UPG_Vendor_T2_01"] = 178327560L,
			["CAMPAIGN_INTERLUDE_02 UPG_Recycler"] = 178331648L,
			["CAMPAIGN_INTERLUDE_02 UPG_ItemLocker_01"] = 178331649L,
			["CAMPAIGN_INTERLUDE_02 UPG_ItemLocker_02"] = 178331650L,
			["CAMPAIGN_INTERLUDE_02 UPG_Ration_T1"] = 178331651L,
			["CAMPAIGN_INTERLUDE_02 UPG_Ration_T2"] = 178331652L,
			["CAMPAIGN_INTERLUDE_02 UPG_Vendor_T1_01"] = 178331653L,
			["CAMPAIGN_INTERLUDE_02 UPG_Vendor_T2_01"] = 178331654L,
			["CAMPAIGN_INTERLUDE_03 UPG_Recycler"] = 178335744L,
			["CAMPAIGN_INTERLUDE_03 UPG_ItemLocker_01"] = 178335745L,
			["CAMPAIGN_INTERLUDE_03 UPG_ItemLocker_02"] = 178335746L,
			["CAMPAIGN_INTERLUDE_03 UPG_ATM"] = 178335747L,
			["CAMPAIGN_INTERLUDE_03 UPG_Vendor_T2_01"] = 178335748L,
			["CAMPAIGN_INTERLUDE_03 UPG_Rho_Altar_Repair"] = 178335749L,
			["CAMPAIGN_INTERLUDE_04 UPG_Recycler"] = 178339840L,
			["CAMPAIGN_INTERLUDE_04 UPG_ItemLocker_01"] = 178339841L,
			["CAMPAIGN_INTERLUDE_04 UPG_ItemLocker_02"] = 178339842L,
			["CAMPAIGN_INTERLUDE_04 UPG_Ration_T1"] = 178339843L,
			["CAMPAIGN_INTERLUDE_04 UPG_Ration_T2"] = 178339844L,
			["CAMPAIGN_INTERLUDE_04 UPG_Wine_T1"] = 178339845L,
			["CAMPAIGN_INTERLUDE_04 UPG_ATM"] = 178339846L,
			["CAMPAIGN_INTERLUDE_04 UPG_Vendor_T2_01"] = 178339847L
		};

		public static Dictionary<string, long> RoomNameToAP = new Dictionary<string, long>
		{
			["M1_Silos_Storage_01"] = 179372032L,
			["M1_Silos_Storage_03"] = 179372033L,
			["M1_Silos_Storage_06"] = 179372034L,
			["M1_Silos_Storage_09"] = 179372035L,
			["M1_Silos_Storage_10"] = 179372036L,
			["M1_Silos_Storage_15"] = 179372037L,
			["M1_Silos_Air_02"] = 179372038L,
			["M1_Silos_Air_03"] = 179372039L,
			["M1_Silos_Air_04"] = 179372040L,
			["M1_Silos_Air_08"] = 179372041L,
			["M1_Silos_Broken_01"] = 179372042L,
			["M1_Silos_Broken_04"] = 179372043L,
			["M1_Silos_Broken_08"] = 179372044L,
			["M1_Silos_Broken_09"] = 179372045L,
			["M1_Silos_Broken_10"] = 179372046L,
			["M1_Silos_Storage_04"] = 179372288L,
			["M1_Silos_Storage_11"] = 179372289L,
			["M1_Silos_Storage_12"] = 179372290L,
			["M1_Silos_Storage_02"] = 179372544L,
			["M1_Silos_Storage_08"] = 179372545L,
			["M1_Silos_Storage_16"] = 179372546L,
			["M1_Silos_Air_05"] = 179372547L,
			["M1_Silos_Air_06"] = 179372548L,
			["M1_Silos_Broken_03"] = 179372549L,
			["M1_Silos_Broken_05"] = 179372550L,
			["M1_Silos_Storage_05"] = 179372800L,
			["M1_Silos_Storage_07"] = 179372801L,
			["M1_Silos_Air_01"] = 179372802L,
			["M1_Silos_Air_09"] = 179372803L,
			["M1_Silos_Broken_02"] = 179372804L,
			["M1_Silos_Broken_06"] = 179372805L,
			["M1_Silos_Storage_13"] = 179373056L,
			["M1_Silos_Storage_14"] = 179373057L,
			["M1_Silos_Air_07"] = 179373058L,
			["M1_Silos_Air_10"] = 179373059L,
			["M1_Silos_Broken_07"] = 179373060L,
			["M1_Silos_Storage_17"] = 179373312L,
			["M1_Silos_Air_11"] = 179373313L,
			["M1_Silos_Broken_11"] = 179373314L,
			["M2_Pipeworks_Drainage_01"] = 179437568L,
			["M2_Pipeworks_Drainage_02"] = 179437569L,
			["M2_Pipeworks_Drainage_05"] = 179437570L,
			["M2_Pipeworks_Drainage_07"] = 179437571L,
			["M2_Pipeworks_Drainage_08"] = 179437572L,
			["M2_Pipeworks_Drainage_09"] = 179437573L,
			["M2_Pipeworks_Drainage_10"] = 179437574L,
			["M2_Pipeworks_Waste_02"] = 179437824L,
			["M2_Pipeworks_Waste_04"] = 179437825L,
			["M2_Pipeworks_Waste_05"] = 179437826L,
			["M2_Pipeworks_Organ_02"] = 179438080L,
			["M2_Pipeworks_Organ_05"] = 179438081L,
			["M2_Pipeworks_Organ_06"] = 179438082L,
			["M2_Pipeworks_Organ_07"] = 179438083L,
			["M2_Pipeworks_Drainage_03"] = 179441664L,
			["M2_Pipeworks_Drainage_04"] = 179441665L,
			["M2_Pipeworks_Waste_01"] = 179441920L,
			["M2_Pipeworks_Organ_01"] = 179442176L,
			["M2_Pipeworks_Organ_03"] = 179442177L,
			["M2_Pipeworks_Drainage_06"] = 179445760L,
			["M2_Pipeworks_Waste_03"] = 179446016L,
			["M2_Pipeworks_Organ_04"] = 179446272L,
			["M2_Pipeworks_Organ_08"] = 179446273L,
			["M2_Pipeworks_Organ_09"] = 179450368L,
			["M3_Habitation_Shaft_01"] = 179503104L,
			["M3_Habitation_Shaft_02"] = 179503105L,
			["M3_Habitation_Shaft_03"] = 179503106L,
			["M3_Habitation_Shaft_04"] = 179503107L,
			["M3_Habitation_Shaft_05"] = 179503108L,
			["M3_Habitation_Shaft_06"] = 179503109L,
			["M3_Habitation_Shaft_To_Pier"] = 179503110L,
			["M3_Habitation_Pier_01"] = 179503360L,
			["M3_Habitation_Pier_02"] = 179503361L,
			["M3_Habitation_Lab_Lobby"] = 179503616L,
			["M3_Habitation_Lab_01"] = 179503617L,
			["M3_Habitation_Lab_02"] = 179503618L,
			["M3_Habitation_Lab_03"] = 179503619L,
			["M3_Habitation_Lab_04"] = 179503620L,
			["M3_Habitation_Lab_Ending"] = 179503621L,
			["M3_Habitation_Shaft_07"] = 179507200L,
			["M3_Habitation_Pier_03"] = 179507456L,
			["M3_Habitation_Pier_04"] = 179507457L,
			["M3_Habitation_Lab_05"] = 179507712L,
			["M3_Habitation_Lab_06"] = 179507713L,
			["M3_Habitation_Lab_07"] = 179507714L,
			["M3_Habitation_Lab_08"] = 179507715L,
			["M4_Abyss_Intro_01"] = 179568640L,
			["M4_Abyss_Outro_01"] = 179568641L,
			["M4_Abyss_Transit_01"] = 179568897L,
			["M4_Abyss_Transit_02"] = 179568898L,
			["M4_Abyss_Transit_03"] = 179568899L,
			["M4_Abyss_Transit_04"] = 179568900L,
			["M4_Abyss_Transit_05"] = 179568901L,
			["M4_Abyss_Transit_06"] = 179568902L,
			["M4_Abyss_Handle_01"] = 179569152L,
			["M4_Abyss_Garden_01"] = 179569408L,
			["M4_Abyss_Garden_02"] = 179569409L,
			["M4_Abyss_Garden_03"] = 179569410L,
			["M4_Abyss_Garden_04"] = 179569411L,
			["M4_Abyss_Handle_02"] = 179569664L,
			["M5_Nest_Infested_01"] = 179634176L,
			["M5_Nest_Infested_02"] = 179634177L,
			["M5_Nest_Infested_03"] = 179634178L,
			["M5_Nest_Infested_04"] = 179634179L,
			["M5_Nest_Infested_05"] = 179634180L,
			["M5_Nest_Infested_HunterIntro_01"] = 179634181L,
			["M5_Nest_Infested_Chase_01"] = 179634182L,
			["M5_Nest_Infested_Chase_02"] = 179634183L,
			["M5_Nest_Trough_01"] = 179634432L,
			["M5_Nest_Trough_02"] = 179634433L,
			["M5_Nest_Trough_03"] = 179634434L,
			["M5_Nest_Trough_04"] = 179634435L,
			["M5_Nest_Trough_05"] = 179634436L,
			["M5_Nest_Trough_06"] = 179634437L,
			["M5_Nest_Trough_07"] = 179634438L,
			["M5_Nest_Trough_08"] = 179634439L,
			["M5_Nest_Trough_Ending_01"] = 179634440L,
			["M5_Nest_HotZone_Intro_01"] = 179634688L,
			["M5_Nest_HotZone_Outro_01"] = 179634689L,
			["M5_Nest_HotZone_01"] = 179634690L,
			["M5_Nest_HotZone_02"] = 179634691L,
			["M5_Nest_HotZone_03"] = 179634692L,
			["M5_Nest_HotZone_04"] = 179634693L,
			["S1_TangledSink_Intro_01"] = 179699712L,
			["S1_TangledSink_01"] = 179699713L,
			["S1_TangledSink_02"] = 179699714L,
			["S1_TangledSink_03"] = 179699715L,
			["S1_TangledSink_04"] = 179699716L,
			["S1_GarbageChute_Start_01"] = 179765248L,
			["S1_GarbageChute_01"] = 179765249L,
			["S1_GarbageChute_02"] = 179765250L,
			["S1_GarbageChute_03"] = 179765251L,
			["S1_GarbageChute_04"] = 179765252L,
			["S1_GarbageChute_05"] = 179765253L,
			["S1_GarbageChute_06"] = 179765254L,
			["S1_GarbageChute_End_01"] = 179765255L,
			["T1_Foundations_Items_01"] = 179830784L,
			["T1_Foundations_Items_02"] = 179830785L,
			["T1_Foundations_Items_03"] = 179830786L,
			["T1_Foundations_Items_04"] = 179830787L,
			["T1_Foundations_Items_05"] = 179830788L,
			["T1_Foundations_Low_01"] = 179830789L,
			["T1_Foundations_Low_02"] = 179830790L,
			["T1_Foundations_Low_03"] = 179830791L,
			["T1_Foundations_Low_04"] = 179830792L,
			["T1_Foundations_Low_05"] = 179830793L,
			["T1_Foundations_Low_06"] = 179830794L,
			["T1_Foundations_Mastery_01"] = 179830795L,
			["T1_Foundations_Mastery_02"] = 179830796L
		};

		public static Dictionary<string, bool> ProgressionUnlocks = new Dictionary<string, bool>
		{
			["binding_abyss"] = false,
			["binding_core"] = false,
			["binding_habitation"] = false,
			["binding_nest"] = false,
			["binding_roach"] = false,
			["challenge_advancedcourse"] = false,
			["challenge_boostcourse"] = false,
			["challenge_commsarray"] = false,
			["challenge_fracturedterritory"] = false,
			["challenge_roachrun"] = false,
			["challenge_shutteredrift"] = false,
			["cosmetic_bloodied"] = false,
			["cosmetic_crowbar"] = false,
			["cosmetic_denizen"] = false,
			["cosmetic_experienced"] = false,
			["cosmetic_glove_leather"] = false,
			["cosmetic_glove_winter"] = false,
			["cosmetic_glove_wraps"] = false,
			["cosmetic_hammer_alternate"] = false,
			["cosmetic_hammer_mallet"] = false,
			["cosmetic_hammer_mallet_christmas"] = false,
			["cosmetic_hammer_pipe"] = false,
			["cosmetic_hammer_wrench"] = false,
			["cosmetic_hand_celestial"] = false,
			["cosmetic_hand_stone"] = false,
			["cosmetic_hand_sunspot"] = false,
			["cosmetic_infested"] = false,
			["cosmetic_inverted"] = false,
			["cosmetic_maintenanceglove_new"] = false,
			["cosmetic_maintenanceglove_worn"] = false,
			["cosmetic_marionette"] = false,
			["cosmetic_hammer_ornamental"] = false,
			["cosmetic_outline"] = false,
			["cosmetic_roach"] = false,
			["cosmetic_scribble"] = false,
			["cosmetic_skeletontattoo"] = false,
			["cosmetic_streaked"] = false,
			["cosmetic_xray"] = false,
			["r_hardmode"] = false,
			["r_10kendless"] = false,
			["r_competitive"] = false,
			["perk_mother"] = false,
			["perk_t1"] = false,
			["perk_t2"] = false,
			["perk_t3"] = false,
			["perk_t4"] = false,
			["perk_t5"] = false,
			["perk_u_adoption"] = false,
			["perk_u_delta"] = false,
			["perk_u_t1"] = false,
			["perk_u_t2"] = false,
			["perk_u_t3"] = false,
			["r_abyss_t1"] = false,
			["r_deepstorage_t1"] = false,
			["r_habitation_t1"] = false,
			["r_pipeworks_t1"] = false,
			["r_pipeworks_t2"] = false,
			["r_pipeworks_t3"] = false,
			["r_shortcut_expulsionchute"] = false,
			["r_shortcut_tangledsink"] = false,
			["r_silos_t1"] = false,
			["r_silos_t2"] = false,
			["r_silos_t3"] = false,
			["r_silos_t4"] = false,
			["trinket_calmingbuddy"] = false,
			["trinket_deltalabs"] = false,
			["trinket_helmet"] = false,
			["trinket_interlude01"] = false,
			["trinket_interlude02"] = false,
			["trinket_interlude03"] = false,
			["trinket_interlude04"] = false,
			["trinket_pouch"] = false,
			["trinket_recycler"] = false,
			["trinket_deepstorage"] = false,
			["vendor_item_autopiton"] = false,
			["vendor_item_blinkeye"] = false,
			["vendor_item_explosiverebar"] = false,
			["vendor_item_flaregun"] = false,
			["vendor_item_flares"] = false,
			["vendor_item_foodbar"] = false,
			["vendor_item_10mm_ammo"] = false,
			["vendor_item_injector"] = false,
			["vendor_item_pills"] = false,
			["vendor_item_grub"] = false
		};

		public static Dictionary<string, long> ProgressionUnlocksToAPID = new Dictionary<string, long>
		{
			["challenge_advancedcourse"] = 180355072L,
			["challenge_boostcourse"] = 180355073L,
			["challenge_commsarray"] = 180355074L,
			["challenge_fracturedterritory"] = 180355075L,
			["challenge_roachrun"] = 180355076L,
			["challenge_shutteredrift"] = 180355077L,
			["perk_mother"] = 180355328L,
			["perk_t1"] = 180355329L,
			["perk_t2"] = 180355330L,
			["perk_t3"] = 180355331L,
			["perk_t4"] = 180355332L,
			["perk_t5"] = 180355333L,
			["perk_u_adoption"] = 180355334L,
			["perk_u_delta"] = 180355335L,
			["perk_u_t1"] = 180355336L,
			["perk_u_t2"] = 180355337L,
			["perk_u_t3"] = 180355338L,
			["r_abyss_t1"] = 180355584L,
			["r_habitation_t1"] = 180355585L,
			["r_pipeworks_t1"] = 180355586L,
			["r_pipeworks_t2"] = 180355587L,
			["r_pipeworks_t3"] = 180355588L,
			["r_shortcut_expulsionchute"] = 180355589L,
			["r_shortcut_tangledsink"] = 180355590L,
			["r_silos_t1"] = 180355591L,
			["r_silos_t2"] = 180355592L,
			["r_silos_t3"] = 180355593L,
			["r_silos_t4"] = 180355594L,
			["r_deepstorage_t1"] = 180355595L,
			["trinket_deltalabs"] = 180355840L,
			["trinket_helmet"] = 180355841L,
			["trinket_interlude02"] = 180355842L,
			["trinket_interlude03"] = 180355843L,
			["trinket_interlude04"] = 180355844L,
			["trinket_recycler"] = 180355845L,
			["vendor_item_autopiton"] = 180356096L,
			["vendor_item_blinkeye"] = 180356097L,
			["vendor_item_explosiverebar"] = 180356098L,
			["vendor_item_flaregun"] = 180356099L,
			["vendor_item_flares"] = 180356100L,
			["vendor_item_foodbar"] = 180356101L,
			["vendor_item_10mm_ammo"] = 180356102L,
			["vendor_item_injector"] = 180356103L,
			["vendor_item_pills"] = 180356104L,
			["vendor_item_grubs"] = 180356105L
		};

		public static Dictionary<long, string> APIDtoProgressionUnlock = new Dictionary<long, string>
		{
			[180355328L] = "perk_mother",
			[180355329L] = "perk_t1",
			[180355330L] = "perk_t2",
			[180355331L] = "perk_t3",
			[180355332L] = "perk_t4",
			[180355333L] = "perk_t5",
			[180355334L] = "perk_u_adoption",
			[180355335L] = "perk_u_delta",
			[180355336L] = "perk_u_t1",
			[180355337L] = "perk_u_t2",
			[180355338L] = "perk_u_t3",
			[180355584L] = "r_abyss_t1",
			[180355585L] = "r_habitation_t1",
			[180355586L] = "r_pipeworks_t1",
			[180355587L] = "r_pipeworks_t2",
			[180355588L] = "r_pipeworks_t3",
			[180355589L] = "r_shortcut_expulsionchute",
			[180355590L] = "r_shortcut_tangledsink",
			[180355591L] = "r_silos_t1",
			[180355592L] = "r_silos_t2",
			[180355593L] = "r_silos_t3",
			[180355594L] = "r_silos_t4",
			[180355595L] = "r_deepstorage_t1"
		};

		public static Dictionary<string, bool> ModeUnlocks = new Dictionary<string, bool>
		{
			["Mode Selection Button - Campaign Variant"] = true,
			["Mode Selection Button - Tutorial"] = true,
			["Mode Selection Button - Training Sector"] = false,
			["Mode Selection Button - Endless"] = false,
			["Mode Selection Button - Endless Underworks"] = false,
			["Mode Selection Button - Endless Superstructure"] = false,
			["Mode Selection Button - Silos"] = false,
			["Mode Selection Button - Pipeworks"] = false,
			["Mode Selection Button - Habitation"] = false,
			["Mode Selection Button - Abyss"] = false,
			["Mode Selection Button - Nest"] = false,
			["Mode Selection Button - Challenge 01 - Advanced Course"] = true,
			["Mode Selection Button - Challenge 02 - Shattered"] = true,
			["Mode Selection Button - Challenge 03 - Roach Run"] = true,
			["Mode Selection Button - Challenge 04 - Comms"] = false,
			["Mode Selection Button - Challenge 05 - Shutter"] = false,
			["Mode Selection Button - Challenge 06 - Boost"] = false,
			["Mode Selection Button - Chimney"] = false,
			["Mode Selection Button - Parasite.01"] = false
		};

		public static Dictionary<string, bool> TrinketUnlocks = new Dictionary<string, bool>
		{
			["Trinket_Beta"] = false,
			["Trinket_Carabiner"] = false,
			["Trinket_Chalk"] = false,
			["Trinket_EmployeeID"] = false,
			["Trinket_GoldNugget"] = false,
			["Trinket_MassDamper"] = false,
			["Trinket_MoonRock"] = false,
			["Trinket_PhotoOfHome"] = false,
			["Trinket_Pouch"] = false,
			["Trinket_BagExpander"] = false,
			["Trinket_Headlamp"] = false,
			["Trinket_ClimbingShoes"] = false,
			["Trinket_Helmet"] = false,
			["Trinket_CalmingBuddy"] = false
		};

		public static readonly Dictionary<long, string> APIDtoTrinketUnlock = new Dictionary<long, string>
		{
			[181403648L] = "Trinket_Beta",
			[181403649L] = "Trinket_Carabiner",
			[181403650L] = "Trinket_Chalk",
			[181403651L] = "Trinket_EmployeeID",
			[181403652L] = "Trinket_GoldNugget",
			[181403653L] = "Trinket_MassDamper",
			[181403654L] = "Trinket_MoonRock",
			[181403655L] = "Trinket_PhotoOfHome",
			[181403656L] = "Trinket_Pouch",
			[181403657L] = "Trinket_BagExpander",
			[181403658L] = "Trinket_Headlamp",
			[181403659L] = "Trinket_ClimbingShoes",
			[181403660L] = "Trinket_Helmet",
			[181403661L] = "Trinket_CalmingBuddy"
		};

		public static readonly Dictionary<long, string> APIDtoModeUnlock = new Dictionary<long, string>
		{
			[182452224L] = "Mode Selection Button - Campaign Variant",
			[182452225L] = "Mode Selection Button - Training Sector",
			[182452226L] = "Mode Selection Button - Endless",
			[182452227L] = "Mode Selection Button - Endless Underworks",
			[182452228L] = "Mode Selection Button - Endless Superstructure",
			[182452229L] = "Mode Selection Button - Silos",
			[182452230L] = "Mode Selection Button - Pipeworks",
			[182452231L] = "Mode Selection Button - Habitation",
			[182452232L] = "Mode Selection Button - Abyss",
			[182452233L] = "Mode Selection Button - Nest",
			[182452234L] = "Mode Selection Button - Challenge 01 - Advanced Course",
			[182452235L] = "Mode Selection Button - Challenge 02 - Shattered",
			[182452236L] = "Mode Selection Button - Challenge 03 - Roach Run",
			[182452238L] = "Mode Selection Button - Challenge 04 - Comms",
			[182452239L] = "Mode Selection Button - Challenge 05 - Shutter",
			[182452240L] = "Mode Selection Button - Challenge 06 - Boost",
			[182452241L] = "Mode Selection Button - Chimney",
			[182452242L] = "Mode Selection Button - Parasite.01"
		};

		public static Dictionary<string, long> ChallengeMedaltoAPID = new Dictionary<string, long>
		{
			["Advanced Course 1"] = 183500800L,
			["Advanced Course 2"] = 183500801L,
			["Advanced Course 3"] = 183500802L,
			["Advanced Course 4"] = 183500803L,
			["Fractured Territory 1"] = 183500816L,
			["Fractured Territory 2"] = 183500817L,
			["Fractured Territory 3"] = 183500818L,
			["Fractured Territory 4"] = 183500819L,
			["Roach Run 1"] = 183500832L,
			["Roach Run 2"] = 183500833L,
			["Roach Run 3"] = 183500834L,
			["Roach Run 4"] = 183500835L,
			["Comms Array 1"] = 183500848L,
			["Comms Array 2"] = 183500849L,
			["Comms Array 3"] = 183500850L,
			["Comms Array 4"] = 183500851L,
			["Shuttered Rift 1"] = 183500864L,
			["Shuttered Rift 2"] = 183500865L,
			["Shuttered Rift 3"] = 183500866L,
			["Shuttered Rift 4"] = 183500867L,
			["Boost Course 1"] = 183500880L,
			["Boost Course 2"] = 183500881L,
			["Boost Course 3"] = 183500882L,
			["Boost Course 4"] = 183500883L
		};

		public static void ClearCampaignFacilities()
		{
			foreach (string item in FacilityDict.Keys.ToList())
			{
				foreach (string item2 in FacilityDict[item].Keys.ToList())
				{
					FacilityDict[item][item2] = false;
				}
			}
		}

		public static void ClearAllFlags()
		{
			ClearCampaignFacilities();
			foreach (string item in ProgressionUnlocks.Keys.ToList())
			{
				ProgressionUnlocks[item] = false;
			}
			foreach (string item2 in ModeUnlocks.Keys.ToList())
			{
				if (item2 != "Mode Selection Button - Campaign Variant" && item2 != "Mode Selection Button - Tutorial")
				{
					ModeUnlocks[item2] = false;
				}
			}
			foreach (string item3 in TrinketUnlocks.Keys.ToList())
			{
				TrinketUnlocks[item3] = false;
			}
		}

		public static void UpdateFromItem(ItemInfo item)
		{
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			Sprite val = SpriteFromPath("WKRando/Assets/Archipelago_Icon.png");
			Color val2 = default(Color);
			((Color)(ref val2))..ctor(0.3f, 0.3f, 0f);
			long itemId = item.ItemId;
			Plugin.Logger.LogInfo((object)("Attempting to update from AP Item: " + item.ItemDisplayName));
			if (!SentLocations.Contains(itemId))
			{
				SentLocations.Add(itemId);
			}
			if ((179306495 >= itemId && itemId >= 178327552) || itemId == 178323456 || itemId == 178323465)
			{
				string[] array = APtoFullFacilityUpgrade[itemId].Split(" ");
				FacilityDict[array[0]][array[1]] = true;
				Facility.onPurchaseUpgrade();
			}
			else if (181403647 >= itemId && itemId >= 180355072)
			{
				ProgressionUnlocks[APIDtoProgressionUnlock[itemId]] = true;
			}
			else if (182452223 >= itemId && itemId >= 181403648)
			{
				TrinketUnlocks[APIDtoTrinketUnlock[itemId]] = true;
			}
			else if (183500799 >= itemId && itemId >= 182452224)
			{
				ModeUnlocks[APIDtoModeUnlock[itemId]] = true;
			}
			switch (itemId)
			{
			case 177209345L:
				Plugin.LoanAmount++;
				CL_GameManager.runRoaches++;
				TotalRoachesReceived++;
				break;
			case 177209346L:
				CL_GameManager.globalRoaches += 10;
				TotalCreditsReceived += 10;
				break;
			case 177209360L:
				ProgressiveRegions++;
				break;
			case 177209376L:
				TargetAPDebuffCount--;
				break;
			case 177209392L:
				ProgressivePerkUnlocks++;
				val2.g = 0.5f;
				break;
			case 177209408L:
				TrinketSlots++;
				break;
			}
			if (!ArchipelagoClient.Connecting)
			{
				if (item.Player.Slot != ArchipelagoClient.Slot)
				{
					CL_ProgressionManager.ShowUnlockPopup(val, "Received Item:", $"{item.ItemDisplayName} from game {item.LocationGame} at {item.LocationDisplayName}", val2, (AudioClip)null, true);
				}
				else
				{
					CL_ProgressionManager.ShowUnlockPopup(val, "Found your item!", item.ItemDisplayName + " from location " + item.LocationDisplayName, val2, (AudioClip)null, true);
				}
			}
		}

		public static List<long> CheckFacilities()
		{
			return (from facility in StatManager.saveData.facilities
				from upgrade in facility.upgrades
				select FullFacilityUpgradetoAP[$"{facility} {upgrade}"] into id
				where !SentLocations.Contains(id)
				select id).ToList();
		}

		public static Sprite SpriteFromPath(string localPath)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(256, 256);
			ImageConversion.LoadImage(val, File.ReadAllBytes(Path.Combine(Path.Combine(Paths.PluginPath, "ConcreteConsumer-WhiteKnuckleArchipelago"), localPath)));
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 10f);
		}
	}
	public class ArchipelagoClient
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static ItemReceivedHandler <0>__OnItemReceive;

			public static MessageReceivedHandler <1>__OnMessageReceive;

			public static ErrorReceivedHandler <2>__OnError;

			public static SocketClosedHandler <3>__OnSocketClosed;

			public static CheckedLocationsUpdatedHandler <4>__OnLocationReceive;

			public static DeathLinkReceivedHandler <5>__ProcDeathlink;
		}

		private static ArchipelagoSession _session = ArchipelagoSessionFactory.CreateSession("localhost", 38281);

		public static string Servername = "localhost:38281";

		public static string Username = string.Empty;

		public static string Password = string.Empty;

		public static string DeathMessage = "Died to Archipelago Player";

		public static DeathLinkService Deathlinkservice;

		private static string Seed;

		private static bool _connectedBefore;

		public static bool Connecting;

		public static bool Connected;

		private static int _reconnectAttempts = 0;

		public static int Slot = -1;

		private static bool _goaled;

		private static Dictionary<string, object> _slotData;

		private static Queue<ItemInfo> _items = new Queue<ItemInfo>();

		private static List<long> _locationsToSend = new List<long>();

		public event DeathLinkReceivedHandler OnDeathLinkReceived
		{
			add
			{
			}
			remove
			{
			}
		}

		private static void NewSession(string server)
		{
			_session = ArchipelagoSessionFactory.CreateSession(server, 38281);
			Plugin.ClientOptions.Server = server;
		}

		public static async Task<object> Connect(string server = null, string user = null, string pass = null)
		{
			if (Connected)
			{
				CommandConsole.Log("Already connected to server " + Plugin.ClientOptions.Server + " as " + Plugin.ClientOptions.User);
				return null;
			}
			Plugin.Logger.LogInfo((object)("Connecting to " + server));
			if (server != null && server != Plugin.ClientOptions.Server)
			{
				Plugin.ClientOptions.Server = server;
			}
			if (user != null && user != Plugin.ClientOptions.User)
			{
				Plugin.ClientOptions.User = user;
			}
			if (pass != null && pass != Plugin.ClientOptions.Password)
			{
				Plugin.ClientOptions.Password = pass;
			}
			NewSession(Plugin.ClientOptions.Server);
			IReceivedItemsHelper items = _session.Items;
			object obj = <>O.<0>__OnItemReceive;
			if (obj == null)
			{
				ItemReceivedHandler val = OnItemReceive;
				<>O.<0>__OnItemReceive = val;
				obj = (object)val;
			}
			items.ItemReceived += (ItemReceivedHandler)obj;
			IMessageLogHelper messageLog = _session.MessageLog;
			object obj2 = <>O.<1>__OnMessageReceive;
			if (obj2 == null)
			{
				MessageReceivedHandler val2 = OnMessageReceive;
				<>O.<1>__OnMessageReceive = val2;
				obj2 = (object)val2;
			}
			messageLog.OnMessageReceived += (MessageReceivedHandler)obj2;
			IArchipelagoSocketHelper socket = _session.Socket;
			object obj3 = <>O.<2>__OnError;
			if (obj3 == null)
			{
				ErrorReceivedHandler val3 = OnError;
				<>O.<2>__OnError = val3;
				obj3 = (object)val3;
			}
			socket.ErrorReceived += (ErrorReceivedHandler)obj3;
			IArchipelagoSocketHelper socket2 = _session.Socket;
			object obj4 = <>O.<3>__OnSocketClosed;
			if (obj4 == null)
			{
				SocketClosedHandler val4 = OnSocketClosed;
				<>O.<3>__OnSocketClosed = val4;
				obj4 = (object)val4;
			}
			socket2.SocketClosed += (SocketClosedHandler)obj4;
			ILocationCheckHelper locations = _session.Locations;
			object obj5 = <>O.<4>__OnLocationReceive;
			if (obj5 == null)
			{
				CheckedLocationsUpdatedHandler val5 = OnLocationReceive;
				<>O.<4>__OnLocationReceive = val5;
				obj5 = (object)val5;
			}
			locations.CheckedLocationsUpdated += (CheckedLocationsUpdatedHandler)obj5;
			APItems.TargetAPDebuffCount = 10;
			APItems.ClearAllFlags();
			APItems.SentLocations.Clear();
			LoginResult result;
			try
			{
				result = _session.TryConnectAndLogin("White Knuckle", Plugin.ClientOptions.User, (ItemsHandlingFlags)7, (Version)null, (string[])null, (string)null, (string)null, true);
			}
			catch (Exception ex)
			{
				result = (LoginResult)new LoginFailure(ex.GetBaseException().Message);
			}
			if (!result.Successful)
			{
				LoginFailure failure = (LoginFailure)result;
				CommandConsole.Log($"Failed to Connect to {Plugin.ClientOptions.Server} as {Plugin.ClientOptions.User}:");
				string[] errors = failure.Errors;
				foreach (string error in errors)
				{
					CommandConsole.Log("    " + error);
				}
				ConnectionRefusedError[] errorCodes = failure.ErrorCodes;
				foreach (ConnectionRefusedError error2 in errorCodes)
				{
					CommandConsole.Log($"    {error2}");
				}
				await Disconnect(tryReconnect: true);
				return null;
			}
			Connecting = true;
			Connected = true;
			LoginSuccessful loginSuccess = (LoginSuccessful)result;
			Slot = loginSuccess.Slot;
			Seed = _session.RoomState.Seed;
			if (!File.Exists(Path.Combine(Application.persistentDataPath, Seed + "_save.json")))
			{
				File.Create(Path.Combine(Application.persistentDataPath, Seed + "_save.json"));
				Plugin.AlterStats.UpdateSaveLocationNames(Seed);
				CommandConsole.hasCheated = true;
				CL_GameManager.runRoaches = 0;
				CL_GameManager.globalRoaches = 0;
				CL_GameManager.gMan.Restart(Array.Empty<string>());
			}
			else
			{
				Plugin.AlterStats.UpdateSaveLocationNames(Seed);
			}
			APItems.SentLocations.AddRange(_session.Locations.AllLocationsChecked);
			FixSendQueue();
			foreach (ItemInfo item in _session.Items.AllItemsReceived)
			{
				_items.Enqueue(item);
			}
			CheckReceivedItems();
			foreach (long item2 in APItems.SentLocations)
			{
				Plugin.Logger.LogInfo((object)$"Logged Sent Location ID: {item2}");
			}
			Update();
			FillOptions(loginSuccess.SlotData);
			if (!Utility.IsNullOrWhiteSpace(server))
			{
				Plugin.ClientOptions.Server = server;
			}
			if (!Utility.IsNullOrWhiteSpace(user))
			{
				Plugin.ClientOptions.User = user;
			}
			if (!Utility.IsNullOrWhiteSpace(pass))
			{
				Plugin.ClientOptions.Password = pass;
			}
			Connecting = false;
			CommandConsole.Log($"Successfully connected to {Plugin.ClientOptions.Server} as {Plugin.ClientOptions.User}!");
			CommandConsole.Log($"   Slot Number: {loginSuccess.Slot}");
			Plugin.ClientOptions.SaveOptions();
			_connectedBefore = true;
			Deathlinkservice = DeathLinkProvider.CreateDeathLinkService(_session);
			DeathLinkService deathlinkservice = Deathlinkservice;
			object obj6 = <>O.<5>__ProcDeathlink;
			if (obj6 == null)
			{
				DeathLinkReceivedHandler val6 = DeathLinkHandler.ProcDeathlink;
				<>O.<5>__ProcDeathlink = val6;
				obj6 = (object)val6;
			}
			deathlinkservice.OnDeathLinkReceived += (DeathLinkReceivedHandler)obj6;
			if (Plugin.ClientOptions.Deathlink)
			{
				Deathlinkservice.EnableDeathLink();
			}
			return null;
		}

		public static async Task<object> Disconnect(bool tryReconnect = false)
		{
			if (_session != null)
			{
				IReceivedItemsHelper items = _session.Items;
				object obj = <>O.<0>__OnItemReceive;
				if (obj == null)
				{
					ItemReceivedHandler val = OnItemReceive;
					<>O.<0>__OnItemReceive = val;
					obj = (object)val;
				}
				items.ItemReceived -= (ItemReceivedHandler)obj;
				IMessageLogHelper messageLog = _session.MessageLog;
				object obj2 = <>O.<1>__OnMessageReceive;
				if (obj2 == null)
				{
					MessageReceivedHandler val2 = OnMessageReceive;
					<>O.<1>__OnMessageReceive = val2;
					obj2 = (object)val2;
				}
				messageLog.OnMessageReceived -= (MessageReceivedHandler)obj2;
				IArchipelagoSocketHelper socket = _session.Socket;
				object obj3 = <>O.<2>__OnError;
				if (obj3 == null)
				{
					ErrorReceivedHandler val3 = OnError;
					<>O.<2>__OnError = val3;
					obj3 = (object)val3;
				}
				socket.ErrorReceived -= (ErrorReceivedHandler)obj3;
				IArchipelagoSocketHelper socket2 = _session.Socket;
				object obj4 = <>O.<3>__OnSocketClosed;
				if (obj4 == null)
				{
					SocketClosedHandler val4 = OnSocketClosed;
					<>O.<3>__OnSocketClosed = val4;
					obj4 = (object)val4;
				}
				socket2.SocketClosed -= (SocketClosedHandler)obj4;
				ILocationCheckHelper locations = _session.Locations;
				object obj5 = <>O.<4>__OnLocationReceive;
				if (obj5 == null)
				{
					CheckedLocationsUpdatedHandler val5 = OnLocationReceive;
					<>O.<4>__OnLocationReceive = val5;
					obj5 = (object)val5;
				}
				locations.CheckedLocationsUpdated -= (CheckedLocationsUpdatedHandler)obj5;
				if (Deathlinkservice != null)
				{
					DeathLinkService deathlinkservice = Deathlinkservice;
					object obj6 = <>O.<5>__ProcDeathlink;
					if (obj6 == null)
					{
						DeathLinkReceivedHandler val6 = DeathLinkHandler.ProcDeathlink;
						<>O.<5>__ProcDeathlink = val6;
						obj6 = (object)val6;
					}
					deathlinkservice.OnDeathLinkReceived -= (DeathLinkReceivedHandler)obj6;
					Deathlinkservice = null;
				}
				APItems.TargetAPDebuffCount = 10;
				APItems.TrinketSlots = 3;
				APItems.ProgressiveRegions = 0;
				APItems.ProgressivePerkUnlocks = 0;
				Plugin.LoanAmount = 0;
				APItems.ClearAllFlags();
				APItems.SentLocations.Clear();
				CL_GameManager.globalRoaches -= APItems.TotalCreditsReceived;
				CL_GameManager.runRoaches -= APItems.TotalRoachesReceived;
			}
			Connected = false;
			_goaled = false;
			if (_connectedBefore && tryReconnect)
			{
				_reconnectAttempts++;
				if (_reconnectAttempts >= 5)
				{
					await Task.Delay(5000);
					_connectedBefore = false;
				}
				await Connect();
			}
			_slotData = new Dictionary<string, object>();
			return null;
		}

		public static void Update()
		{
			if (Connected)
			{
				try
				{
					CheckReceivedItems();
					CheckLocationsToSend();
				}
				catch
				{
					Disconnect();
				}
			}
		}

		private static void OnLocationReceive(ReadOnlyCollection<long> newCheckedLocations)
		{
			lock (APItems.SentLocations)
			{
				foreach (long newCheckedLocation in newCheckedLocations)
				{
					APItems.SentLocations.Add(newCheckedLocation);
				}
			}
		}

		private static void OnItemReceive(ReceivedItemsHelper helper)
		{
			while (helper.Any())
			{
				_items.Enqueue(helper.DequeueItem());
			}
		}

		private static void OnMessageReceive(LogMessage message)
		{
			CommandConsole.Log($"[{Plugin.ClientOptions.Server}] - {message}");
		}

		public static void Say(string[] args)
		{
			if (Connected)
			{
				_session.Say(string.Join(" ", args));
			}
			else
			{
				CommandConsole.Log("Not currently connected to server");
			}
		}

		public static void TryQueueLocation(long itemID)
		{
			_locationsToSend.Add(itemID);
		}

		private static void CheckReceivedItems()
		{
			while (_items.Any() && Connected)
			{
				ItemInfo val = _items.Dequeue();
				APItems.UpdateFromItem(val);
				CommandConsole.Log($"Received item: {val.ItemDisplayName} from {val.LocationName} in game {val.LocationGame}");
			}
		}

		public static void Goal()
		{
			if (!_goaled)
			{
				_session.SetGoalAchieved();
				_goaled = true;
			}
		}

		private static void CheckLocationsToSend()
		{
			//IL_00bd: Expected O, but got Unknown
			if (!(_locationsToSend.Any() & Connected))
			{
				return;
			}
			try
			{
				_session.Locations.CompleteLocationChecksAsync(_locationsToSend.ToArray());
				List<long> locationsToSend = _locationsToSend;
				_locationsToSend.Clear();
				foreach (long item in locationsToSend)
				{
					Plugin.Logger.LogInfo((object)("Sent item ID: " + item));
					if (!APItems.SentLocations.Contains(item))
					{
						APItems.SentLocations.Add(item);
					}
				}
				ShowSentItemPopup(locationsToSend);
			}
			catch (ArchipelagoSocketClosedException ex)
			{
				ArchipelagoSocketClosedException ex2 = ex;
				Plugin.Logger.LogError((object)((object)ex2).ToString());
				Disconnect();
			}
		}

		private static async Task ShowSentItemPopup(List<long> locationsToSend)
		{
			Dictionary<long, ScoutedItemInfo> infos = await _session.Locations.ScoutLocationsAsync(_locationsToSend.ToArray());
			foreach (long l in locationsToSend)
			{
				if (infos[l].Player.Name != Plugin.ClientOptions.User && !Connecting)
				{
					ItemFlags flags = ((ItemInfo)infos[l]).Flags;
					if (1 == 0)
					{
					}
					string text = (int)flags switch
					{
						0 => "Filler_Icon", 
						1 => "Progression_Icon", 
						2 => "Icon", 
						4 => "Trap_Icon", 
						_ => throw new ArgumentOutOfRangeException(), 
					};
					if (1 == 0)
					{
					}
					Sprite val = APItems.SpriteFromPath("WKRando/Assets/Archipelago_" + text + ".png");
					string text2 = $"{((ItemInfo)infos[l]).ItemDisplayName} for {infos[l].Player} from {((ItemInfo)infos[l]).LocationDisplayName}";
					ItemFlags flags2 = ((ItemInfo)infos[l]).Flags;
					if (1 == 0)
					{
					}
					Color val2 = (Color)((int)flags2 switch
					{
						0 => new Color(0.2f, 0.2f, 0.2f), 
						1 => new Color(0.5f, 0.5f, 0f), 
						2 => new Color(0.3f, 0f, 0.5f), 
						4 => new Color(0.5f, 0f, 0f), 
						_ => throw new ArgumentOutOfRangeException(), 
					});
					if (1 == 0)
					{
					}
					CL_ProgressionManager.ShowUnlockPopup(val, "Sent Item:", text2, val2, (AudioClip)null, true);
				}
			}
		}

		private static void OnError(Exception exception, string message)
		{
			Plugin.Logger.LogError((object)exception.ToString());
			CommandConsole.Log("AP " + message);
			Disconnect();
		}

		private static void OnSocketClosed(string message)
		{
			Plugin.Logger.LogError((object)("AP " + message));
			CommandConsole.Log("AP " + message);
			Disconnect();
		}

		private static void FixSendQueue()
		{
			for (int i = 0; i < _locationsToSend.Count; i++)
			{
				if (APItems.SentLocations.Contains(_locationsToSend[i]))
				{
					_locationsToSend.RemoveAt(i);
				}
			}
		}

		private static void FillOptions(Dictionary<string, object> slotData)
		{
			string text = "";
			foreach (string key in slotData.Keys)
			{
				text += $"{key}: {slotData[key]}\n";
			}
			Plugin.Logger.LogInfo((object)text);
			Plugin.Logger.LogInfo((object)Convert.ToString(DataStorageElement.op_Implicit(_session.DataStorage[(Scope)3, "ConnectedOnce"])));
			_session.DataStorage[(Scope)3, "ConnectedOnce"].Initialize(JToken.op_Implicit(false));
			Plugin.APOptions.StartingDebuffs = (slotData.TryGetValue("Starting_Debuffs", out var value) ? Convert.ToInt32(value) : 10);
			APItems.TargetAPDebuffCount -= 10 - Plugin.APOptions.StartingDebuffs;
			Plugin.APOptions.StartingTrinketSlots = ((!slotData.TryGetValue("Starting_Trinket_Slots", out var value2)) ? 1 : Convert.ToInt32(value2));
			APItems.TrinketSlots += 3 - Plugin.APOptions.StartingTrinketSlots;
			Plugin.APOptions.EnableAllTrinkets = slotData.TryGetValue("Enable_Trinket_Randomization", out var value3) && Convert.ToBoolean(value3);
			Plugin.APOptions.SetGoalArea(slotData.TryGetValue("Goal_Region", out var value4) ? Convert.ToInt32(value4) : 3);
			if (slotData.TryGetValue("Include_Challenge_Modes", out var value5) && (int)value5 == 1)
			{
				Plugin.APOptions.UnlockChallenges();
			}
			Plugin.ClientOptions.LoadOptions();
			if (!DataStorageElement.op_Implicit(_session.DataStorage[(Scope)3, "ConnectedOnce"]))
			{
				Plugin.Logger.LogInfo((object)"First connection detecting, setting any client data");
				SetClientOptions(slotData);
			}
			_session.DataStorage[(Scope)3, "ConnectedOnce"] = DataStorageElement.op_Implicit(true);
		}

		public static async Task<List<ScoutedItemInfo>> ScoutItemDescriptionFromID(long[] ids)
		{
			return (await _session.Locations.ScoutLocationsAsync(false, ids)).Values.ToList();
		}

		private static void FillOptions()
		{
		}

		public static void SetClientOptions(string[] args)
		{
			SetClientOptions(_slotData);
		}

		public static void SetClientOptions(Dictionary<string, object> slotData)
		{
			try
			{
				if (Convert.ToInt32(slotData["Deathlink"]) == 0)
				{
					Plugin.ClientOptions.EnableDeathlink();
				}
				else if (Convert.ToInt32(slotData["Deathlink"]) == 1)
				{
					Plugin.ClientOptions.DisableDeathlink();
				}
			}
			catch
			{
				Plugin.Logger.LogInfo((object)"Deathlink not found, skipping");
			}
			try
			{
				if (Convert.ToInt32(slotData["Deathlink_Amnesty"]) != 0)
				{
					Plugin.ClientOptions.DeathlinkAmnesty = Convert.ToInt32(slotData["deathlink_amnesty"]);
				}
			}
			catch
			{
				Plugin.Logger.LogInfo((object)"Deathlink amnesty not found, skipping");
			}
			try
			{
				if (Convert.ToBoolean(slotData["Include_Challenge_Modes"]))
				{
					Plugin.ClientOptions.FreeDiskVendors = true;
				}
				else
				{
					Plugin.ClientOptions.FreeDiskVendors = false;
				}
			}
			catch
			{
				Plugin.Logger.LogInfo((object)"Disk Vendor Cost not found, skipping");
			}
			Plugin.ClientOptions.ServerSeed = _session.RoomState.Seed;
			Plugin.ClientOptions.SaveOptions();
			if (Plugin.ClientOptions.Deathlink)
			{
				Deathlinkservice.EnableDeathLink();
			}
		}
	}
	public static class CustomPerks
	{
		private static Perk _apDebuff;

		private static Perk _apBuff;

		private static Perk _apAmnesty;

		public static Perk ApBuff(int stacks = 1)
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Expected O, but got Unknown
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Expected O, but got Unknown
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0216: Unknown result type (might be due to invalid IL or missing references)
			_apBuff = ScriptableObject.CreateInstance<Perk>();
			_apBuff.id = "archipelago_buff";
			((Object)_apBuff).name = "perk_ap_buff";
			_apBuff.title = "Archipelago Buff";
			_apBuff.description = "You feel the pull of other worlds taking you higher";
			_apBuff.canStack = true;
			_apBuff.stackMax = 100;
			_apBuff.useBuff = true;
			_apBuff.buffMultiplier = 1f;
			_apBuff.multiplierCurve = AnimationCurve.Constant(0f, 1f, 1f);
			_apBuff.modules = new List<PerkModule>();
			_apBuff.stackAmount = stacks;
			_apBuff.buff = new BuffContainer
			{
				id = "archipelago_buff",
				desc = "",
				loseOverTime = false,
				loseRate = 0f,
				buffTime = 1f,
				multiplier = 1f,
				loseRateEffectedByPerks = false,
				buffs = new List<Buff>
				{
					NewBuff("addGravity", -0.03f, -0.03f),
					NewBuff("addStaminaRegen", 0.04f, 0.04f),
					NewBuff("addStamina", 0.05f, 0.05f),
					NewBuff("addClimb", 0.06f, 0.06f),
					NewBuff("addJump", 0.05f, 0.05f),
					NewBuff("addSpeed", 0.06f, 0.06f)
				}
			};
			Texture2D val = new Texture2D(256, 256);
			string path = Path.Combine(Path.Combine(Paths.PluginPath, "ConcreteConsumer-WhiteKnuckleArchipelago"), "WKRando\\Assets\\Archipelago_Perk.png");
			ImageConversion.LoadImage(val, File.ReadAllBytes(path));
			_apBuff.icon = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 900f);
			_apBuff.iconMat = CL_AssetManager.baseDatabase.perkAssets[62].iconMat;
			return _apBuff;
		}

		public static Perk ApDebuff(int stacks = 1)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Expected O, but got Unknown
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			_apDebuff = ScriptableObject.CreateInstance<Perk>();
			_apDebuff.id = "archipelago_debuff";
			((Object)_apDebuff).name = "perk_ap_debuff";
			_apDebuff.title = "Archipelago Debuff";
			_apDebuff.description = "The grasp of other worlds weighs you down";
			_apDebuff.flavorText = "Debuffs to all stats";
			_apDebuff.stackMax = 100;
			_apDebuff.useBuff = true;
			_apDebuff.buffMultiplier = 1f;
			_apDebuff.multiplierCurve = CreateExponentialDecayCurve(0.98f);
			_apDebuff.modules = new List<PerkModule>();
			_apDebuff.stackAmount = stacks;
			_apDebuff.buff = new BuffContainer
			{
				id = "archipelago_debuff",
				desc = "",
				loseOverTime = false,
				loseRate = 0f,
				buffTime = 1f,
				multiplier = 1f,
				loseRateEffectedByPerks = false,
				buffs = new List<Buff>
				{
					NewBuff("addGravity", 0.05f, 0.05f),
					NewBuff("addStaminaRegen", -0.01f, -0.01f),
					NewBuff("addStamina", -0.05f, -0.05f),
					NewBuff("addClimb", -0.005f, -0.005f),
					NewBuff("addJump", -0.005f, -0.005f),
					NewBuff("addSpeed", -0.03f, -0.03f)
				}
			};
			Texture2D val = new Texture2D(256, 256);
			ImageConversion.LoadImage(val, File.ReadAllBytes(Path.Combine(Path.Combine(Paths.PluginPath, "ConcreteConsumer-WhiteKnuckleArchipelago"), "WKRando\\Assets\\Broken_Archipelago_Perk.png")));
			_apDebuff.icon = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 900f);
			_apDebuff.iconMat = CL_AssetManager.baseDatabase.perkAssets[10].iconMat;
			return _apDebuff;
		}

		public static Perk AmnestyStack(int stacks = 1)
		{
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Expected O, but got Unknown
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			_apAmnesty = ScriptableObject.CreateInstance<Perk>();
			_apAmnesty.id = "archipelago_amnesty";
			((Object)_apAmnesty).name = "perk_ap_amnesty";
			_apAmnesty.title = "Deathlink Amnesty";
			_apAmnesty.description = "Receiving a specified amount of this perk will kill you!";
			_apAmnesty.flavorText = "Obtained whenever someone dies in the multiworld";
			_apAmnesty.stackMax = 100;
			_apAmnesty.useBuff = false;
			_apAmnesty.buffMultiplier = 0f;
			_apAmnesty.modules = new List<PerkModule>();
			_apAmnesty.multiplierCurve = AnimationCurve.Constant(0f, 1f, 1f);
			_apAmnesty.stackAmount = stacks;
			Texture2D val = new Texture2D(256, 256);
			ImageConversion.LoadImage(val, File.ReadAllBytes(Path.Combine(Path.Combine(Paths.PluginPath, "ConcreteConsumer-WhiteKnuckleArchipelago"), "WKRando\\Assets\\Archipelago_Amnesty_Perk.png")));
			_apAmnesty.icon = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 900f);
			_apAmnesty.iconMat = CL_AssetManager.baseDatabase.perkAssets[10].iconMat;
			return _apAmnesty;
		}

		private static Buff NewBuff(string id, float amount, float maxAmount)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			Buff val = new Buff();
			val.id = id;
			val.amount = amount;
			val.maxAmount = maxAmount;
			return val;
		}

		private static AnimationCurve CreateExponentialDecayCurve(float decay, int keyFrameCount = 100)
		{
			//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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			Keyframe[] array = (Keyframe[])(object)new Keyframe[keyFrameCount];
			float num = 1f;
			for (int i = 0; i < keyFrameCount; i++)
			{
				array[i] = new Keyframe((float)i / (float)(keyFrameCount - 1), num);
				num *= decay;
			}
			return new AnimationCurve(array);
		}
	}
	internal static class DeathLinkHandler
	{
		private static Sprite _amnestyIcon;

		public static bool deathlinkbusy;

		public static int DeathLinksSentSinceLast;

		public static void Awake()
		{
			_amnestyIcon = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Deathlink_Receive.png");
		}

		public static void ProcDeathlink(DeathLink DeathlinkObject)
		{
			DeathlinkDeath(DeathlinkObject);
		}

		public static void LocalSendDeathLink(string reason)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			Plugin.Logger.LogInfo((object)("Died to " + reason + " As Player " + Plugin.ClientOptions.User));
			if (!Plugin.ClientOptions.Deathlink || ArchipelagoClient.Deathlinkservice == null || Utility.IsNullOrWhiteSpace(reason))
			{
				Plugin.Logger.LogInfo((object)"Deathlink is disabled");
				return;
			}
			ArchipelagoClient.Deathlinkservice.SendDeathLink(new DeathLink(Utility.IsNullOrWhiteSpace(Plugin.ClientOptions.User) ? "white knuckle player" : Plugin.ClientOptions.User, Plugin.ClientOptions.User + ": " + reason.ToLower()));
			Plugin.Logger.LogInfo((object)"Successfully sent DeathLink");
		}

		private static void DeathlinkDeath(DeathLink DeathlinkObject)
		{
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.ClientOptions.Deathlink || Plugin.ClientOptions.DeathlinkAmnesty == 0)
			{
				return;
			}
			Plugin.Logger.LogInfo((object)"Starting Deathlink");
			DeathLinksSentSinceLast++;
			if (DeathLinksSentSinceLast >= Plugin.ClientOptions.DeathlinkAmnesty)
			{
				deathlinkbusy = true;
				if (((DeathlinkObject != null) ? DeathlinkObject.Cause : null) != null)
				{
					ArchipelagoClient.DeathMessage = DeathlinkObject.Cause;
				}
				Plugin.Logger.LogInfo((object)("Killing player because of deathlink " + (((DeathlinkObject != null) ? DeathlinkObject.Source : null) ?? "Some player") + ", " + (((DeathlinkObject != null) ? DeathlinkObject.Cause : null) ?? "Unknown Cause")));
				((GameEntity)ENT_Player.playerObject).Kill("deathlink", (DamageInfo)null);
				DeathLinksSentSinceLast = 0;
			}
			else
			{
				Plugin.Logger.LogInfo((object)"Deathlink caught by amnesty");
				CL_ProgressionManager.ShowUnlockPopup(_amnestyIcon, "Deathlink Stack Received", ((DeathlinkObject != null) ? DeathlinkObject.Cause : null) ?? "Unknown Cause", new Color(0.4f, 0.1f, 0.1f), (AudioClip)null, true);
			}
			deathlinkbusy = false;
		}
	}
	[BepInPlugin("com.wuckle.concsumer.name", "WKRando", "1.0.0")]
	[BepInProcess("White Knuckle.exe")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ENT_Player), "Update")]
		private class PlayerUpdate
		{
			private static void Prefix(ENT_Player __instance)
			{
				ArchipelagoClient.Update();
				try
				{
					if (ArchipelagoClient.Connected && (Object)(object)WorldLoader.instance != (Object)null && WorldLoader.instance.GetCurrentLevel().GetLevel().levelName == APOptions.GoalArea)
					{
						ArchipelagoClient.Goal();
					}
					if ((Object)(object)WorldLoader.instance != (Object)null && APItems.RoomNameToAP.TryGetValue(WorldLoader.instance.GetCurrentLevel().GetLevel().levelName, out var value) && !APItems.SentLocations.Contains(value))
					{
						APItems.SentLocations.Add(value);
						ArchipelagoClient.TryQueueLocation(value);
					}
				}
				catch
				{
				}
				int? num = ((__instance == null) ? ((int?)null) : __instance.GetPerk("archipelago_debuff")?.stackAmount);
				int valueOrDefault;
				if (!num.HasValue)
				{
					int? obj2;
					if (__instance == null)
					{
						obj2 = null;
					}
					else
					{
						Perk perk = __instance.GetPerk("archipelago_buff");
						obj2 = ((perk != null) ? new int?(-perk.stackAmount) : ((int?)null));
					}
					int? num2 = obj2;
					valueOrDefault = num2.GetValueOrDefault();
				}
				else
				{
					valueOrDefault = num.GetValueOrDefault();
				}
				int num3 = valueOrDefault;
				if (num3 != APItems.TargetAPDebuffCount && (Object)(object)__instance != (Object)null && !((GameEntity)__instance).IsDead())
				{
					Logger.LogInfo((object)("Amount, Target: " + num3 + ", " + APItems.TargetAPDebuffCount));
					__instance.RemovePerk("archipelago_buff", true);
					__instance.RemovePerk("archipelago_debuff", true);
					if (APItems.TargetAPDebuffCount > 0)
					{
						__instance.AddPerk(CL_AssetManager.GetPerkAsset("archipelago_debuff", ""), APItems.TargetAPDebuffCount, true);
					}
					else if (APItems.TargetAPDebuffCount != 0)
					{
						__instance.AddPerk(CL_AssetManager.GetPerkAsset("archipelago_buff", ""), -APItems.TargetAPDebuffCount, true);
					}
				}
				if (ClientOptions.DeathlinkAmnesty != 0 && (Object)(object)__instance != (Object)null && !((GameEntity)__instance).IsDead() && DeathLinkHandler.DeathLinksSentSinceLast != ((__instance == null) ? ((int?)null) : __instance.GetPerk("archipelago_amnesty")?.stackAmount).GetValueOrDefault())
				{
					__instance.RemovePerk("archipelago_amnesty", true);
					__instance.AddPerk(CL_AssetManager.GetPerkAsset("archipelago_amnesty", ""), DeathLinkHandler.DeathLinksSentSinceLast, true);
				}
			}
		}

		[HarmonyPatch(typeof(FacilityUpgrade), "IsOwned")]
		private class AlterUpgradeCheck
		{
			private static bool Prefix(FacilityUpgrade __instance, ref bool __result, object[] __args)
			{
				string id = StatManager.saveData.GetFacility((string)__args[0]).id;
				if (APItems.FacilityDict.TryGetValue(id, out var value) && value.TryGetValue(__instance.id, out var value2))
				{
					__result = value2;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(SteamManager), "Update")]
		public class DisableSteamManager
		{
			private static bool Prefix()
			{
				return false;
			}
		}

		[HarmonyPatch]
		public class AlterStats
		{
			public static string SaveLocation = "Archipelago/rando_save.json";

			public static string BackupSaveLocation = "Archipelago/rando_save-backup.json";

			public static string ErrorBackupLocation = "Archipelago/rando_save-error-backup.json";

			public static string CrashBackupLocation = "Archipelago/rando_save-backup-crash.json";

			public static string QuitBackupLocation = "Archipelago/rando_save-backup-quit.json";

			public static void UpdateSaveLocationNames(string seedID)
			{
				SaveLocation = "Archipelago/" + seedID + "_save.json";
				if (StatManager.hasLoaded)
				{
					StatManager.instance.filePath = Path.Combine(Application.persistentDataPath, SaveLocation);
				}
				BackupSaveLocation = "Archipelago/" + seedID + "_save-backup.json";
				ErrorBackupLocation = "Archipelago/" + seedID + "_save-error-backup.json";
				CrashBackupLocation = "Archipelago/" + seedID + "_save-backup-crash.json";
				QuitBackupLocation = "Archipelago/" + seedID + "_save-backup-quit.json";
			}

			[HarmonyPatch(typeof(StatManager), "Awake")]
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0003: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Expected O, but got Unknown
				return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(true, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((OpCode?)OpCodes.Ldstr, (object)"wk_save.json", (string)null)
				}).Repeat((Action<CodeMatcher>)delegate(CodeMatcher matcher)
				{
					//IL_001a: Unknown result type (might be due to invalid IL or missing references)
					//IL_0024: Expected O, but got Unknown
					matcher.SetInstruction(new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(AlterStats), "SaveLocation")));
				}, (Action<string>)null).InstructionEnumeration();
			}

			[HarmonyPatch(typeof(StatManager), "LoadStats")]
			private static void Postfix(StatManager __instance)
			{
				Logger.LogInfo((object)("Save is at: " + __instance.filePath));
			}

			[HarmonyPatch(typeof(CL_Leaderboard), "CreateUserDataFromCurrentSession")]
			[HarmonyPrefix]
			private static bool PreventOfflineScores(ref WK_Leaderboard_UserData __result)
			{
				__result = null;
				return false;
			}
		}

		[HarmonyPatch(typeof(CommandConsole), "Awake")]
		private class AddCommands
		{
			private static void ChangeLoanCommand(string[] args)
			{
				if (args.Length == 0 || args[0] == "")
				{
					CommandConsole.Log("Incorrect format: Uses a single integer");
				}
				else
				{
					LoanAmount = int.Parse(args[0]);
				}
			}

			public static void CheatRoachesInCommand(string[] args)
			{
				try
				{
					CL_GameManager.runRoaches = int.Parse(args[0]);
				}
				catch
				{
					CommandConsole.Log("Requires a single integer");
				}
			}

			private static async void TryConnectCommand(string[] args)
			{
				if (args.Length == 0)
				{
					await ArchipelagoClient.Connect();
				}
				else if (args.Length == 1)
				{
					await ArchipelagoClient.Connect(args[0]);
				}
				else if (args.Length == 2)
				{
					await ArchipelagoClient.Connect(args[0], args[1]);
				}
				else
				{
					await ArchipelagoClient.Connect(args[0], args[1], args[2]);
				}
			}

			private static void ResetAPSaveData(string[] args)
			{
				CommandConsole.Log("Resetting Save...");
				File.Create(Path.Combine(Application.persistentDataPath, (ClientOptions.ServerSeed ?? "rando") + "_save.json"));
			}

			private static async void DisconnectCommand(string[] args)
			{
				await ArchipelagoClient.Disconnect();
			}

			private static void SetDebuffs(string[] args)
			{
				if (args.Length < 1 || !int.TryParse(args[0], out var result))
				{
					CommandConsole.Log("Requires a single integer");
				}
				else
				{
					APItems.TargetAPDebuffCount = result;
				}
			}

			private static void TestPopup(string[] args)
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				string text = "Test message";
				if (args.Length >= 1)
				{
					text = args[0];
				}
				CL_ProgressionManager.ShowUnlockPopup(APItems.SpriteFromPath("WKRando/Assets/Archipelago_Icon.png"), "Test Popup", text, new Color(0f, 1f, 0f), (AudioClip)null, true);
			}

			private static void ChangeClientSettings(string[] args)
			{
				for (int i = 0; i < args.Length - 1; i++)
				{
					try
					{
						switch (args[i].ToLower().Replace('-', '_'))
						{
						case "deathlink":
							Logger.LogInfo((object)"deathlink...");
							if (args[i + 1] == "amnesty")
							{
								ClientOptions.DeathlinkAmnesty = Convert.ToInt32(args[i + 2]);
								Logger.LogInfo((object)("setting deathlink amnesty to " + args[i + 2]));
								CommandConsole.Log("setting deathlink amnesty to " + args[i + 2]);
								break;
							}
							if (Convert.ToBoolean(args[i + 1]))
							{
								ClientOptions.EnableDeathlink();
							}
							else if (!Convert.ToBoolean(args[i + 1]))
							{
								ClientOptions.DisableDeathlink();
							}
							Logger.LogInfo((object)("Setting Deathlink to " + args[i + 1]));
							CommandConsole.Log("Setting Deathlink to " + args[i + 1]);
							break;
						case "deathlink_amnesty":
							ClientOptions.DeathlinkAmnesty = Convert.ToInt32(args[i + 1]);
							Logger.LogInfo((object)("Setting Deathlink-amnesty to " + args[i + 1]));
							CommandConsole.Log("Setting Deathlink-amnesty to " + args[i + 1]);
							break;
						case "free_disk_vendors":
							ClientOptions.FreeDiskVendors = Convert.ToBoolean(args[i + 1]);
							Logger.LogInfo((object)("Setting Free-disk-vendors to " + args[i + 1]));
							CommandConsole.Log("Setting Free-disk-vendors to " + args[i + 1]);
							break;
						case "unlock_all_endless":
							ClientOptions.UnlockAllEndlessModes = Convert.ToBoolean(args[i + 1]);
							Logger.LogInfo((object)("Setting Unlock-all-endless to " + args[i + 1]));
							CommandConsole.Log("Setting Unlock-all-endless to " + args[i + 1]);
							break;
						}
					}
					catch
					{
						CommandConsole.Log("Invalid command arguments");
					}
				}
				ClientOptions.SaveOptions();
			}

			private static void TestArchipelagoDeath(string[] args)
			{
				if (args.Length >= 1)
				{
					ArchipelagoClient.DeathMessage = string.Join(" ", args);
				}
				((GameEntity)ENT_Player.playerObject).Kill("deathlink");
			}

			private static void Postfix()
			{
				CommandConsole.BuildCommand("setdebuff", (Action<string[]>)SetDebuffs).NotCheat().Description("Sets the number of archipelago debuffs to the specified integer. Using a negative integer will apply buffs instead.");
				CommandConsole.BuildCommand("setloan", (Action<string[]>)ChangeLoanCommand).Description("Sets the starting roach loan value to the specified value");
				CommandConsole.BuildCommand("connect", (Action<string[]>)TryConnectCommand).NotCheat().Description("Attempts to connect to Archipelago Server \n")
					.OverValue((Func<object>)(() => "\n    <color=yellow>Servername:</color> " + (Utility.IsNullOrWhiteSpace(ClientOptions.Server) ? "none" : ClientOptions.Server) + " " + "\n    <color=yellow>Username:</color> " + (Utility.IsNullOrWhiteSpace(ClientOptions.User) ? "none" : ClientOptions.User) + " \n    <color=yellow>Password:</color> " + (Utility.IsNullOrWhiteSpace(ClientOptions.Password) ? "none" : new string('*', ClientOptions.Password.Length))));
				CommandConsole.BuildCommand("resetapsave", (Action<string[]>)ResetAPSaveData).Description("Deprecated command");
				CommandConsole.BuildCommand("say", (Action<string[]>)ArchipelagoClient.Say).NotCheat().Description("Sends a message to the archipelago client.");
				CommandConsole.BuildCommand("disconnect", (Action<string[]>)DisconnectCommand).NotCheat().Description("Disconnects from the Archipelago Server");
				CommandConsole.BuildCommand("testpopup", (Action<string[]>)TestPopup).NotCheat();
				CommandConsole.BuildCommand("ResetClientOptions", (Action<string[]>)ArchipelagoClient.SetClientOptions).NotCheat().Description("Resets your client options back to what is listed in the yaml");
				CommandConsole.BuildCommand("ChangeClientOptions", (Action<string[]>)ChangeClientSettings).NotCheat().Description("Changes options, use ListOptions to get a list of the ones you can change, spaces and both dashes work")
					.AutocompleteCustom((Action<CommandAutocomplete>)delegate(CommandAutocomplete autocomplete)
					{
						if (autocomplete.activeArg < 0 || autocomplete.activeArg > 1)
						{
							autocomplete.Reject();
						}
						else if (autocomplete.activeArg == 0)
						{
							autocomplete.FromArrayWithDesc((IReadOnlyList<ValueTuple<string, string>>)new List<(string, string)>
							{
								("deathlink", $"Sets deathlink with true or false: {ClientOptions.Deathlink}"),
								("deathlink-amnesty", $"Sets receive amnesty with integer: {ClientOptions.DeathlinkAmnesty}"),
								("free-disk-vendors", $"Sets whether or not disk vendors are free: {ClientOptions.FreeDiskVendors}"),
								("unlock-all-endless", $"Unlocks all endless modes: {ClientOptions.UnlockAllEndlessModes}")
							});
						}
						else if (autocomplete.activeArg == 1)
						{
							string text = autocomplete.args[0];
							if (text == "deathlink" || text == "free-disk-vendors")
							{
								autocomplete.FromArray((IReadOnlyList<string>)new <>z__ReadOnlyArray<string>(new string[2] { "true", "false" }));
							}
						}
					});
				CommandConsole.BuildCommand("TestArchipelagoDeath", (Action<string[]>)TestArchipelagoDeath).Description("Kills the player with the specified death message");
				Logger.LogInfo((object)"Successfully Injected Commands");
			}
		}

		[HarmonyPatch(typeof(UI_CapsuleButton), "CheckAchievement")]
		private class PatchModeUIButtons
		{
			private static Dictionary<string, string> areaChecker = new Dictionary<string, string>
			{
				["Mode Selection Button - Endless"] = "none",
				["Mode Selection Button - Endless Underworks"] = "none",
				["Mode Selection Button - Endless Superstructure"] = "none",
				["Mode Selection Button - Silos"] = "ldc-silos-breakroom-totaltimesreached",
				["Mode Selection Button - Pipeworks"] = "ldc-interlude-lockdown-totaltimesreached",
				["Mode Selection Button - Habitation"] = "ldc-m3_shaft_safearea-totaltimesreached",
				["Mode Selection Button - Abyss"] = "ldc-interlude-evacuation-totaltimesreached",
				["Mode Selection Button - Nest"] = "ldc-interlude-symbiosis-start-totaltimesreached"
			};

			private static Dictionary<string, int> progressiveReqs = new Dictionary<string, int>
			{
				["Mode Selection Button - Endless"] = 4,
				["Mode Selection Button - Endless Underworks"] = 1,
				["Mode Selection Button - Endless Superstructure"] = 2,
				["Mode Selection Button - Silos"] = 0,
				["Mode Selection Button - Pipeworks"] = 1,
				["Mode Selection Button - Habitation"] = 2,
				["Mode Selection Button - Abyss"] = 3,
				["Mode Selection Button - Nest"] = 4
			};

			private static bool Prefix(UI_CapsuleButton __instance)
			{
				if (APItems.ModeUnlocks.TryGetValue(((Object)__instance).name, out var value))
				{
					if (areaChecker.TryGetValue(((Object)__instance).name, out var value2) && progressiveReqs.TryGetValue(((Object)__instance).name, out var value3) && ((StatManager.GetTotalStatisticInt(value2) > 0 && APItems.ProgressiveRegions >= value3) || ClientOptions.UnlockAllEndlessModes))
					{
						value = true;
					}
					if (__instance.unlockIcon != null)
					{
						((Component)__instance.unlockIcon).gameObject.SetActive(!value);
					}
					if (__instance.group != null)
					{
						__instance.group.interactable = value;
						__instance.group.alpha = (value ? 1f : 0.5f);
					}
					__instance.button.interactable = value;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Cosmetic_Base), "IsUnlocked")]
		private class PatchCosmeticBaseIsUnlocked
		{
			private static bool Prefix(ref bool __result)
			{
				__result = true;
				return false;
			}
		}

		[HarmonyPatch(typeof(UI_FacilityMenu_Button), "Refresh")]
		private class PatchMainMenuFacilityButtons
		{
			private static void Postfix(UI_FacilityMenu_Button __instance)
			{
				//IL_00af: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Expected I4, but got Unknown
				if ((Object)(object)__instance == (Object)null)
				{
					return;
				}
				Logger.LogInfo((object)((Object)__instance.upgrade).name);
				if (!ArchipelagoClient.Connected)
				{
					__instance.tooltip.tip = "<color=red>DISCONNECTED\n</color>Connect to the archipelago server to purchase facility upgrades";
					__instance.lockRoot.SetActive(true);
					__instance.isLocked = true;
					return;
				}
				__instance.lockRoot.SetActive(false);
				__instance.isLocked = false;
				((Component)__instance.icon).gameObject.SetActive(true);
				if (_nameToScoutedItem.TryGetValue("GLOBAL " + ((Object)__instance.upgrade).name, out var value))
				{
					ItemFlags flags = ((ItemInfo)value).Flags;
					ItemFlags val = flags;
					switch ((int)val)
					{
					case 1:
						__instance.tooltip.tip = "<color=blue>Progression Item</color>\nThis item is classified as progression to some player in this multiworld.";
						__instance.icon.sprite = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Progression_Icon.png");
						break;
					case 2:
						__instance.tooltip.tip = "<color=purple>Useful Item</color>\nThis item is classified as useful to some player in this multiworld.";
						__instance.icon.sprite = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Icon.png");
						break;
					case 0:
						__instance.tooltip.tip = "<color=grey>Filler Item</color>\nThis item is classified as useful to some player in this multiworld.";
						__instance.icon.sprite = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Filler_Icon.png");
						break;
					case 4:
						__instance.tooltip.tip = "<color=red>Trap Item</color>\nThis item is classified as a trap to some player in this multiworld.";
						__instance.icon.sprite = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Trap_Icon.png");
						break;
					}
					__instance.purchasedRoot.SetActive(APItems.SentLocations.Contains(((ItemInfo)value).LocationId));
				}
				else
				{
					__instance.tooltip.tip = "This is an unknown archipelago item!";
					__instance.icon.sprite = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Icon.png");
				}
				Upgrade upgrade = StatManager.saveData.GetFacility(__instance.facility.id).GetUpgrade(__instance.upgrade.id);
				if (upgrade != null && upgrade.owned)
				{
					__instance.isSelected = true;
					__instance.purchasedRoot.SetActive(true);
					return;
				}
				__instance.isSelected = false;
				__instance.purchasedRoot.SetActive(false);
				if (!__instance.isLocked && __instance.upgrade.cost > StatManager.saveData.GetRoachBankByID("campaign").value)
				{
					__instance.tooltip.tip = "<color=red>CANNOT AFFORD\n</color>\n" + __instance.tooltip.tip;
					__instance.expensiveRoot.gameObject.SetActive(true);
					((Component)__instance.icon).gameObject.SetActive(false);
					__instance.isLocked = true;
				}
			}
		}

		[HarmonyPatch(typeof(FacilityMenu), "FillUpgrades")]
		private class PatchScoutFromFacilityMenu
		{
			private static void Prefix(FacilityMenu __instance)
			{
				if (!ArchipelagoClient.Connected)
				{
					return;
				}
				List<long> list = new List<long>();
				List<string> list2 = new List<string>();
				foreach (FacilityUpgrade upgrade in __instance.globalFacility.upgrades)
				{
					Logger.LogInfo((object)("Detected Global Upgrade " + upgrade.id));
					if (APItems.FullFacilityUpgradetoAP.TryGetValue("GLOBAL " + upgrade.id, out var value))
					{
						list.Add(value);
						list2.Add("GLOBAL " + upgrade.id);
					}
				}
				UpdateScoutedItems(list, list2);
			}
		}

		[HarmonyPatch(typeof(SteamManager), "Update")]
		private class DisableSteamLeaderboardUploads
		{
			private static bool Prefix()
			{
				return false;
			}
		}

		[HarmonyPatch]
		private class PatchUnlocks
		{
			[HarmonyPatch(typeof(ProgressionUnlock), "CheckUnlock")]
			private static bool Prefix(ProgressionUnlock __instance, ref bool __result)
			{
				bool flag = (__instance.state = APItems.ProgressionUnlocks[__instance.id]);
				if ((Object)(object)CL_GameManager.gMan != (Object)null)
				{
					CL_GameManager.SetGameFlag("unlock_" + ((Object)__instance).name, flag, "", false, false);
				}
				__result = flag;
				return false;
			}

			[HarmonyPatch(typeof(CL_ProgressionManager), "HasProgressionUnlock")]
			[HarmonyPrefix]
			private static bool Prefix(CL_ProgressionManager __instance, ref bool __result, object[] __args)
			{
				__result = CL_ProgressionManager.progressionDict != null && CL_ProgressionManager.progressionDict.ContainsKey((string)__args[0]) && CL_ProgressionManager.progressionDict[(string)__args[0]].CheckUnlock();
				return false;
			}
		}

		[HarmonyPatch(typeof(App_PerkPage), "CheckIronKnuckle")]
		private class PatchPerksPage
		{
			private static bool Prefix(App_PerkPage __instance)
			{
				//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_00af: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
				//IL_010e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0119: Unknown result type (might be due to invalid IL or missing references)
				//IL_011e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0128: Expected O, but got Unknown
				string levelName = WorldLoader.instance.GetCurrentLevel().GetLevel().levelName;
				int progressivePerkUnlocks = APItems.ProgressivePerkUnlocks;
				bool flag = ((levelName == "Campaign_Interlude_Silo_To_Pipeworks_01" || levelName == "Campaign_Interlude_Sink_To_Pipeworks_01") ? true : false);
				bool flag2 = flag && progressivePerkUnlocks < 1;
				bool flag3 = flag2;
				if (!flag3)
				{
					bool flag4 = ((levelName == "M3_Habitation_Shaft_Intro" || levelName == "Campaign_Interlude_Chute_To_Habitation") ? true : false);
					flag3 = flag4 && progressivePerkUnlocks < 2;
				}
				if (flag3 || (levelName == "Campaign_Interlude_Abyss_To_Nest_01_SafeArea" && progressivePerkUnlocks < 3))
				{
					__instance.window.os.messageManager.CreateMessage(new Message_Packet
					{
						type = "default",
						closeText = "Quit",
						closeFunction = __instance.window.CloseApp,
						message = $"Perks for this sector are disabled by Archipelago!\nCurrent progressive perk count is {APItems.ProgressivePerkUnlocks}",
						screenPos = new Vector2(0f, 0f)
					});
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(App_Unlocker))]
		private class PatchShortcutUnlock
		{
			[HarmonyPatch("Start")]
			private static void Postfix(App_Unlocker __instance)
			{
				__instance.password = "impossible passcode uwu you can't unlock this no matter what you do!";
				if (((__instance.saveFlagOnUnlock == "unlockedsink") & APItems.ProgressionUnlocks["r_shortcut_tangledsink"]) || ((__instance.window.file.fileInfo.data.Split(",")[0].Split(":")[1] == "chutecode") & APItems.ProgressionUnlocks["r_shortcut_expulsionchute"]))
				{
					__instance.authorizationCost = 0;
					__instance.CheckAuthorize();
				}
			}
		}

		[HarmonyPatch(typeof(Trinket), "IsUnlocked")]
		private class PatchTrinketUnlock
		{
			private static bool Prefix(Trinket __instance, ref bool __result)
			{
				if (APItems.TrinketUnlocks.TryGetValue(((Object)__instance).name, out var value))
				{
					__result = APOptions.EnableAllTrinkets || value;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(UI_TrinketPicker))]
		private class PatchPips
		{
			[HarmonyPatch("UpdateTrinketActivation")]
			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0003: 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_0023: Expected O, but got Unknown
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Expected O, but got Unknown
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Expected O, but got Unknown
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_005f: Expected O, but got Unknown
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Expected O, but got Unknown
				return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[4]
				{
					new CodeMatch((OpCode?)OpCodes.Ldc_I4_0, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Stloc_0, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Ldc_I4_1, (object)null, (string)null),
					new CodeMatch((OpCode?)OpCodes.Stloc_1, (object)null, (string)null)
				}).Advance(2).SetInstruction(new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(APItems), "TrinketSlots")))
					.InstructionEnumeration();
			}

			[HarmonyPatch("UpdatePips")]
			private static void Prefix(object[] __args)
			{
				__args[0] = APItems.TrinketSlots;
			}
		}

		[HarmonyPatch(typeof(Item))]
		private class RemoveUnlockPopup
		{
			[HarmonyPatch("SendUnlockMessage")]
			private static bool Prefix()
			{
				return false;
			}
		}

		[HarmonyPatch(typeof(CL_Button), "Interact", new Type[] { })]
		private class PatchFacilityButtons
		{
			private static bool Prefix(CL_Button __instance)
			{
				Logger.LogInfo((object)((Object)__instance).name);
				string levelName = WorldLoader.instance.GetCurrentLevel().GetLevel().levelName;
				int progressiveRegions = APItems.ProgressiveRegions;
				Logger.LogInfo((object)("Current Progressive Region Count: " + progressiveRegions));
				if (progressiveRegions < 1 && ((levelName == "Campaign_Interlude_Silo_To_Pipeworks_01" && ((Object)__instance).name == "Button.002") || (levelName == "Campaign_Interlude_Sink_To_Pipeworks_01" && ((Object)__instance).name == "Prop_Button_02_Switch.01")))
				{
					return false;
				}
				if (progressiveRegions < 2 && ((levelName == "M3_Habitation_Shaft_Intro" && ((Object)__instance).name == "Prop_Button_03_Door") || (levelName == "Campaign_Interlude_Chute_To_Habitation" && ((Object)__instance).name == "Prop_Button_04")))
				{
					return false;
				}
				if (progressiveRegions < 3 && levelName == "Campaign_Interlude_Habitation_To_Abyss_01" && ((Object)__instance).name == "Prop_Button_03.01")
				{
					return false;
				}
				return !((progressiveRegions < 4) & (levelName == "Campaign_Interlude_Abyss_To_Nest_01_SafeArea")) || !(((Object)__instance).name == "Prop_Button_03");
			}
		}

		[HarmonyPatch(typeof(CL_GameManager), "Awake")]
		private class PatchCommandConsole
		{
			private static void Prefix()
			{
			}
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		private class PatchCommands
		{
			private static void Postfix()
			{
				Loaded = true;
			}

			private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
			{
				//IL_0003: 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_0023: Expected O, but got Unknown
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Expected O, but got Unknown
				return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((OpCode?)OpCodes.Ldc_I4_S, (object)null, (string)null)
				}).SetInstructionAndAdvance(new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(Plugin), "LoanAmount"))).InstructionEnumeration();
			}
		}

		[HarmonyPatch(typeof(Facility), "HasUpgrade")]
		private class Force20RoachConditional
		{
			private static bool Prefix(ref bool __result, object[] __args)
			{
				if ((string)__args[0] == "UPG_Global_StartingRoaches_T3")
				{
					__result = true;
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(CL_GameManager), "OnDestroy")]
		private class UnloadgMan
		{
			private static void Prefix()
			{
				Loaded = false;
			}
		}

		[HarmonyPatch(typeof(FacilityUpgrade), "Purchase", new Type[] { typeof(Facility) })]
		private class PatchPurchase
		{
			private static void Prefix(FacilityUpgrade __instance, object[] __args)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				long itemID = APItems.FullFacilityUpgradetoAP[((Facility)__args[0]).id + " " + __instance.id];
				ArchipelagoClient.TryQueueLocation(itemID);
			}
		}

		[HarmonyPatch(typeof(CL_AssetManager), "Initialize")]
		private class PatchPerks
		{
			private static void Postfix()
			{
				CL_AssetManager.baseDatabase.perkAssets.AddRange(new <>z__ReadOnlyArray<Perk>((Perk[])(object)new Perk[3]
				{
					CustomPerks.ApBuff(),
					CustomPerks.ApDebuff(),
					CustomPerks.AmnestyStack()
				}));
			}
		}

		[HarmonyPatch(typeof(App_Facility_Card), "CheckLock")]
		private class PatchPerkRefresh
		{
			private static bool Prefix(App_Facility_Card __instance)
			{
				//IL_009e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c2: Expected I4, but got Unknown
				if (!ArchipelagoClient.Connected)
				{
					__instance.lockedObject.SetActive(true);
					__instance.tooltip.tip = "<color=red>LOCKED\nDisconnected from Archipelago!</color>\nConnect to purchase upgrades!";
					__instance.locked = true;
				}
				else
				{
					__instance.lockedObject.SetActive(false);
					__instance.locked = false;
					if (_nameToScoutedItem != null && _nameToScoutedItem.TryGetValue(__instance.facility.id + " " + __instance.upgrade.id, out var value))
					{
						((Component)__instance.art).gameObject.SetActive(true);
						ItemFlags flags = ((ItemInfo)value).Flags;
						ItemFlags val = flags;
						switch ((int)val)
						{
						case 1:
							__instance.tooltip.tip = "<color=blue>Progression Item</color>\nThis item is classified as progression to some player in this multiworld.";
							__instance.art.sprite = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Progression_Icon.png");
							break;
						case 2:
							__instance.tooltip.tip = "<color=purple>Useful Item</color>\nThis item is classified as useful to some player in this multiworld.";
							__instance.art.sprite = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Icon.png");
							break;
						case 0:
							__instance.tooltip.tip = "<color=grey>Filler Item</color>\nThis item is classified as useful to some player in this multiworld.";
							__instance.art.sprite = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Filler_Icon.png");
							break;
						case 4:
							__instance.tooltip.tip = "<color=red>Trap Item</color>\nThis item is classified as a trap to some player in this multiworld.";
							__instance.art.sprite = APItems.SpriteFromPath("WKRando/Assets/Archipelago_Trap_Icon.png");
							break;
						}
						__instance.purchasedObject.SetActive(APItems.SentLocations.Contains(((ItemInfo)value).LocationId));
					}
					else
					{
						__instance.tooltip.tip = "Some archipelago item probably (scouting failed :( )";
					}
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(App_FacilitySlotHolder), "Start")]
		private class PatchSlotHolder
		{
			private static void Prefix(App_FacilitySlotHolder __instance)
			{
				if (!ArchipelagoClient.Connected || (Object)(object)__instance.window == (Object)null)
				{
					return;
				}
				Logger.LogInfo((object)"Attempting to scout facility upgrades");
				Facility facilityAsset = CL_AssetManager.GetFacilityAsset(__instance.window.os.worldInterface.facilityID, "");
				Facility globalFacility = __instance.globalFacility;
				List<long> locationsToScout = new List<long>();
				List<string> list = new List<string>();
				foreach (FacilityUpgrade upgrade in facilityAsset.GetUpgrades())
				{
					if (APItems.FullFacilityUpgradetoAP.TryGetValue(facilityAsset.id + " " + upgrade.id, out var value))
					{
						locationsToScout.Add(value);
						list.Add(facilityAsset.id + " " + upgrade.id);
					}
				}
				foreach (FacilityUpgrade upgrade2 in globalFacility.GetUpgrades())
				{
					Logger.LogInfo((object)("Detected Global Upgrade " + upgrade2.id));
					if (APItems.FullFacilityUpgradetoAP.TryGetValue("GLOBAL " + upgrade2.id, out var value2))
					{
						locationsToScout.Add(value2);
						list.Add("GLOBAL " + upgrade2.id);
					}
				}
				List<ScoutedItemInfo> result = Task.Run(async () => await ArchipelagoClient.ScoutItemDescriptionFromID(locationsToScout.ToArray())).GetAwaiter().GetResult();
				for (int num = 0; num < list.Count; num++)
				{
					if (!_nameToScoutedItem.TryGetValue(list[num], out var value3))
					{
						_nameToScoutedItem.Add(list[num], result[num]);
					}
					else if (value3 != result[num])
					{
						_nameToScoutedItem.Remove(list[num]);
						_nameToScoutedItem.Add(list[num], result[num]);
					}
				}
			}
		}

		[HarmonyPatch(typeof(ENV_Vendor_Disk), "Update")]
		private class PatchDiskVendorCost
		{
			private static void Prefix(ENV_Vendor_Disk __instance)
			{
				if (ClientOptions.FreeDiskVendors && __instance.cost != 0)
				{
					__instance.cost = 0;
				}
			}
		}

		[HarmonyPatch(typeof(MenuManager), "Start")]
		private class PatchChallengeChecks
		{
			private static void Prefix()
			{
				if (ArchipelagoClient.Connected)
				{
					ChallengeQueue();
				}
			}

			private static void ChallengeQueue()
			{
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				foreach (M_Gamemode gamemodeAsset in CL_AssetManager.GetFullCombinedAssetDatabase().gamemodeAssets)
				{
					if (!(((object)gamemodeAsset.gamemodeModule).GetType() == typeof(GamemodeModule_Challenge)))
					{
						continue;
					}
					foreach (Medal medal in ((GamemodeModule_Challenge)gamemodeAsset.gamemodeModule).medals)
					{
						if (medal.scoreRequirement < 1f)
						{
							medal.scoreRequirement = 1f;
						}
					}
				}
				foreach (M_Gamemode gamemodeAsset2 in CL_AssetManager.GetFullCombinedAssetDatabase().gamemodeAssets)
				{
					int num = ChallengeMode.GetMedalRankFromGamemode(gamemodeAsset2);
					int num2 = 0;
					while (num2 < num)
					{
						Logger.LogInfo((object)$"Detected medal: {gamemodeAsset2.gamemodeName} rank {num}");
						if (APItems.ChallengeMedaltoAPID.TryGetValue($"{gamemodeAsset2.gamemodeName} {num}", out var value) && !APItems.SentLocations.Contains(value))
						{
							ArchipelagoClient.TryQueueLocation(value);
						}
						num--;
					}
				}
			}
		}

		[HarmonyPatch(typeof(CL_LocalizationManager), "GetLocalization")]
		private class PatchDeathmessage
		{
			private static bool Prefix(ref string __result, object[] __args)
			{
				if ((string)__args[0] == "deathmessages" && (string)__args[1] == "deathlink")
				{
					__result = ArchipelagoClient.DeathMessage;
					return false;
				}
				if ((string)__args[0] == "deathmessages")
				{
					DeathLinkHandler.LocalSendDeathLink(CL_LocalizationManager.currentLocalization.GetLine((string)__args[0], (string)__args[1]));
				}
				return true;
			}
		}

		[HarmonyPatch]
		private class PatchUnlockPopups
		{
			[HarmonyPatch(typeof(Item), "SendUnlockMessage")]
			[HarmonyPrefix]
			private static bool RemoveItemProgressPopup()
			{
				return false;
			}

			[HarmonyPatch(typeof(CL_ProgressionManager), "UpdateUnlocks")]
			[HarmonyPrefix]
			private static bool RemoveProgressionPopups()
			{
				return false;
			}
		}

		[HarmonyPatch(typeof(SteamManager), "UploadGamemodeResults")]
		private class PatchSteamUpload
		{
			private static bool Prefix()
			{
				return false;
			}
		}

		public class APOptions
		{
			public static int StartingDebuffs = 10;

			public static int StartingTrinketSlots = 1;

			public static bool EnableAllTrinkets;

			public static string GoalArea = "M5_Nest_Trough_Ending_01";

			public static void SetGoalArea(int i)
			{
				switch (i)
				{
				case 1:
					GoalArea = "Campaign_Interlude_Silo_To_Pipeworks_01";
					break;
				case 2:
					GoalArea = "M3_Habitation_Shaft_Intro";
					break;
				case 3:
					GoalArea = "Campaign_Interlude_Habitation_To_Abyss_01";
					break;
				case 4:
					GoalArea = "Campaign_Interlude_Abyss_To_Nest_01_SafeArea";
					break;
				case 5:
					GoalArea = "M5_Nest_Trough_Ending_01";
					break;
				}
			}

			public static void UnlockChallenges()
			{
				foreach (string item in APItems.ModeUnlocks.Keys.ToList())
				{
					if (item.Contains("Challenge"))
					{
						APItems.ModeUnlocks[item] = true;
					}
				}
			}
		}

		public class CLoptions
		{
			public bool Deathlink = false;

			public int DeathlinkAmnesty = 0;

			public bool FreeDiskVendors = false;

			public bool UnlockAllEndlessModes = false;

			public string ServerSeed;

			public string Server = "";

			public string User = "";

			public string Password = "";

			public void EnableDeathlink()
			{
				if (ArchipelagoClient.Deathlinkservice == null)
				{
					CommandConsole.Log("No deathlink object present");
					return;
				}
				Deathlink = true;
				ArchipelagoClient.Deathlinkservice.EnableDeathLink();
			}

			public void DisableDeathlink()
			{
				Deathlink = false;
				ArchipelagoClient.Deathlinkservice.DisableDeathLink();
			}

			public void SaveOptions()
			{
				File.WriteAllText(Application.persistentDataPath + "\\Archipelago\\ClientOptions.json", JsonUtility.ToJson((object)ClientOptions));
				Logger.LogInfo((object)("Saving client options as " + JsonUtility.ToJson((object)ClientOptions)));
			}

			public void LoadOptions()
			{
				string text = File.ReadAllText(Application.persistentDataPath + "\\Archipelago\\ClientOptions.json");
				Logger.LogInfo((object)("Loading client options as: " + text));
				ClientOptions = JsonUtility.FromJson<CLoptions>(text) ?? new CLoptions();
			}

			public static void ListClientSettings(string[] args)
			{
				CommandConsole.Log($"Deathlink: {ClientOptions.Deathlink} \nDeathlink Amnesty: {ClientOptions.DeathlinkAmnesty}");
			}
		}

		internal static ManualLogSource Logger;

		public static int LoanAmount = 0;

		public static bool Loaded;

		public static CLoptions ClientOptions;

		private static Dictionary<string, ScoutedItemInfo> _nameToScoutedItem = new Dictionary<string, ScoutedItemInfo>();

		private void Awake()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			Harmony val = new Harmony("com.wuckle.concsumer.name");
			HarmonyFileLog.Enabled = true;
			if (!Directory.Exists(Application.persistentDataPath + "\\Archipelago"))
			{
				Directory.CreateDirectory(Path.Combine(Application.persistentDataPath, "Archipelago"));
			}
			if (!File.Exists(Application.persistentDataPath + "\\Archipelago\\ClientOptions.json"))
			{
				ClientOptions = new CLoptions();
				ClientOptions.SaveOptions();
			}
			else
			{
				ClientOptions = new CLoptions();
				ClientOptions.LoadOptions();
				if (ClientOptions == null)
				{
					ClientOptions = new CLoptions();
				}
				if (ClientOptions?.ServerSeed != null && !Utility.IsNullOrWhiteSpace(ClientOptions.ServerSeed))
				{
					AlterStats.UpdateSaveLocationNames(ClientOptions.ServerSeed);
				}
			}
			DeathLinkHandler.Awake();
			val.PatchAll(Assembly.GetExecutingAssembly());
			Logger.LogInfo((object)"Archipelago plugin Loaded");
		}

		public static async void UpdateScoutedItems(List<long> locationsToScout, List<string> upgradeNames)
		{
			try
			{
				List<ScoutedItemInfo> descriptions = await ArchipelagoClient.ScoutItemDescriptionFromID(locationsToScout.ToArray());
				for (int i = 0; i < upgradeNames.Count; i++)
				{
					if (!_nameToScoutedItem.TryGetValue(upgradeNames[i], out var info))
					{
						_nameToScoutedItem.Add(upgradeNames[i], descriptions[i]);
					}
					else if (info != descriptions[i])
					{
						_nameToScoutedItem.Remove(upgradeNames[i]);
						_nameToScoutedItem.Add(upgradeNames[i], descriptions[i]);
					}
					info = null;
				}
			}
			catch (Exception ex)
			{
				Exception e = ex;
				Logger.LogError((object)e.ToString());
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "WKRando";

		public const string PLUGIN_NAME = "My first plugin";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}