Decompiled source of StickyBomb v0.1.1

plugins/MuckStickyBomb.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("MuckStickyBomb")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Adds Risk of Rain 2's Sticky Bomb (chance on hit to attach a bomb) to Muck as a Blue powerup.")]
[assembly: AssemblyFileVersion("0.1.1.0")]
[assembly: AssemblyInformationalVersion("0.1.1+879fc7ac66fec639f2f84b4b7a65d5c61c9ed734")]
[assembly: AssemblyProduct("Sticky Bomb")]
[assembly: AssemblyTitle("MuckStickyBomb")]
[assembly: InternalsVisibleTo("MuckStickyBomb.Tests")]
[assembly: AssemblyVersion("0.1.1.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
}
namespace MuckStickyBomb
{
	[HarmonyPatch(typeof(HitableMob), "Hit")]
	internal static class HitableMobHitPatch
	{
		private static void Postfix(HitableMob __instance, int __0, int __4)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null)
				{
					return;
				}
				Mob component = ((Component)__instance).GetComponent<Mob>();
				if (StickyBomb.TryArm(hit: new HitSnapshot(__4, __0, StickyBombPowerup.LocalStacks(), StickyBombHits.KindOf(component), StickyBombHits.IsDetonating), tuning: StickyBombPlugin.Cfg.Tuning(), roll: () => Random.value, bomb: out var bomb))
				{
					if (StickyBombPlugin.Cfg.VerboseLogging.Value)
					{
						StickyBombPlugin.Log.LogInfo((object)$"Sticky bomb stuck to {((Object)__instance).name} from a {__0} hit.");
					}
					((MonoBehaviour)StickyBombRunner.Instance).StartCoroutine(StickyBombHits.Fuse(__instance, bomb));
				}
			}
			catch (Exception arg)
			{
				StickyBombPlugin.Log.LogError((object)$"Sticky bomb on-hit failed: {arg}");
			}
		}
	}
	internal static class PickupArt
	{
		public const string ObjResource = "MuckStickyBomb.pickup.obj";

		public const string JsonResource = "MuckStickyBomb.pickup.json";

		public static void Apply(Powerup powerup, Powerup[] pool)
		{
			if ((Object)(object)powerup == (Object)null || (Object)(object)powerup.mesh != (Object)null)
			{
				return;
			}
			Powerup val = Donor(pool, powerup);
			try
			{
				PickupMesh data = PickupMesh.From(PickupModel.Parse(Read("MuckStickyBomb.pickup.obj"), Read("MuckStickyBomb.pickup.json")));
				Material val2 = (((Object)(object)val != (Object)null) ? val.material : null);
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = FallbackShader();
				}
				bool vertexColors = (Object)(object)val2 == (Object)null || !val2.HasProperty("_MainTex");
				powerup.mesh = ToMesh(data, powerup.name, vertexColors);
				powerup.material = ToMaterial(data, val2, powerup.name);
			}
			catch (Exception ex)
			{
				StickyBombPlugin.Log.LogWarning((object)("Sticky Bomb pickup model was not applied (" + ex.Message + ")."));
				if ((Object)(object)val != (Object)null && (Object)(object)val.mesh != (Object)null)
				{
					powerup.mesh = val.mesh;
					powerup.material = val.material;
				}
				else
				{
					StickyBombPlugin.Log.LogWarning((object)"No Blue powerup to borrow a pickup model from; dropped Sticky Bombs will be invisible.");
				}
			}
		}

		private static Powerup Donor(Powerup[] pool, Powerup self)
		{
			if (pool == null)
			{
				return null;
			}
			Powerup val = null;
			foreach (Powerup val2 in pool)
			{
				if (!((Object)(object)val2 == (Object)null) && val2 != self)
				{
					if ((Object)(object)val2.material != (Object)null)
					{
						return val2;
					}
					if ((Object)(object)val == (Object)null && (Object)(object)val2.mesh != (Object)null)
					{
						val = val2;
					}
				}
			}
			return val;
		}

		private static string Read(string name)
		{
			using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name);
			if (stream == null)
			{
				throw new FileNotFoundException(name);
			}
			using StreamReader streamReader = new StreamReader(stream);
			return streamReader.ReadToEnd();
		}

		private static Mesh ToMesh(PickupMesh data, string itemName, bool vertexColors)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			//IL_0097: 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_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			Mesh val = new Mesh
			{
				name = itemName + " pickup",
				hideFlags = (HideFlags)32
			};
			List<Vector3> list = new List<Vector3>(data.Positions.Length);
			List<Vector3> list2 = new List<Vector3>(data.Normals.Length);
			List<Vector2> list3 = new List<Vector2>(data.U.Length);
			List<Color> list4 = new List<Color>(data.Positions.Length);
			for (int i = 0; i < data.Positions.Length; i++)
			{
				list.Add(new Vector3(data.Positions[i].X, data.Positions[i].Y, data.Positions[i].Z));
				list2.Add(new Vector3(data.Normals[i].X, data.Normals[i].Y, data.Normals[i].Z));
				list3.Add(new Vector2(data.U[i], 0.5f));
				list4.Add((Color)(vertexColors ? new Color(data.R[i], data.G[i], data.B[i], 1f) : Color.white));
			}
			val.SetVertices(list);
			val.SetNormals(list2);
			val.SetUVs(0, list3);
			val.SetColors(list4);
			val.SetTriangles(data.Triangles, 0);
			val.RecalculateBounds();
			return val;
		}

		private static Material FallbackShader()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			Shader val = Shader.Find("Standard");
			if ((Object)(object)val == (Object)null)
			{
				val = Shader.Find("Diffuse");
			}
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return new Material(val);
		}

		private static Material ToMaterial(PickupMesh data, Material source, string itemName)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			if (!source.HasProperty("_MainTex"))
			{
				MaterialSpec materialSpec = data.Palette[0];
				return new Material(source)
				{
					name = itemName + " pickup",
					color = new Color(materialSpec.R, materialSpec.G, materialSpec.B, 1f),
					hideFlags = (HideFlags)32
				};
			}
			Texture2D val = new Texture2D(data.Palette.Count, 1, (TextureFormat)4, false)
			{
				name = itemName + " palette",
				filterMode = (FilterMode)0,
				wrapMode = (TextureWrapMode)1,
				hideFlags = (HideFlags)32
			};
			for (int i = 0; i < data.Palette.Count; i++)
			{
				MaterialSpec materialSpec2 = data.Palette[i];
				val.SetPixel(i, 0, new Color(materialSpec2.R, materialSpec2.G, materialSpec2.B, 1f));
			}
			val.Apply(false, true);
			Material val2 = new Material(source)
			{
				name = itemName + " pickup",
				hideFlags = (HideFlags)32
			};
			val2.mainTexture = (Texture)(object)val;
			val2.mainTextureScale = Vector2.one;
			val2.mainTextureOffset = Vector2.zero;
			if (val2.HasProperty("_Color"))
			{
				val2.color = Color.white;
			}
			return val2;
		}
	}
	internal readonly struct Vec3
	{
		public readonly float X;

		public readonly float Y;

		public readonly float Z;

		public Vec3(float x, float y, float z)
		{
			X = x;
			Y = y;
			Z = z;
		}

		public static Vec3 operator -(Vec3 a, Vec3 b)
		{
			return new Vec3(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
		}
	}
	internal readonly struct MaterialSpec
	{
		public readonly float R;

		public readonly float G;

		public readonly float B;

		public readonly float Emission;

		public MaterialSpec(float r, float g, float b, float emission)
		{
			R = r;
			G = g;
			B = b;
			Emission = emission;
		}
	}
	internal sealed class SubMesh
	{
		public readonly string Material;

		public readonly int[] Triangles;

		public SubMesh(string material, int[] triangles)
		{
			Material = material;
			Triangles = triangles;
		}
	}
	internal sealed class PickupModel
	{
		private sealed class ObjObject
		{
			public readonly List<Vec3> Positions = new List<Vec3>();

			public readonly List<Vec3> Normals = new List<Vec3>();

			public readonly List<string> MaterialOrder = new List<string>();

			public readonly Dictionary<string, List<int>> Triangles = new Dictionary<string, List<int>>();
		}

		public readonly string Name;

		public readonly Vec3[] Positions;

		public readonly Vec3[] Normals;

		public readonly IReadOnlyList<SubMesh> SubMeshes;

		public readonly IReadOnlyDictionary<string, MaterialSpec> Materials;

		public int TriangleCount => Positions.Length / 3;

		public PickupModel(string name, Vec3[] positions, Vec3[] normals, IReadOnlyList<SubMesh> subMeshes, IReadOnlyDictionary<string, MaterialSpec> materials)
		{
			Name = name;
			Positions = positions;
			Normals = normals;
			SubMeshes = subMeshes;
			Materials = materials;
		}

		public static PickupModel Parse(string objText, string json)
		{
			if (!(JsonReader.Parse(json) is Dictionary<string, object> obj))
			{
				throw new FormatException("pickup json: top level is not an object.");
			}
			string text = Str(obj, "name");
			Dictionary<string, MaterialSpec> dictionary = ReadMaterials(Obj(obj, "materials"));
			Dictionary<string, ObjObject> dictionary2 = ReadObj(objText, text);
			if (dictionary2.Count != 1)
			{
				throw new FormatException($"{text}: a pickup OBJ needs exactly one object, it has {dictionary2.Count}.");
			}
			ObjObject objObject = null;
			foreach (ObjObject value in dictionary2.Values)
			{
				objObject = value;
			}
			List<SubMesh> list = new List<SubMesh>();
			foreach (string item in objObject.MaterialOrder)
			{
				if (!dictionary.ContainsKey(item))
				{
					throw new FormatException(text + ": uses undefined material '" + item + "'.");
				}
				list.Add(new SubMesh(item, objObject.Triangles[item].ToArray()));
			}
			PickupModel pickupModel = new PickupModel(text, objObject.Positions.ToArray(), objObject.Normals.ToArray(), list, dictionary);
			int num = (int)Num(obj, "tris");
			if (pickupModel.TriangleCount != num)
			{
				throw new FormatException($"{text}: OBJ has {pickupModel.TriangleCount} triangles, the json says {num}.");
			}
			return pickupModel;
		}

		private static Dictionary<string, ObjObject> ReadObj(string text, string name)
		{
			if (text == null)
			{
				throw new FormatException(name + ": OBJ text is null.");
			}
			List<Vec3> list = new List<Vec3>();
			List<Vec3> list2 = new List<Vec3>();
			Dictionary<string, ObjObject> dictionary = new Dictionary<string, ObjObject>();
			ObjObject objObject = null;
			string text2 = null;
			string[] array = text.Split(new char[1] { '\n' });
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Trim().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
				if (array2.Length == 0)
				{
					continue;
				}
				switch (array2[0])
				{
				case "v":
				{
					Vec3 vec2 = ReadVec(array2, name, i);
					list.Add(new Vec3(0f - vec2.X, vec2.Y, vec2.Z));
					break;
				}
				case "vn":
				{
					Vec3 vec = ReadVec(array2, name, i);
					list2.Add(new Vec3(0f - vec.X, vec.Y, vec.Z));
					break;
				}
				case "o":
				{
					string text3 = string.Join(" ", array2, 1, array2.Length - 1);
					if (dictionary.ContainsKey(text3))
					{
						throw new FormatException(name + ": OBJ object " + text3 + " appears twice.");
					}
					objObject = new ObjObject();
					dictionary.Add(text3, objObject);
					text2 = null;
					break;
				}
				case "usemtl":
					text2 = ((array2.Length > 1) ? array2[1] : null);
					break;
				case "f":
					if (objObject == null || text2 == null)
					{
						throw new FormatException($"{name}: OBJ line {i + 1} has a face outside an object or material.");
					}
					if (array2.Length != 4)
					{
						throw new FormatException($"{name}: OBJ line {i + 1} is not a triangle.");
					}
					AddTriangle(objObject, text2, list, list2, array2, name, i);
					break;
				}
			}
			return dictionary;
		}

		private static void AddTriangle(ObjObject obj, string material, List<Vec3> vertices, List<Vec3> normals, string[] tokens, string name, int line)
		{
			if (!obj.Triangles.TryGetValue(material, out var value))
			{
				value = new List<int>();
				obj.Triangles.Add(material, value);
				obj.MaterialOrder.Add(material);
			}
			int[] array = new int[3] { 1, 3, 2 };
			foreach (int num in array)
			{
				string[] array2 = tokens[num].Split(new char[1] { '/' });
				Vec3 item = vertices[Index(array2[0], vertices.Count, name, line)];
				if (array2.Length < 3 || array2[2].Length == 0)
				{
					throw new FormatException($"{name}: OBJ line {line + 1} has a corner without a normal.");
				}
				value.Add(obj.Positions.Count);
				obj.Positions.Add(item);
				obj.Normals.Add(normals[Index(array2[2], normals.Count, name, line)]);
			}
		}

		private static int Index(string raw, int count, string name, int line)
		{
			if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result == 0)
			{
				throw new FormatException($"{name}: OBJ line {line + 1} has a bad index '{raw}'.");
			}
			int num = ((result > 0) ? (result - 1) : (count + result));
			if (num < 0 || num >= count)
			{
				throw new FormatException($"{name}: OBJ line {line + 1} index {raw} is out of range.");
			}
			return num;
		}

		private static Vec3 ReadVec(string[] tokens, string name, int line)
		{
			if (tokens.Length < 4)
			{
				throw new FormatException($"{name}: OBJ line {line + 1} needs three numbers.");
			}
			return new Vec3(Float(tokens[1], name, line), Float(tokens[2], name, line), Float(tokens[3], name, line));
		}

		private static float Float(string raw, string name, int line)
		{
			if (!float.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				throw new FormatException($"{name}: OBJ line {line + 1} has a bad number '{raw}'.");
			}
			return result;
		}

		private static Dictionary<string, MaterialSpec> ReadMaterials(Dictionary<string, object> raw)
		{
			Dictionary<string, MaterialSpec> dictionary = new Dictionary<string, MaterialSpec>();
			foreach (KeyValuePair<string, object> item in raw)
			{
				if (!(item.Value is Dictionary<string, object> obj))
				{
					throw new FormatException("pickup json: material " + item.Key + " is not an object.");
				}
				Vec3 vec = ReadVec3(obj, "rgb");
				dictionary.Add(item.Key, new MaterialSpec(vec.X, vec.Y, vec.Z, (float)Num(obj, "emission")));
			}
			return dictionary;
		}

		private static Vec3 ReadVec3(Dictionary<string, object> obj, string key)
		{
			List<object> list = Arr(obj, key);
			if (list.Count != 3 || !(list[0] is double num) || !(list[1] is double num2) || !(list[2] is double num3))
			{
				throw new FormatException("pickup json: '" + key + "' is not three numbers.");
			}
			return new Vec3((float)num, (float)num2, (float)num3);
		}

		private static object Field(Dictionary<string, object> obj, string key)
		{
			if (!obj.TryGetValue(key, out var value))
			{
				throw new FormatException("pickup json: missing '" + key + "'.");
			}
			return value;
		}

		private static string Str(Dictionary<string, object> obj, string key)
		{
			return (Field(obj, key) as string) ?? throw new FormatException("pickup json: '" + key + "' is not a string.");
		}

		private static double Num(Dictionary<string, object> obj, string key)
		{
			object obj2 = Field(obj, key);
			if (obj2 is double)
			{
				return (double)obj2;
			}
			throw new FormatException("pickup json: '" + key + "' is not a number.");
		}

		private static List<object> Arr(Dictionary<string, object> obj, string key)
		{
			return (Field(obj, key) as List<object>) ?? throw new FormatException("pickup json: '" + key + "' is not an array.");
		}

		private static Dictionary<string, object> Obj(Dictionary<string, object> obj, string key)
		{
			return (Field(obj, key) as Dictionary<string, object>) ?? throw new FormatException("pickup json: '" + key + "' is not an object.");
		}
	}
	internal sealed class PickupMesh
	{
		public readonly Vec3[] Positions;

		public readonly Vec3[] Normals;

		public readonly float[] U;

		public readonly float[] R;

		public readonly float[] G;

		public readonly float[] B;

		public readonly int[] Triangles;

		public readonly IReadOnlyList<MaterialSpec> Palette;

		private PickupMesh(Vec3[] positions, Vec3[] normals, float[] u, float[] r, float[] g, float[] b, int[] triangles, IReadOnlyList<MaterialSpec> palette)
		{
			Positions = positions;
			Normals = normals;
			U = u;
			R = r;
			G = g;
			B = b;
			Triangles = triangles;
			Palette = palette;
		}

		public static PickupMesh From(PickupModel model)
		{
			Vec3 vec = new Vec3(float.MaxValue, float.MaxValue, float.MaxValue);
			Vec3 vec2 = new Vec3(float.MinValue, float.MinValue, float.MinValue);
			Vec3[] positions = model.Positions;
			for (int i = 0; i < positions.Length; i++)
			{
				Vec3 vec3 = positions[i];
				vec = new Vec3(Math.Min(vec.X, vec3.X), Math.Min(vec.Y, vec3.Y), Math.Min(vec.Z, vec3.Z));
				vec2 = new Vec3(Math.Max(vec2.X, vec3.X), Math.Max(vec2.Y, vec3.Y), Math.Max(vec2.Z, vec3.Z));
			}
			Vec3 vec4 = new Vec3((vec.X + vec2.X) / 2f, (vec.Y + vec2.Y) / 2f, (vec.Z + vec2.Z) / 2f);
			int count = model.SubMeshes.Count;
			List<Vec3> list = new List<Vec3>(model.Positions.Length);
			List<Vec3> list2 = new List<Vec3>(model.Positions.Length);
			List<float> list3 = new List<float>(model.Positions.Length);
			List<float> list4 = new List<float>(model.Positions.Length);
			List<float> list5 = new List<float>(model.Positions.Length);
			List<float> list6 = new List<float>(model.Positions.Length);
			List<MaterialSpec> list7 = new List<MaterialSpec>(count);
			for (int j = 0; j < count; j++)
			{
				SubMesh subMesh = model.SubMeshes[j];
				MaterialSpec item = model.Materials[subMesh.Material];
				list7.Add(item);
				float item2 = ((float)j + 0.5f) / (float)count;
				int[] triangles = subMesh.Triangles;
				foreach (int num in triangles)
				{
					list.Add(model.Positions[num] - vec4);
					list2.Add(model.Normals[num]);
					list3.Add(item2);
					list4.Add(item.R);
					list5.Add(item.G);
					list6.Add(item.B);
				}
			}
			int[] array = new int[list.Count];
			for (int k = 0; k < array.Length; k++)
			{
				array[k] = k;
			}
			return new PickupMesh(list.ToArray(), list2.ToArray(), list3.ToArray(), list4.ToArray(), list5.ToArray(), list6.ToArray(), array, list7);
		}
	}
	internal sealed class JsonReader
	{
		private readonly string text;

		private int pos;

		private JsonReader(string text)
		{
			this.text = text;
		}

		public static object Parse(string text)
		{
			if (text == null)
			{
				throw new FormatException("JSON text is null.");
			}
			JsonReader jsonReader = new JsonReader(text);
			object result = jsonReader.ReadValue();
			jsonReader.SkipWhitespace();
			if (jsonReader.pos != text.Length)
			{
				throw jsonReader.Error("trailing characters");
			}
			return result;
		}

		private object ReadValue()
		{
			SkipWhitespace();
			if (pos >= text.Length)
			{
				throw Error("unexpected end");
			}
			char c = text[pos];
			switch (c)
			{
			case '{':
				return ReadObject();
			case '[':
				return ReadArray();
			case '"':
				return ReadString();
			case 't':
				Expect("true");
				return true;
			case 'f':
				Expect("false");
				return false;
			case 'n':
				Expect("null");
				return null;
			default:
				switch (c)
				{
				case '-':
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
					return ReadNumber();
				default:
					throw Error($"unexpected '{c}'");
				}
			}
		}

		private Dictionary<string, object> ReadObject()
		{
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			pos++;
			SkipWhitespace();
			if (Peek() == '}')
			{
				pos++;
				return dictionary;
			}
			while (true)
			{
				SkipWhitespace();
				if (Peek() != '"')
				{
					throw Error("expected a key");
				}
				string key = ReadString();
				SkipWhitespace();
				if (Peek() != ':')
				{
					break;
				}
				pos++;
				dictionary[key] = ReadValue();
				SkipWhitespace();
				char c = Peek();
				pos++;
				switch (c)
				{
				case ',':
					break;
				case '}':
					return dictionary;
				default:
					throw Error("expected ',' or '}'");
				}
			}
			throw Error("expected ':'");
		}

		private List<object> ReadArray()
		{
			List<object> list = new List<object>();
			pos++;
			SkipWhitespace();
			if (Peek() == ']')
			{
				pos++;
				return list;
			}
			while (true)
			{
				list.Add(ReadValue());
				SkipWhitespace();
				char c = Peek();
				pos++;
				switch (c)
				{
				case ',':
					break;
				case ']':
					return list;
				default:
					throw Error("expected ',' or ']'");
				}
			}
		}

		private string ReadString()
		{
			pos++;
			StringBuilder stringBuilder = new StringBuilder();
			while (pos < text.Length)
			{
				char c = text[pos++];
				switch (c)
				{
				case '"':
					return stringBuilder.ToString();
				default:
					stringBuilder.Append(c);
					break;
				case '\\':
				{
					if (pos >= text.Length)
					{
						throw Error("unterminated escape");
					}
					char c2 = text[pos++];
					switch (c2)
					{
					case '"':
						stringBuilder.Append('"');
						break;
					case '\\':
						stringBuilder.Append('\\');
						break;
					case '/':
						stringBuilder.Append('/');
						break;
					case 'b':
						stringBuilder.Append('\b');
						break;
					case 'f':
						stringBuilder.Append('\f');
						break;
					case 'n':
						stringBuilder.Append('\n');
						break;
					case 'r':
						stringBuilder.Append('\r');
						break;
					case 't':
						stringBuilder.Append('\t');
						break;
					case 'u':
						if (pos + 4 > text.Length)
						{
							throw Error("short \\u escape");
						}
						stringBuilder.Append((char)int.Parse(text.Substring(pos, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
						pos += 4;
						break;
					default:
						throw Error($"bad escape '\\{c2}'");
					}
					break;
				}
				}
			}
			throw Error("unterminated string");
		}

		private double ReadNumber()
		{
			int num = pos;
			while (pos < this.text.Length && "+-0123456789.eE".IndexOf(this.text[pos]) >= 0)
			{
				pos++;
			}
			string text = this.text.Substring(num, pos - num);
			if (!double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				throw Error("bad number '" + text + "'");
			}
			return result;
		}

		private void Expect(string word)
		{
			if (string.CompareOrdinal(text, pos, word, 0, word.Length) != 0)
			{
				throw Error("expected '" + word + "'");
			}
			pos += word.Length;
		}

		private char Peek()
		{
			if (pos >= text.Length)
			{
				return '\0';
			}
			return text[pos];
		}

		private void SkipWhitespace()
		{
			while (pos < text.Length && char.IsWhiteSpace(text[pos]))
			{
				pos++;
			}
		}

		private FormatException Error(string what)
		{
			return new FormatException($"JSON: {what} at offset {pos}.");
		}
	}
	internal static class PowerupIds
	{
		public static int Resolve(IEnumerable<int> existingIds, bool nameExists, int existingId)
		{
			if (nameExists)
			{
				return existingId;
			}
			int num = 0;
			bool flag = false;
			foreach (int existingId2 in existingIds)
			{
				if (!flag || existingId2 > num)
				{
					num = existingId2;
					flag = true;
				}
			}
			if (!flag)
			{
				return 0;
			}
			return num + 1;
		}
	}
	internal enum MobKind
	{
		Hostile,
		Neutral
	}
	internal readonly struct Point
	{
		public readonly float X;

		public readonly float Y;

		public readonly float Z;

		public Point(float x, float y, float z)
		{
			X = x;
			Y = y;
			Z = z;
		}
	}
	internal readonly struct StickyBombTuning
	{
		public static readonly StickyBombTuning Default = new StickyBombTuning(5f, 5f, 180, 1.5f, 10f, hitsNeutral: false);

		public readonly float ChancePercent;

		public readonly float ChancePercentPerStack;

		public readonly int DamagePercent;

		public readonly float FuseSeconds;

		public readonly float Radius;

		public readonly bool HitsNeutral;

		public StickyBombTuning(float chancePercent, float chancePercentPerStack, int damagePercent, float fuseSeconds, float radius, bool hitsNeutral)
		{
			ChancePercent = Clamp(chancePercent, 0f, 100f);
			ChancePercentPerStack = Clamp(chancePercentPerStack, 0f, 100f);
			if (damagePercent < 0)
			{
				damagePercent = 0;
			}
			else if (damagePercent > 10000)
			{
				damagePercent = 10000;
			}
			DamagePercent = damagePercent;
			FuseSeconds = Clamp(fuseSeconds, 0f, 30f);
			Radius = Clamp(radius, 0f, 100f);
			HitsNeutral = hitsNeutral;
		}

		public string Description()
		{
			return FormattableString.Invariant($"{ChancePercent}% (+{ChancePercentPerStack}% per stack) chance on hit to attach a bomb to an enemy, detonating after {FuseSeconds}s for {DamagePercent}% TOTAL damage within {Radius}m.");
		}

		private static float Clamp(float value, float min, float max)
		{
			if (float.IsNaN(value) || value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}
	}
	internal readonly struct HitSnapshot
	{
		public readonly int WeaponType;

		public readonly int Damage;

		public readonly int Stacks;

		public readonly MobKind Carrier;

		public readonly bool DuringBlast;

		public HitSnapshot(int weaponType, int damage, int stacks, MobKind carrier, bool duringBlast)
		{
			WeaponType = weaponType;
			Damage = damage;
			Stacks = stacks;
			Carrier = carrier;
			DuringBlast = duringBlast;
		}
	}
	internal readonly struct BlastMob<T>
	{
		public readonly T Mob;

		public readonly Point At;

		public readonly bool Alive;

		public readonly MobKind Kind;

		public BlastMob(T mob, Point at, bool alive, MobKind kind)
		{
			Mob = mob;
			At = at;
			Alive = alive;
			Kind = kind;
		}
	}
	internal readonly struct Strike<T>
	{
		public readonly T Mob;

		public readonly int Damage;

		public Strike(T mob, int damage)
		{
			Mob = mob;
			Damage = damage;
		}
	}
	internal sealed class StickyBomb
	{
		public const int BlastWeaponType = -1;

		public const float RoughReachMargin = 30f;

		private const float SweetSpotFraction = 0.5f;

		private const int RimPercent = 25;

		private readonly StickyBombTuning _tuning;

		private readonly int _triggerDamage;

		private bool _spent;

		public float Radius => _tuning.Radius;

		private StickyBomb(StickyBombTuning tuning, int triggerDamage)
		{
			_tuning = tuning;
			_triggerDamage = triggerDamage;
		}

		public static bool TryArm(StickyBombTuning tuning, HitSnapshot hit, Func<float> roll, out StickyBomb bomb)
		{
			bomb = null;
			if (hit.DuringBlast || hit.WeaponType < 0 || hit.Damage <= 0 || hit.Stacks <= 0 || !Affects(tuning, hit.Carrier))
			{
				return false;
			}
			float num = ChancePercentFor(tuning, hit.Stacks);
			if (num < 100f && roll() >= num / 100f)
			{
				return false;
			}
			bomb = new StickyBomb(tuning, hit.Damage);
			return true;
		}

		public bool IsDue(float secondsSinceArmed)
		{
			return secondsSinceArmed >= _tuning.FuseSeconds;
		}

		public static bool FartherThanRoughReach(Point origin, Point center, float radius, float margin)
		{
			float num = radius + margin;
			return DistanceSqr(origin, center) > num * num;
		}

		public IReadOnlyList<Strike<T>> Detonate<T>(Point center, IReadOnlyList<BlastMob<T>> mobs)
		{
			if (_spent)
			{
				return Array.Empty<Strike<T>>();
			}
			_spent = true;
			List<Strike<T>> list = new List<Strike<T>>();
			for (int i = 0; i < mobs.Count; i++)
			{
				BlastMob<T> blastMob = mobs[i];
				if (blastMob.Alive && Affects(_tuning, blastMob.Kind) && TryDamageAt(DistanceSqr(center, blastMob.At), out var damage))
				{
					list.Add(new Strike<T>(blastMob.Mob, damage));
				}
			}
			return list;
		}

		private static float ChancePercentFor(StickyBombTuning tuning, int stacks)
		{
			if (stacks <= 0)
			{
				return 0f;
			}
			float num = tuning.ChancePercent + tuning.ChancePercentPerStack * (float)(stacks - 1);
			if (!(num > 100f))
			{
				return num;
			}
			return 100f;
		}

		private static bool Affects(StickyBombTuning tuning, MobKind kind)
		{
			return kind switch
			{
				MobKind.Hostile => true, 
				MobKind.Neutral => tuning.HitsNeutral, 
				_ => false, 
			};
		}

		private bool TryDamageAt(float distanceSqr, out int damage)
		{
			if (_tuning.DamagePercent == 0)
			{
				damage = 0;
				return false;
			}
			float radius = _tuning.Radius;
			float num = radius * 0.5f;
			if (distanceSqr <= num * num)
			{
				damage = RoundHalfEvenAtLeastOne((long)_triggerDamage * (long)_tuning.DamagePercent, 100L);
				return true;
			}
			if (distanceSqr <= radius * radius)
			{
				damage = RoundHalfEvenAtLeastOne((long)_triggerDamage * (long)_tuning.DamagePercent * 25, 10000L);
				return true;
			}
			damage = 0;
			return false;
		}

		private static int RoundHalfEvenAtLeastOne(long numerator, long denominator)
		{
			long num = numerator / denominator;
			long num2 = numerator % denominator * 2;
			if (num2 > denominator || (num2 == denominator && (num & 1) != 0L))
			{
				num++;
			}
			if (num < 1)
			{
				return 1;
			}
			if (num > int.MaxValue)
			{
				return int.MaxValue;
			}
			return (int)num;
		}

		private static float DistanceSqr(Point a, Point b)
		{
			float num = a.X - b.X;
			float num2 = a.Y - b.Y;
			float num3 = a.Z - b.Z;
			return num * num + num2 * num2 + num3 * num3;
		}
	}
	internal sealed class StickyBombConfig
	{
		public readonly ConfigEntry<float> ChancePercent;

		public readonly ConfigEntry<float> ChancePercentPerStack;

		public readonly ConfigEntry<int> DamagePercent;

		public readonly ConfigEntry<float> FuseSeconds;

		public readonly ConfigEntry<float> Radius;

		public readonly ConfigEntry<bool> HitNeutralMobs;

		public readonly ConfigEntry<bool> ShowBombs;

		public readonly ConfigEntry<KeyboardShortcut> GiveStickyBombKey;

		public readonly ConfigEntry<bool> VerboseLogging;

		public StickyBombConfig(ConfigFile cfg)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Expected O, but got Unknown
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			StickyBombTuning stickyBombTuning = StickyBombTuning.Default;
			ChancePercent = cfg.Bind<float>("StickyBomb", "ChancePercent", stickyBombTuning.ChancePercent, new ConfigDescription("Percent chance (0-100) that a hit sticks a bomb with one stack.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			ChancePercentPerStack = cfg.Bind<float>("StickyBomb", "ChancePercentPerStack", stickyBombTuning.ChancePercentPerStack, new ConfigDescription("Extra percent chance for each stack after the first (0-100). The total stops at 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			DamagePercent = cfg.Bind<int>("StickyBomb", "DamagePercent", stickyBombTuning.DamagePercent, new ConfigDescription("Percent of the triggering hit dealt inside half the radius (0-10000). Zero deals no blast damage. The rim uses this percent times 25, divided by 10000, with the bomb's half-even rounding.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10000), Array.Empty<object>()));
			FuseSeconds = cfg.Bind<float>("StickyBomb", "FuseSeconds", stickyBombTuning.FuseSeconds, new ConfigDescription("Seconds from sticking a bomb to the blast (0-30). The timer starts one frame after the hit, so zero still waits a frame.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>()));
			Radius = cfg.Bind<float>("StickyBomb", "Radius", stickyBombTuning.Radius, new ConfigDescription("Blast radius in meters (0-100). The stronger inner blast is the inner half of this distance.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			HitNeutralMobs = cfg.Bind<bool>("StickyBomb", "HitNeutralMobs", stickyBombTuning.HitsNeutral, "If true, bombs can stick to neutral animals and the blast can hurt them.");
			ShowBombs = cfg.Bind<bool>("Visuals", "ShowBombs", true, "Show a sphere on each stuck bomb. The sphere is only drawn on the attacker's screen. The blast still happens when this is off.");
			GiveStickyBombKey = cfg.Bind<KeyboardShortcut>("Debug", "GiveStickyBombKey", KeyboardShortcut.Empty, "Press in-game to give yourself one Sticky Bomb stack (local test helper). Empty = disabled.");
			VerboseLogging = cfg.Bind<bool>("Debug", "VerboseLogging", false, "Log every stuck bomb and detonation.");
			EventHandler eventHandler = delegate
			{
				RefreshCard();
			};
			ChancePercent.SettingChanged += eventHandler;
			ChancePercentPerStack.SettingChanged += eventHandler;
			DamagePercent.SettingChanged += eventHandler;
			FuseSeconds.SettingChanged += eventHandler;
			Radius.SettingChanged += eventHandler;
			HitNeutralMobs.SettingChanged += eventHandler;
		}

		private void RefreshCard()
		{
			Powerup definition = StickyBombPowerup.Definition;
			if ((Object)(object)definition != (Object)null)
			{
				definition.description = Tuning().Description();
			}
		}

		internal StickyBombTuning Tuning()
		{
			return new StickyBombTuning(ChancePercent.Value, ChancePercentPerStack.Value, DamagePercent.Value, FuseSeconds.Value, Radius.Value, HitNeutralMobs.Value);
		}
	}
	internal static class StickyBombHits
	{
		internal static bool IsDetonating;

		internal const int UndefinedMatchesBlast = 1;

		private const float MarkerDiameter = 0.45f;

		private static readonly Color MarkerColor = new Color(1f, 0.46f, 0.08f, 1f);

		private static readonly List<Collider> ColliderBuffer = new List<Collider>();

		private static Material _material;

		private static bool _shaderMissingLogged;

		private static readonly string[] ShaderCandidates = new string[6] { "Legacy Shaders/Particles/Additive", "Particles/Additive", "Particles/Standard Unlit", "Unlit/Color", "Sprites/Default", "Hidden/Internal-Colored" };

		internal static MobKind KindOf(Mob mob)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)mob != (Object)null && (Object)(object)mob.mobType != (Object)null && (int)mob.mobType.behaviour == 0)
			{
				return MobKind.Neutral;
			}
			return MobKind.Hostile;
		}

		internal static IEnumerator Fuse(HitableMob carrier, StickyBomb bomb)
		{
			yield return null;
			IEnumerator burn = Burn(carrier, bomb);
			try
			{
				while (burn.MoveNext())
				{
					yield return burn.Current;
				}
			}
			finally
			{
				IDisposable disposable = burn as IDisposable;
				if (disposable != null)
				{
					disposable.Dispose();
				}
			}
		}

		private static IEnumerator Burn(HitableMob carrier, StickyBomb bomb)
		{
			float armedAt = Time.time;
			Collider body = FirstSolid(carrier);
			Vector3 center = (((Object)(object)carrier != (Object)null) ? MarkerPoint(carrier, body) : Vector3.zero);
			GameObject marker = SpawnMarker(center);
			try
			{
				while (true)
				{
					if ((Object)(object)carrier != (Object)null)
					{
						center = MarkerPoint(carrier, body);
					}
					if ((Object)(object)marker != (Object)null)
					{
						marker.transform.position = center;
					}
					if (bomb.IsDue(Time.time - armedAt))
					{
						break;
					}
					yield return null;
				}
				if ((Object)(object)MobManager.Instance == (Object)null)
				{
					if (StickyBombPlugin.Cfg.VerboseLogging.Value)
					{
						StickyBombPlugin.Log.LogInfo((object)"Sticky bomb fuse ended without a blast because the mob list is gone.");
					}
				}
				else
				{
					Apply(bomb.Detonate(ToPoint(center), SnapshotMobs(center, bomb.Radius)));
				}
			}
			finally
			{
				if ((Object)(object)marker != (Object)null)
				{
					Object.Destroy((Object)(object)marker);
				}
			}
		}

		private static void Apply(IReadOnlyList<Strike<HitableMob>> strikes)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			if (StickyBombPlugin.Cfg.VerboseLogging.Value)
			{
				StickyBombPlugin.Log.LogInfo((object)$"Sticky bomb detonated. {strikes.Count} strikes.");
			}
			IsDetonating = true;
			try
			{
				for (int i = 0; i < strikes.Count; i++)
				{
					Strike<HitableMob> strike = strikes[i];
					HitableMob mob = strike.Mob;
					if (!((Object)(object)mob == (Object)null))
					{
						((Hitable)mob).Hit(strike.Damage, 0f, 0, AimPoint(mob), -1);
					}
				}
			}
			finally
			{
				IsDetonating = false;
			}
		}

		private static List<BlastMob<HitableMob>> SnapshotMobs(Vector3 center, float radius)
		{
			//IL_0016: 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_0072: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<int, Mob> mobs = MobManager.Instance.mobs;
			List<BlastMob<HitableMob>> list = new List<BlastMob<HitableMob>>();
			if (mobs == null)
			{
				return list;
			}
			Point center2 = ToPoint(center);
			foreach (Mob value in mobs.Values)
			{
				if (!((Object)(object)value == (Object)null) && !StickyBomb.FartherThanRoughReach(ToPoint(((Component)value).transform.position), center2, radius, 30f))
				{
					HitableMob component = ((Component)value).GetComponent<HitableMob>();
					if (!((Object)(object)component == (Object)null))
					{
						Vector3 v = ClosestPoint(component, center);
						bool alive = ((Hitable)component).hp > 0;
						list.Add(new BlastMob<HitableMob>(component, ToPoint(v), alive, KindOf(value)));
					}
				}
			}
			return list;
		}

		private static Vector3 ClosestPoint(HitableMob mob, Vector3 center)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: 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_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)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			((Component)mob).GetComponentsInChildren<Collider>(false, ColliderBuffer);
			bool flag = false;
			Vector3 result = ((Component)mob).transform.position + Vector3.up;
			float num = float.MaxValue;
			foreach (Collider item in ColliderBuffer)
			{
				if (!((Object)(object)item == (Object)null) && item.enabled && !item.isTrigger)
				{
					Vector3 val = item.ClosestPoint(center);
					Vector3 val2 = val - center;
					float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
					if (!flag || sqrMagnitude < num)
					{
						flag = true;
						result = val;
						num = sqrMagnitude;
					}
				}
			}
			return result;
		}

		private static Collider FirstSolid(HitableMob mob)
		{
			if ((Object)(object)mob == (Object)null)
			{
				return null;
			}
			((Component)mob).GetComponentsInChildren<Collider>(false, ColliderBuffer);
			foreach (Collider item in ColliderBuffer)
			{
				if ((Object)(object)item != (Object)null && item.enabled && !item.isTrigger)
				{
					return item;
				}
			}
			return null;
		}

		private static Vector3 MarkerPoint(HitableMob mob, Collider body)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)body != (Object)null)
			{
				Bounds bounds = body.bounds;
				return ((Bounds)(ref bounds)).center;
			}
			return ((Component)mob).transform.position + Vector3.up;
		}

		private static Vector3 AimPoint(HitableMob mob)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			Collider body = FirstSolid(mob);
			return MarkerPoint(mob, body);
		}

		private static Point ToPoint(Vector3 v)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return new Point(v.x, v.y, v.z);
		}

		private static GameObject SpawnMarker(Vector3 center)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			if (!StickyBombPlugin.Cfg.ShowBombs.Value)
			{
				return null;
			}
			Material val = MarkerMaterial();
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)0);
			((Object)obj).name = "StickyBomb";
			Collider component = obj.GetComponent<Collider>();
			if ((Object)(object)component != (Object)null)
			{
				component.enabled = false;
				Object.Destroy((Object)(object)component);
			}
			obj.transform.position = center;
			obj.transform.localScale = Vector3.one * 0.45f;
			MeshRenderer component2 = obj.GetComponent<MeshRenderer>();
			if ((Object)(object)component2 != (Object)null)
			{
				((Renderer)component2).sharedMaterial = val;
				((Renderer)component2).shadowCastingMode = (ShadowCastingMode)0;
				((Renderer)component2).receiveShadows = false;
			}
			return obj;
		}

		private static Material MarkerMaterial()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_material != (Object)null)
			{
				return _material;
			}
			string[] shaderCandidates = ShaderCandidates;
			foreach (string text in shaderCandidates)
			{
				Shader val = Shader.Find(text);
				if (!((Object)(object)val == (Object)null))
				{
					_material = new Material(val)
					{
						name = "StickyBombMarker",
						hideFlags = (HideFlags)32
					};
					if (_material.HasProperty("_MainTex"))
					{
						_material.mainTexture = (Texture)(object)Texture2D.whiteTexture;
					}
					if (_material.HasProperty("_Color"))
					{
						_material.color = MarkerColor;
					}
					StickyBombPlugin.Log.LogInfo((object)("Sticky bomb markers use shader '" + text + "'."));
					return _material;
				}
			}
			if (!_shaderMissingLogged)
			{
				_shaderMissingLogged = true;
				StickyBombPlugin.Log.LogWarning((object)"No usable built-in shader found for sticky bomb markers. The blast still happens.");
			}
			return null;
		}
	}
	[BepInPlugin("evan.muck.stickybomb", "Sticky Bomb", "0.1.1")]
	public class StickyBombPlugin : BaseUnityPlugin
	{
		public const string Guid = "evan.muck.stickybomb";

		public const string Name = "Sticky Bomb";

		public const string Version = "0.1.1";

		internal static ManualLogSource Log;

		internal static StickyBombConfig Cfg;

		private void Awake()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Cfg = new StickyBombConfig(((BaseUnityPlugin)this).Config);
			Harmony harmony = new Harmony("evan.muck.stickybomb");
			if (!TryPatch(harmony, typeof(HitableMobHitPatch)))
			{
				Log.LogError((object)"Sticky Bomb did not register. The hit patch failed, so the powerup will not drop.");
				return;
			}
			if (!TryPatch(harmony, typeof(RegisterStickyBombPatch)))
			{
				Log.LogError((object)"Sticky Bomb patched hits, but registration failed. The powerup will not drop.");
				return;
			}
			StickyBombPowerup.Create();
			StickyBombRunner.Ensure();
			Log.LogInfo((object)"Sticky Bomb 0.1.1 loaded. Every player needs this mod, the same other powerup mods, and the same gameplay config.");
		}

		private static bool TryPatch(Harmony harmony, Type patchClass)
		{
			try
			{
				harmony.CreateClassProcessor(patchClass).Patch();
				return true;
			}
			catch (Exception arg)
			{
				Log.LogError((object)string.Format("{0} failed to patch {1}: {2}", "Sticky Bomb", patchClass.Name, arg));
				return false;
			}
		}
	}
	internal static class StickyBombPowerup
	{
		public const string PowerupName = "Sticky Bomb";

		private static readonly FieldRef<PowerupInventory, int[]> PowerupCounts = AccessTools.FieldRefAccess<PowerupInventory, int[]>("powerups");

		public static Powerup Definition { get; private set; }

		public static int Id { get; internal set; } = -1;

		public static void Create()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			Powerup obj = ScriptableObject.CreateInstance<Powerup>();
			obj.name = "Sticky Bomb";
			((Object)obj).name = "Sticky Bomb";
			obj.description = StickyBombPlugin.Cfg.Tuning().Description();
			obj.tier = (PowerTier)1;
			obj.sprite = LoadIcon();
			((Object)obj).hideFlags = (HideFlags)32;
			Definition = obj;
		}

		public static int LocalStacks()
		{
			PowerupInventory instance = PowerupInventory.Instance;
			if ((Object)(object)instance == (Object)null || Id < 0)
			{
				return 0;
			}
			int[] array = PowerupCounts.Invoke(instance);
			if (array == null || Id >= array.Length)
			{
				return 0;
			}
			return array[Id];
		}

		public static void GiveOneLocal()
		{
			PowerupInventory instance = PowerupInventory.Instance;
			int[] array = (((Object)(object)instance != (Object)null) ? PowerupCounts.Invoke(instance) : null);
			if (array == null || Id < 0 || Id >= array.Length)
			{
				StickyBombPlugin.Log.LogWarning((object)"Can't give Sticky Bomb: not in a game yet, or the powerup isn't registered.");
				return;
			}
			if ((Object)(object)PowerupUI.Instance == (Object)null || (Object)(object)PlayerStatus.Instance == (Object)null)
			{
				StickyBombPlugin.Log.LogWarning((object)"Can't give Sticky Bomb: the powerup bar or the player status is not ready.");
				return;
			}
			array[Id]++;
			PowerupUI.Instance.AddPowerup(Id);
			PlayerStatus.Instance.UpdateStats();
			StickyBombPlugin.Log.LogInfo((object)$"Debug: Sticky Bomb stacks now {array[Id]} (local only; the host's copy of your powerups is not updated).");
		}

		private static Sprite LoadIcon()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				using Stream stream = typeof(StickyBombPowerup).Assembly.GetManifestResourceStream("MuckStickyBomb.icon.png");
				if (stream == null)
				{
					throw new FileNotFoundException("embedded icon.png missing");
				}
				using MemoryStream memoryStream = new MemoryStream();
				stream.CopyTo(memoryStream);
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, memoryStream.ToArray()))
				{
					throw new InvalidDataException("icon.png failed to decode");
				}
				((Object)val).name = "StickyBombIcon";
				((Object)val).hideFlags = (HideFlags)32;
				Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
				((Object)obj).name = "StickyBombIcon";
				((Object)obj).hideFlags = (HideFlags)32;
				return obj;
			}
			catch (Exception arg)
			{
				StickyBombPlugin.Log.LogError((object)$"Failed to load Sticky Bomb icon: {arg}");
				return null;
			}
		}
	}
	[HarmonyPatch(typeof(ItemManager), "InitAllPowerups")]
	internal static class RegisterStickyBombPatch
	{
		[HarmonyPriority(600)]
		[HarmonyAfter(new string[] { "evan.muck.ukulele", "evan.muck.atgmissile", "evan.muck.crowbar" })]
		private static void Postfix(ItemManager __instance)
		{
			Powerup definition = StickyBombPowerup.Definition;
			if ((Object)(object)definition == (Object)null)
			{
				return;
			}
			Dictionary<int, Powerup> allPowerups = __instance.allPowerups;
			Dictionary<string, int> stringToPowerupId = __instance.stringToPowerupId;
			PickupArt.Apply(definition, __instance.powerupsBlue);
			int value;
			bool flag = stringToPowerupId.TryGetValue("Sticky Bomb", out value);
			int num = PowerupIds.Resolve(allPowerups.Keys, flag, value);
			if (!flag)
			{
				allPowerups.Add(num, definition);
				stringToPowerupId.Add("Sticky Bomb", num);
				definition.id = num;
			}
			if (!__instance.powerupsBlue.Contains(definition))
			{
				__instance.powerupsBlue = CollectionExtensions.AddToArray<Powerup>(__instance.powerupsBlue, definition);
			}
			StickyBombPowerup.Id = num;
			StickyBombPlugin.Log.LogInfo((object)$"Registered Sticky Bomb as Blue powerup id {num} ({allPowerups.Count} powerups total, {__instance.powerupsBlue.Length} in the Blue pool).");
			if (StickyBombPlugin.Cfg.VerboseLogging.Value)
			{
				StickyBombPlugin.Log.LogInfo((object)("Powerup ids: " + string.Join(", ", from kv in allPowerups
					orderby kv.Key
					select $"{kv.Key}={kv.Value.name}")));
			}
		}
	}
	internal sealed class StickyBombRunner : MonoBehaviour
	{
		private static StickyBombRunner _instance;

		public static StickyBombRunner Instance
		{
			get
			{
				Ensure();
				return _instance;
			}
		}

		public static void Ensure()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			if (!((Object)(object)_instance != (Object)null))
			{
				GameObject val = new GameObject("MuckStickyBomb")
				{
					hideFlags = (HideFlags)61
				};
				Object.DontDestroyOnLoad((Object)val);
				_instance = val.AddComponent<StickyBombRunner>();
			}
		}

		private void Update()
		{
			//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)
			KeyboardShortcut value = StickyBombPlugin.Cfg.GiveStickyBombKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				StickyBombPowerup.GiveOneLocal();
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "MuckStickyBomb";

		public const string PLUGIN_NAME = "Sticky Bomb";

		public const string PLUGIN_VERSION = "0.1.1";
	}
}