Decompiled source of Ukulele v0.1.2

plugins/MuckUkulele.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("MuckUkulele")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Adds Risk of Rain 2's Ukulele (chain lightning on hit) to Muck as a Blue powerup.")]
[assembly: AssemblyFileVersion("0.1.2.0")]
[assembly: AssemblyInformationalVersion("0.1.2+879fc7ac66fec639f2f84b4b7a65d5c61c9ed734")]
[assembly: AssemblyProduct("Ukulele")]
[assembly: AssemblyTitle("MuckUkulele")]
[assembly: InternalsVisibleTo("MuckUkulele.Tests")]
[assembly: AssemblyVersion("0.1.2.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
}
namespace MuckUkulele
{
	internal static class ChainLightning
	{
		internal static bool IsFiring;

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

		public static void Fire(HitableMob origin, int hitDamage, int stacks)
		{
			UkuleleConfig cfg = UkulelePlugin.Cfg;
			StackScaling stackScaling = cfg.Scaling();
			int num = stackScaling.TargetsFor(stacks);
			float num2 = stackScaling.RangeFor(stacks);
			int num3 = stackScaling.DamageFor(hitDamage, stacks);
			if (cfg.VerboseLogging.Value)
			{
				int num4 = StackScaling.RoundToInt(stackScaling.FractionFor(stacks) * 100f);
				UkulelePlugin.Log.LogInfo((object)$"Ukulele proc: hit {hitDamage} -> {num3} dmg ({num4}% at {stacks} stacks), {num} jumps, {num2:0.#}m.");
			}
			((MonoBehaviour)UkuleleRunner.Instance).StartCoroutine(Run(origin, num3, num, num2, cfg.HopDelay.Value));
		}

		private static IEnumerator Run(HitableMob origin, int damage, int targets, float range, float hopDelay)
		{
			HashSet<HitableMob> visited = new HashSet<HitableMob> { origin };
			Vector3 from = AimPoint(origin);
			WaitForSeconds wait = ((!(hopDelay > 0f)) ? ((WaitForSeconds)null) : new WaitForSeconds(hopDelay));
			Strike(origin, damage, from);
			if (UkulelePlugin.Cfg.VerboseLogging.Value)
			{
				UkulelePlugin.Log.LogInfo((object)$"Ukulele primary: {((Object)origin).name} took {damage} lightning dmg");
			}
			if (targets <= 0)
			{
				yield break;
			}
			for (int jump = 0; jump < targets; jump++)
			{
				HitableMob val = FindNearest(from, range, visited);
				if ((Object)(object)val == (Object)null)
				{
					if (UkulelePlugin.Cfg.VerboseLogging.Value)
					{
						UkulelePlugin.Log.LogInfo((object)$"Ukulele jump: no target within {range:0.#}m.");
					}
					break;
				}
				Vector3 val2 = AimPoint(val);
				visited.Add(val);
				Strike(val, damage, val2);
				if (UkulelePlugin.Cfg.ShowBolts.Value)
				{
					LightningBolt.Spawn(from, val2);
				}
				if (UkulelePlugin.Cfg.VerboseLogging.Value)
				{
					UkulelePlugin.Log.LogInfo((object)$"Ukulele jump {jump + 1}/{targets}: {((Object)val).name} ({Vector3.Distance(from, val2):0.0}m)");
				}
				from = val2;
				if (wait != null)
				{
					yield return wait;
				}
			}
		}

		private static void Strike(HitableMob target, int damage, Vector3 point)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			IsFiring = true;
			try
			{
				((Hitable)target).Hit(damage, 0f, 3, point, -1);
			}
			finally
			{
				IsFiring = false;
			}
		}

		private static HitableMob FindNearest(Vector3 from, float range, HashSet<HitableMob> visited)
		{
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Invalid comparison between Unknown and I4
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<int, Mob> dictionary = (((Object)(object)MobManager.Instance != (Object)null) ? MobManager.Instance.mobs : null);
			if (dictionary == null)
			{
				return null;
			}
			bool value = UkulelePlugin.Cfg.HitNeutralMobs.Value;
			List<ChainMob> list = new List<ChainMob>(dictionary.Count);
			List<HitableMob> list2 = new List<HitableMob>(dictionary.Count);
			foreach (Mob value2 in dictionary.Values)
			{
				if (!((Object)(object)value2 == (Object)null))
				{
					HitableMob component = ((Component)value2).GetComponent<HitableMob>();
					if (!((Object)(object)component == (Object)null))
					{
						Vector3 val = AimPoint(component);
						bool neutral = (Object)(object)value2.mobType != (Object)null && (int)value2.mobType.behaviour == 0;
						list.Add(new ChainMob(val.x, val.y, val.z, ((Hitable)component).hp > 0, neutral, visited.Contains(component)));
						list2.Add(component);
					}
				}
			}
			int num = ChainPlan.Next(list, from.x, from.y, from.z, range, value);
			if (num >= 0)
			{
				return list2[num];
			}
			return null;
		}

		private static Vector3 AimPoint(HitableMob mob)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_007a: Unknown result type (might be due to invalid IL or missing references)
			((Component)mob).GetComponentsInChildren<Collider>(false, ColliderBuffer);
			foreach (Collider item in ColliderBuffer)
			{
				if ((Object)(object)item != (Object)null && item.enabled && !item.isTrigger)
				{
					Bounds bounds = item.bounds;
					return ((Bounds)(ref bounds)).center;
				}
			}
			return ((Component)mob).transform.position + Vector3.up;
		}
	}
	internal readonly struct ChainMob
	{
		public readonly float X;

		public readonly float Y;

		public readonly float Z;

		public readonly bool Alive;

		public readonly bool Neutral;

		public readonly bool Visited;

		public ChainMob(float x, float y, float z, bool alive, bool neutral, bool visited)
		{
			X = x;
			Y = y;
			Z = z;
			Alive = alive;
			Neutral = neutral;
			Visited = visited;
		}
	}
	internal static class ChainPlan
	{
		public static int Next(IReadOnlyList<ChainMob> mobs, float fromX, float fromY, float fromZ, float range, bool hitNeutral)
		{
			if (mobs.Count == 0)
			{
				return -1;
			}
			float num = range * range;
			int result = -1;
			for (int i = 0; i < mobs.Count; i++)
			{
				ChainMob chainMob = mobs[i];
				if (!chainMob.Visited && chainMob.Alive && (!chainMob.Neutral || hitNeutral))
				{
					float num2 = chainMob.X - fromX;
					float num3 = chainMob.Y - fromY;
					float num4 = chainMob.Z - fromZ;
					float num5 = num2 * num2 + num3 * num3 + num4 * num4;
					if (num5 <= num)
					{
						num = num5;
						result = i;
					}
				}
			}
			return result;
		}
	}
	[HarmonyPatch(typeof(HitableMob), "Hit")]
	internal static class HitableMobHitPatch
	{
		private static void Postfix(HitableMob __instance, int __0, int __4)
		{
			try
			{
				if (ProcGate.CanConsider(ChainLightning.IsFiring, __4, __0, (Object)(object)__instance != (Object)null))
				{
					int num = UkulelePowerup.LocalStacks();
					if (num > 0 && ProcGate.Allows(num, Random.value, UkulelePlugin.Cfg.ProcChance.Value))
					{
						ChainLightning.Fire(__instance, __0, num);
					}
				}
			}
			catch (Exception arg)
			{
				UkulelePlugin.Log.LogError((object)$"Ukulele on-hit failed: {arg}");
			}
		}
	}
	internal sealed class LightningBolt : MonoBehaviour
	{
		private const int Segments = 10;

		private const float JitterInterval = 0.035f;

		private static Material _material;

		private static bool _materialMissingLogged;

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

		private LineRenderer _line;

		private Light _flash;

		private Vector3 _from;

		private Vector3 _to;

		private Color _color;

		private float _life;

		private float _age;

		private float _nextJitter;

		public static void Spawn(Vector3 from, Vector3 to)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: 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_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: 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_013b: Unknown result type (might be due to invalid IL or missing references)
			Material material = GetMaterial();
			if (!((Object)(object)material == (Object)null))
			{
				UkuleleConfig cfg = UkulelePlugin.Cfg;
				GameObject val = new GameObject("UkuleleBolt");
				LightningBolt lightningBolt = val.AddComponent<LightningBolt>();
				lightningBolt._from = from;
				lightningBolt._to = to;
				lightningBolt._color = cfg.BoltColor.Value;
				lightningBolt._life = cfg.BoltDuration.Value;
				LineRenderer val2 = val.AddComponent<LineRenderer>();
				((Renderer)val2).sharedMaterial = material;
				val2.useWorldSpace = true;
				val2.positionCount = 11;
				val2.numCapVertices = 4;
				val2.numCornerVertices = 4;
				val2.alignment = (LineAlignment)0;
				val2.textureMode = (LineTextureMode)0;
				((Renderer)val2).shadowCastingMode = (ShadowCastingMode)0;
				((Renderer)val2).receiveShadows = false;
				val2.widthCurve = new AnimationCurve((Keyframe[])(object)new Keyframe[2]
				{
					new Keyframe(0f, cfg.BoltWidth.Value),
					new Keyframe(1f, cfg.BoltWidth.Value * 0.35f)
				});
				lightningBolt._line = val2;
				GameObject val3 = new GameObject("UkuleleFlash");
				val3.transform.SetParent(val.transform, false);
				val3.transform.position = to;
				Light val4 = val3.AddComponent<Light>();
				val4.type = (LightType)2;
				val4.color = lightningBolt._color;
				val4.range = 14f;
				val4.intensity = 8f;
				val4.shadows = (LightShadows)0;
				lightningBolt._flash = val4;
				lightningBolt.Jitter();
				lightningBolt.ApplyFade();
			}
		}

		private void Update()
		{
			_age += Time.deltaTime;
			if (_age >= _life)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
				return;
			}
			if (_age >= _nextJitter)
			{
				Jitter();
			}
			ApplyFade();
		}

		private void Jitter()
		{
			//IL_0013: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: 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_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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)
			_nextJitter = _age + 0.035f;
			float num = Mathf.Clamp(Vector3.Distance(_from, _to) * 0.06f, 0.15f, 0.8f);
			for (int i = 0; i <= 10; i++)
			{
				float num2 = (float)i / 10f;
				Vector3 val = Vector3.Lerp(_from, _to, num2);
				if (i > 0 && i < 10)
				{
					val += Random.insideUnitSphere * num * Mathf.Sin(num2 * MathF.PI);
				}
				_line.SetPosition(i, val);
			}
		}

		private void ApplyFade()
		{
			//IL_005a: 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)
			float num = 1f - Mathf.Clamp01(_age / _life);
			Color val = default(Color);
			((Color)(ref val))..ctor(_color.r * 4f, _color.g * 4f, _color.b * 4f, num);
			_line.startColor = val;
			_line.endColor = val;
			if ((Object)(object)_flash != (Object)null)
			{
				_flash.intensity = 8f * num;
			}
		}

		private static Material GetMaterial()
		{
			//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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			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 = "UkuleleBolt",
						hideFlags = (HideFlags)32
					};
					if (_material.HasProperty("_MainTex"))
					{
						_material.mainTexture = (Texture)(object)Texture2D.whiteTexture;
					}
					UkulelePlugin.Log.LogInfo((object)("Lightning bolts use shader '" + text + "'."));
					return _material;
				}
			}
			if (!_materialMissingLogged)
			{
				_materialMissingLogged = true;
				UkulelePlugin.Log.LogWarning((object)"No usable built-in shader found for lightning bolts; bolts are disabled (damage still works).");
			}
			return null;
		}
	}
	internal static class PickupArt
	{
		public const string ObjResource = "MuckUkulele.pickup.obj";

		public const string JsonResource = "MuckUkulele.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("MuckUkulele.pickup.obj"), Read("MuckUkulele.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)
			{
				UkulelePlugin.Log.LogWarning((object)("Ukulele 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
				{
					UkulelePlugin.Log.LogWarning((object)"No Blue powerup to borrow a pickup model from; dropped Ukuleles 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 string Fingerprint(IEnumerable<KeyValuePair<int, string>> entries)
		{
			List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
			if (entries != null)
			{
				foreach (KeyValuePair<int, string> entry in entries)
				{
					list.Add(entry);
				}
			}
			list.Sort((KeyValuePair<int, string> a, KeyValuePair<int, string> b) => a.Key.CompareTo(b.Key));
			if (list.Count == 0)
			{
				return "";
			}
			string[] array = new string[list.Count];
			for (int num = 0; num < list.Count; num++)
			{
				array[num] = list[num].Key + "=" + list[num].Value;
			}
			return string.Join(", ", array);
		}

		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 static class ProcGate
	{
		public static bool CanConsider(bool alreadyFiring, int weaponType, int damage, bool hasTarget)
		{
			return !alreadyFiring && weaponType >= 0 && damage > 0 && hasTarget;
		}

		public static bool Allows(int stacks, float roll, float procChance)
		{
			if (stacks > 0)
			{
				return roll < procChance;
			}
			return false;
		}
	}
	internal readonly struct StackScaling
	{
		public readonly float ProcChance;

		public readonly float DamageFraction;

		public readonly float DamageFractionPerStack;

		public readonly int BaseTargets;

		public readonly int TargetsPerStack;

		public readonly int MaxTargets;

		public readonly float BaseRange;

		public readonly float RangePerStack;

		public StackScaling(float procChance, float damageFraction, float damageFractionPerStack, int baseTargets, int targetsPerStack, int maxTargets, float baseRange, float rangePerStack)
		{
			ProcChance = procChance;
			DamageFraction = damageFraction;
			DamageFractionPerStack = damageFractionPerStack;
			BaseTargets = baseTargets;
			TargetsPerStack = targetsPerStack;
			MaxTargets = maxTargets;
			BaseRange = baseRange;
			RangePerStack = rangePerStack;
		}

		public int TargetsFor(int stacks)
		{
			int num = BaseTargets + TargetsPerStack * (stacks - 1);
			if (MaxTargets > 0)
			{
				num = Math.Min(num, MaxTargets);
			}
			return Math.Max(0, num);
		}

		public float RangeFor(int stacks)
		{
			return Math.Max(0f, BaseRange + RangePerStack * (float)(stacks - 1));
		}

		public float FractionFor(int stacks)
		{
			return Math.Max(0f, DamageFraction + DamageFractionPerStack * (float)(stacks - 1));
		}

		public int DamageFor(int hitDamage, int stacks)
		{
			return Math.Max(1, RoundToInt((float)hitDamage * FractionFor(stacks)));
		}

		public string Description()
		{
			return $"{RoundToInt(ProcChance * 100f)}% chance on hit to fire chain lightning for " + $"{RoundToInt(DamageFraction * 100f)}% (+{RoundToInt(DamageFractionPerStack * 100f)}% per stack) damage to up to {BaseTargets} (+{TargetsPerStack} per stack) " + $"enemies within {BaseRange:0.#}m (+{RangePerStack:0.#}m per stack).";
		}

		internal static int RoundToInt(float value)
		{
			return (int)Math.Round(value, MidpointRounding.ToEven);
		}
	}
	internal sealed class UkuleleConfig
	{
		public readonly ConfigEntry<float> ProcChance;

		public readonly ConfigEntry<float> DamageFraction;

		public readonly ConfigEntry<float> DamageFractionPerStack;

		public readonly ConfigEntry<int> BaseTargets;

		public readonly ConfigEntry<int> TargetsPerStack;

		public readonly ConfigEntry<int> MaxTargets;

		public readonly ConfigEntry<float> BaseRange;

		public readonly ConfigEntry<float> RangePerStack;

		public readonly ConfigEntry<float> HopDelay;

		public readonly ConfigEntry<bool> HitNeutralMobs;

		public readonly ConfigEntry<bool> ShowBolts;

		public readonly ConfigEntry<float> BoltDuration;

		public readonly ConfigEntry<float> BoltWidth;

		public readonly ConfigEntry<Color> BoltColor;

		public readonly ConfigEntry<KeyboardShortcut> GiveUkuleleKey;

		public readonly ConfigEntry<bool> VerboseLogging;

		public UkuleleConfig(ConfigFile cfg)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Expected O, but got Unknown
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Expected O, but got Unknown
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Expected O, but got Unknown
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Expected O, but got Unknown
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Expected O, but got Unknown
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			ProcChance = cfg.Bind<float>("Ukulele", "ProcChance", 0.25f, new ConfigDescription("Chance (0-1) that a melee, arrow, or thrown-rock hit on a mob fires chain lightning. Does not scale with stacks.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			DamageFraction = cfg.Bind<float>("Ukulele", "DamageFraction", 0.8f, new ConfigDescription("Lightning damage per target, as a fraction of the triggering hit, with 1 stack (before the target's armor). Minimum 1 damage.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>()));
			DamageFractionPerStack = cfg.Bind<float>("Ukulele", "DamageFractionPerStack", 0.2f, new ConfigDescription("Extra fraction of the triggering hit added per stack after the first. 0.2 with DamageFraction 0.8 is 80%, 100%, 120% at 1, 2, and 3 stacks.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>()));
			BaseTargets = cfg.Bind<int>("Ukulele", "BaseTargets", 3, new ConfigDescription("Number of extra enemies the lightning jumps to with 1 stack. The enemy you hit takes the lightning damage once and is not counted as a jump.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			TargetsPerStack = cfg.Bind<int>("Ukulele", "TargetsPerStack", 2, new ConfigDescription("Extra targets per additional stack.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			MaxTargets = cfg.Bind<int>("Ukulele", "MaxTargets", 0, new ConfigDescription("Hard cap on targets per proc. 0 = no cap.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 500), Array.Empty<object>()));
			BaseRange = cfg.Bind<float>("Ukulele", "BaseRange", 12f, new ConfigDescription("Maximum jump distance in meters with 1 stack. (RoR2 uses 20m, which feels huge at Muck's scale.)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 200f), Array.Empty<object>()));
			RangePerStack = cfg.Bind<float>("Ukulele", "RangePerStack", 2f, new ConfigDescription("Extra jump distance in meters per additional stack.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 50f), Array.Empty<object>()));
			HopDelay = cfg.Bind<float>("Ukulele", "HopDelay", 0.08f, new ConfigDescription("Seconds between jumps. 0 = all jumps land on the same frame.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			HitNeutralMobs = cfg.Bind<bool>("Ukulele", "HitNeutralMobs", false, "If true, lightning can also jump to neutral animals (cows, etc).");
			ShowBolts = cfg.Bind<bool>("Visuals", "ShowBolts", true, "Draw a lightning bolt between targets. Bolts are only drawn on the attacker's screen.");
			BoltDuration = cfg.Bind<float>("Visuals", "BoltDuration", 0.8f, new ConfigDescription("Seconds each bolt stays visible.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.02f, 2f), Array.Empty<object>()));
			BoltWidth = cfg.Bind<float>("Visuals", "BoltWidth", 1.5f, new ConfigDescription("Bolt thickness in meters.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 2f), Array.Empty<object>()));
			BoltColor = cfg.Bind<Color>("Visuals", "BoltColor", new Color(0.55f, 0.85f, 1f, 1f), "Bolt color.");
			GiveUkuleleKey = cfg.Bind<KeyboardShortcut>("Debug", "GiveUkuleleKey", KeyboardShortcut.Empty, "Press in-game to give yourself one Ukulele stack (local test helper; e.g. F8). Empty = disabled.");
			VerboseLogging = cfg.Bind<bool>("Debug", "VerboseLogging", false, "Log every proc and jump.");
		}

		public StackScaling Scaling()
		{
			return new StackScaling(ProcChance.Value, DamageFraction.Value, DamageFractionPerStack.Value, BaseTargets.Value, TargetsPerStack.Value, MaxTargets.Value, BaseRange.Value, RangePerStack.Value);
		}
	}
	[BepInPlugin("evan.muck.ukulele", "Ukulele", "0.1.2")]
	public class UkulelePlugin : BaseUnityPlugin
	{
		public const string Guid = "evan.muck.ukulele";

		public const string Name = "Ukulele";

		public const string Version = "0.1.2";

		internal static ManualLogSource Log;

		internal static UkuleleConfig 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 UkuleleConfig(((BaseUnityPlugin)this).Config);
			Harmony harmony = new Harmony("evan.muck.ukulele");
			if (!TryPatch(harmony, typeof(HitableMobHitPatch)))
			{
				Log.LogError((object)"Ukulele did not register. The hit patch failed, so the powerup will not drop.");
				return;
			}
			if (!TryPatch(harmony, typeof(RegisterUkulelePatch)))
			{
				Log.LogError((object)"Ukulele patched hits, but registration failed. The powerup will not drop.");
				return;
			}
			UkulelePowerup.Create();
			UkuleleRunner.Ensure();
			Log.LogInfo((object)"Ukulele 0.1.2 loaded. Every player needs the same set of 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}", "Ukulele", patchClass.Name, arg));
				return false;
			}
		}
	}
	internal static class UkulelePowerup
	{
		public const string PowerupName = "Ukulele";

		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 = "Ukulele";
			((Object)obj).name = "Ukulele";
			obj.description = UkulelePlugin.Cfg.Scaling().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)
			{
				UkulelePlugin.Log.LogWarning((object)"Can't give Ukulele: not in a game yet, or the powerup isn't registered.");
				return;
			}
			array[Id]++;
			PowerupUI.Instance.AddPowerup(Id);
			PlayerStatus.Instance.UpdateStats();
			UkulelePlugin.Log.LogInfo((object)$"Debug: Ukulele 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(UkulelePowerup).Assembly.GetManifestResourceStream("MuckUkulele.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 = "UkuleleIcon";
				((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 = "UkuleleIcon";
				((Object)obj).hideFlags = (HideFlags)32;
				return obj;
			}
			catch (Exception arg)
			{
				UkulelePlugin.Log.LogError((object)$"Failed to load Ukulele icon: {arg}");
				return null;
			}
		}
	}
	[HarmonyPatch(typeof(ItemManager), "InitAllPowerups")]
	internal static class RegisterUkulelePatch
	{
		[HarmonyPriority(600)]
		private static void Postfix(ItemManager __instance)
		{
			Powerup definition = UkulelePowerup.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("Ukulele", out value);
			int num = PowerupIds.Resolve(allPowerups.Keys, flag, value);
			if (!flag)
			{
				allPowerups.Add(num, definition);
				stringToPowerupId.Add("Ukulele", num);
				definition.id = num;
			}
			if (!__instance.powerupsBlue.Contains(definition))
			{
				__instance.powerupsBlue = CollectionExtensions.AddToArray<Powerup>(__instance.powerupsBlue, definition);
			}
			UkulelePowerup.Id = num;
			List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>(allPowerups.Count);
			foreach (KeyValuePair<int, Powerup> item in allPowerups)
			{
				list.Add(new KeyValuePair<int, string>(item.Key, ((Object)(object)item.Value != (Object)null) ? item.Value.name : ""));
			}
			UkulelePlugin.Log.LogInfo((object)($"Registered Ukulele as Blue powerup id {num} ({allPowerups.Count} powerups total, {__instance.powerupsBlue.Length} in the Blue pool). " + "Every player needs the same set of powerup mods. Fingerprint: " + PowerupIds.Fingerprint(list)));
		}
	}
	internal sealed class UkuleleRunner : MonoBehaviour
	{
		private static UkuleleRunner _instance;

		public static UkuleleRunner 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("MuckUkulele")
				{
					hideFlags = (HideFlags)61
				};
				Object.DontDestroyOnLoad((Object)val);
				_instance = val.AddComponent<UkuleleRunner>();
			}
		}

		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 = UkulelePlugin.Cfg.GiveUkuleleKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				UkulelePowerup.GiveOneLocal();
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "MuckUkulele";

		public const string PLUGIN_NAME = "Ukulele";

		public const string PLUGIN_VERSION = "0.1.2";
	}
}